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 的動作,雖然還不是很完整,但整體的效果比原生好多了。

  1. /**=[ CSS ]===========================================*/ 
  2. dp.sh.Brushes.CSS = function(){ 
  3.    // 樣式定義 
  4.    this.CssClass = 'dp-css'; 
  5.    this.Style = '.dp-css .value{color:blue;}' + 
  6.                  '.dp-css .important{color:red;font-weight:bold;}'+ 
  7.                  '.dp-css .keyword{color:#7F0055;font-weight:bold;}'+ 
  8.                  '.dp-css .func{color:#F55;font-weight:normal;}'; 
  9. }; 
  10.  
  11. dp.sh.Brushes.CSS.prototype = new dp.sh.Highlighter(); 
  12. dp.sh.Brushes.CSS.Aliases   = ['css']; 
  13.  
  14. dp.sh.Brushes.CSS.prototype.ProcessRegexList = function(){ 
  15.    function push(array, value){ 
  16.        array[array.length] = value; 
  17.    } 
  18.    var match1,match2,regex1,regex2; 
  19.  
  20.    /* 加入註解解析 */ 
  21.    this.GetMatches(dp.sh.RegexLib.MultiLineCComments, 'comments'); 
  22.    /* 加入 !important 解析 */ 
  23.    this.GetMatches(new RegExp('!important', 'g'),'important'); 
  24.  
  25.    /* 解析屬性區塊 */ 
  26.    // 匹配 '{' 至 '}' 之間的文字 
  27.    regex1 = new RegExp('\{[^}]+\}', 'gm'); 
  28.    // 匹配 'xxx:xxx[;\n\(!]' 格式的文字 
  29.    regex2 = new RegExp('([:\\w-\.]+)\\s*:\\s*([^;\n\(!]+)[;\n\(!]', 'gm'); 
  30.    while((match1 = regex1.exec(this.code))){ 
  31.        while((match2 = regex2.exec(match1[0]))){ 
  32.            if(!match2[1]){continue;} 
  33.            // 匹配屬性名稱 
  34.            push(this.matches, new dp.sh.Match( 
  35.                match2[1],  
  36.                match1.index+match2.index,  
  37.                'func' 
  38.            )); 
  39.  
  40.            // 匹配屬性值 
  41.            if(match2[2]){ 
  42.                push(this.matches,new dp.sh.Match( 
  43.                    match2[2],  
  44.                    match1.index+match2.index+match2[0].indexOf(match2[2]),  
  45.                    'value' 
  46.                )); 
  47.            } 
  48.        } 
  49.    } 
  50.  
  51.    /* 解析選擇器區塊 */ 
  52.    // 匹配 'xxx[,\{\n]' 格式的文字 
  53.    regex1 = new RegExp('^([\\s\\w\.#*:+-]+)[,\{\n]', 'gm'); 
  54.    while((match1 = regex1.exec(this.code))){ 
  55.        if(!match1[1]){continue;} 
  56.        push(this.matches, new dp.sh.Match( 
  57.            match1[1],  
  58.            match1.index,  
  59.            'keyword' 
  60.        )); 
  61.    } 
  62. }; 


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

0 回應: