Prism:轻量级的 Javascript 代码高亮库

来源:互联网 发布:常用的数据分析方法 编辑:程序博客网 时间:2024/05/16 11:05


Prism 是一个轻量级并且简单易用的 JavaScript 类库,minified 和 gzipped 压缩后只有 1.5kb 大小,即使添加语言定义代码,最大也不会超过 2kb,是目前最小的代码高亮 Javascript 类库

已内置了 HTML\CSS\Javascript 三种语言的高亮支持

目前 Prism 唯一的缺点就是不支持 IE8,看作者的博客介绍,也不想支持 IE8。


 Prism 使 用 

1. 首先在页面的 head 中引入 Prism 的 CSS 样式文件

<link href="prism.css" rel="stylesheet" />

2. 然后在 </body> 标签之前引入 Prism 类库:

<script src="prism.min.js"></script>

3. 添加要高亮显示的代码,要放在 pre 标签中,设置 code 标签的样式类型为代码的类别,如下:

<pre><code class="language-css">p { color: red }</code></pre>

添加 Prism 对 PHP 的支持

默认 Prism 并不支持 PHP 语言的代码高亮,但是如上介绍,Prism 是非常容易扩展的,所以我们通过以下方式增加 PHP 语言的支持:

1. 添加 PHP 代码高亮,在 prism.js 添加如下代码:

Prism.languages.php = {'comment': {pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*?(\r?\n|$))/g,lookbehind: true},'deliminator': /(\?>|\?>|<\?php|<\?php)/ig,'variable': /(\$\w+)\b/ig,'string': /("|')(\\?.)*?\1/g,'regex': {pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind: true},'keyword': /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|extends|private|protected|throw)\b/g,'function': /\b(abs|acos|acosh|addcslashes|addslashes|array_change_key_case|array_chunk|array_combine|array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_filter|array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|array_reduce|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|array_values|array_walk|array_walk_recursive|atan|atan2|atanh|base64_decode|base64_encode|base_convert|basename|bcadd|bccomp|bcdiv|bcmod|bcmul|bindec|bindtextdomain|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|ceil|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_exists|closedir|closelog|copy|cos|cosh|count|count_chars|date|decbin|dechex|decoct|deg2rad|delete|ebcdic2ascii|echo|empty|end|ereg|ereg_replace|eregi|eregi_replace|error_log|error_reporting|escapeshellarg|escapeshellcmd|eval|exec|exit|exp|explode|extension_loaded|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filesize|filetype|floatval|flock|floor|flush|fmod|fnmatch|fopen|fpassthru|fprintf|fputcsv|fputs|fread|fscanf|fseek|fsockopen|fstat|ftell|ftok|getallheaders|getcwd|getdate|getenv|gethostbyaddr|gethostbyname|gethostbynamel|getimagesize|getlastmod|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getopt|getprotobyname|getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|gettext|gettimeofday|gettype|glob|gmdate|gmmktime|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|interface_exists|intval|ip2long|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|mkdir|mktime|nl2br|parse_ini_file|parse_str|parse_url|passthru|pathinfo|readlink|realpath|rewind|rewinddir|rmdir|round|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare)\b/g,'constant': /\b(__FILE__|__LINE__|__METHOD__|__FUNCTION__|__CLASS__)\b/g,'boolean': /\b(true|false)\b/g,'number': /\b-?(0x)?\d*\.?\d+\b/g,'operator': /[-+]{1,2}|!|=?<|=?>|={1,2}|(\&){1,2}|\|?\||\?|\*|\//g,'punctuation': /[{}[\];(),.:]/g};

2. 允许在 PHP 代码中内嵌 HTML 代码,在 prism.js 文件添加如下代码:

if (Prism.languages.markup) {Prism.languages.insertBefore('php', 'comment', {'markup': {pattern: /(\?>|\?>)[\w\W]*?(?=(<\?php|<\?php))/ig,lookbehind : true,inside: {'markup': {pattern: /<\/?[\w:-]+\s*[\w\W]*?>/gi,inside: Prism.languages.markup.tag.inside},rest: Prism.languages.php}}});}

3. 上面的代码增加一些新的语言元素名称:function, keyword, variable and constant,但是它们没有定义 CSS 属性,所以在 prism 的 CSS 文件添加:

.token.function, .token.constant {color: #07a;}.token.variable {color: #e90;}.token.deliminator {font-weight:bold;}



1 0
原创粉丝点击