Highlight.js自定义语言定义

时间:2015-02-20 13:41:49

标签: javascript json syntax-highlighting highlight.js

我正在尝试为 highlight.js 创建语言定义。 但它不起作用。我有一个例子。

在此示例中,我尝试创建自定义" aaa" 语言,这与JSON相同。 registerLanguage函数接收与默认JSON高亮函数相同的函数(来自highlight.js源)。

hljs.listLanguages()显示该语言已注册。

之后,我正在呼叫hljs.highlightBlock(block)

<code class="aaa">强制使用自定义&#34; aaa&#34;语言,在这种情况下,hljs.highlightBlock(block)不会更改内容。

&#13;
&#13;
$(document).ready(function() {
  // registering aaa language (JSON alias)
  // code from https://github.com/isagalaev/highlight.js/blob/master/src/languages/json.js
  hljs.registerLanguage("aaa", function(hljs) {
    var LITERALS = {
      literal: 'true false null'
    };
    var TYPES = [
      hljs.QUOTE_STRING_MODE,
      hljs.C_NUMBER_MODE
    ];
    var VALUE_CONTAINER = {
      className: 'value',
      end: ',',
      endsWithParent: true,
      excludeEnd: true,
      contains: TYPES,
      keywords: LITERALS
    };
    var OBJECT = {
      begin: '{',
      end: '}',
      contains: [{
        className: 'attribute',
        begin: '\\s*"',
        end: '"\\s*:\\s*',
        excludeBegin: true,
        excludeEnd: true,
        contains: [hljs.BACKSLASH_ESCAPE],
        illegal: '\\n',
        starts: VALUE_CONTAINER
      }],
      illegal: '\\S'
    };
    var ARRAY = {
      begin: '\\[',
      end: '\\]',
      contains: [hljs.inherit(VALUE_CONTAINER, {
        className: null
      })], // inherit is also a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
      illegal: '\\S'
    };
    TYPES.splice(TYPES.length, 0, OBJECT, ARRAY);
    return {
      contains: TYPES,
      keywords: LITERALS,
      illegal: '\\S'
    };
  });
  console.log(hljs.listLanguages()); // aaa in the list
  $('pre code').each(function(i, block) {
    hljs.highlightBlock(block);
  });
});
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/tomorrow.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js"></script>
<pre><code class="aaa"> 
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}
</code></pre>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

Highlight.js在构建期间有一个缩小/打包过程,它重命名语言定义对象的字段。这意味着他们在http://highlightjs.readthedocs.org/en/latest/language-guide.html中描述的对象不能使用分布式库。只有在构建时间之前定义的语言才能以这种方式工作。

您可以在minified highlightjs文件中查看registerLanguage的用法,以尝试对字段名称进行反向工程。