diff --git a/content/css/main.sass b/content/css/main.sass index 73901d367..d70c3a526 100644 --- a/content/css/main.sass +++ b/content/css/main.sass @@ -128,7 +128,7 @@ body color: $base01 pre, code - font-family: Monaco, monospace + font-family: Incosolata, Monaco, monospace pre &::selection @@ -174,7 +174,7 @@ ol li ul, ol li ol, ul li ol, ul li ul list-style: circle -body, h1, h2, h3, h4, #entete, .tag +body, h1, h2, h3, h4, #entete, .tagname font-family: Georgia, Palatino, "Century Schoolbook L", "Times New Roman", Times, serif line-height: 1.4em @@ -600,12 +600,12 @@ img.clean margin-top: 2em z-index: 9002 -.file +.codefile font-size: 0.8em text-align: right padding-right: 1em margin-right: 0.1 - margin-bottom: 0 + margin-bottom: -1em .flush clear: both @@ -648,9 +648,6 @@ pre overflow-x: auto overflow-y: hidden -.withfile pre - margin-top: 0 - .navigationprev, .navigationnext padding: 0px margin-left: 0.2em @@ -707,7 +704,7 @@ table.impact tr td a, a:visited color: #ECA -.tag +.tagname display: inline cursor: pointer margin-left: 0.5em diff --git a/layouts/article.html b/layouts/article.html index 19f4876cb..771d19f56 100644 --- a/layouts/article.html +++ b/layouts/article.html @@ -14,6 +14,7 @@ + <% languages.each do |lang| @@ -25,6 +26,8 @@ + + diff --git a/lib/blog.rb b/lib/blog.rb index 0167a9be1..afb451500 100644 --- a/lib/blog.rb +++ b/lib/blog.rb @@ -3,7 +3,7 @@ def blogimage(filename,title="no name", divclass=nil) imgpath=blogimagedir + filename if not divclass.nil? - if divclass !~ /\s*/ + if divclass !~ /^\s*$/ cls=%{ class="#{divclass}"} end end diff --git a/lib/syntaxColorize.rb b/lib/syntaxColorize.rb index 802506e43..e1b714e3b 100644 --- a/lib/syntaxColorize.rb +++ b/lib/syntaxColorize.rb @@ -2,7 +2,6 @@ module Nanoc3::Helpers module SyntaxColorize - require 'nanoc3/helpers/capturing' include Nanoc3::Helpers::Capturing def syntax_colorize(lang, type=:ultraviolet, &block) diff --git a/lib/tag.rb b/lib/tag.rb index 4b3ac5bda..9234d3512 100644 --- a/lib/tag.rb +++ b/lib/tag.rb @@ -88,7 +88,7 @@ tagSize.sort{|a,b| a[0].downcase <=> b[0].downcase}.each do |t,s| protected=t.gsub(/\W/,'_') grouped=t.gsub(/&/,'&').gsub(/ /,' ').gsub(/,'<').gsub(/>/,'>') - tagCloud <<= %{#{grouped} } + tagCloud <<= %{#{grouped} } end tagCloud <<= %{
(.+?)
)}m
+ code_rule = %r{(\n?(.+?)
)}m
new_content=content.gsub(code_rule) do |full|
- @lang, @filename, @code = $2, $4, $5
- if @lang =~ /^(zsh|bash|sh|csh|shell)$/
- @lang='shell-unix-generic'
- end
+ @full, @lang, @filename, @code = $1, $2, $4, $5
@codeprefix=''
- @codesuffix=''
if not @filename.nil? and @filename != ""
create_file_for_code
end
- @codeprefix+
- Uv.parse(@code, "xhtml", @lang, false, @config[:ultraviolet_theme])+
- @codesuffix
+ @codeprefix+"\n\n"+protect(@code)+"
\n\n"
end
return new_content
end
@@ -28,13 +27,10 @@ class UltraVioletFilter < Nanoc3::Filter
webpath = @item.path
url = webpath + 'code/' + @filename
- @codeprefix=%{...
`
+that are traditionally used to mark up code examples. Their content is
+marked up by logical pieces with defined class names.
+
+
+### Custom initialization
+
+If you use different markup for code blocks you can initialize them manually
+with `highlightBlock(code, tabReplace)` function. It takes a DOM element
+containing the code to highlight and optionally a string with which to replace
+TAB characters.
+
+Initialization using, for example, jQuery might look like this:
+
+```javascript
+$(document).ready(function() {
+ $('pre code').each(function(i, e) {hljs.highlightBlock(e, ' ')});
+});
+```
+
+If your code container relies on ``) pass `true` into third parameter of `highlightBlock`: + +```javascript +$('div.code').each(function(i, e) {hljs.highlightBlock(e, null, true)}); +``` + +### Styling + +Elements of code marked up with classes can be styled as desired: + +```css +.comment { + color: gray; +} + +.keyword { + font-weight: bold; +} + +.python .string { + color: blue; +} + +.html .atribute .value { + color: green; +} +``` + +Highlight.js comes with several style themes located in "styles" directory that +can be used directly or as a base for your own experiments. + +**Note**: provided styles work for code defined inside `"}else{N+=L[0]}P=O.lR.lastIndex;L=O.lR.exec(M)}return N+M.substr(P,M.length-P)}function K(r,M){if(M.sL&&d[M.sL]){var L=e(M.sL,r);t+=L.keyword_count;return L.value}else{return F(r,M)}}function I(M,r){var L=M.cN?'':"";if(M.rB){q+=L;M.buffer=""}else{if(M.eB){q+=m(r)+L;M.buffer=""}else{q+=L;M.buffer=r}}C.push(M);B+=M.r}function E(O,L,Q){var R=C[C.length-1];if(Q){q+=K(R.buffer+O,R);return false}var M=z(L,R);if(M){q+=K(R.buffer+O,R);I(M,L);return M.rB}var r=w(C.length-1,L);if(r){var N=R.cN?"":"";if(R.rE){q+=K(R.buffer+O,R)+N}else{if(R.eE){q+=K(R.buffer+O,R)+N+m(L)}else{q+=K(R.buffer+O+L,R)+N}}while(r>1){N=C[C.length-2].cN?"":"";q+=N;r--;C.length--}var P=C[C.length-1];C.length--;C[C.length-1].buffer="";if(P.starts){I(P.starts,"")}return R.rE}if(x(L,R)){throw"Illegal"}}var H=d[J];var C=[H.dM];var B=0;var t=0;var q="";try{var y,v=0;H.dM.buffer="";do{y=s(D,v);var u=E(y[0],y[1],y[2]);v+=y[0].length;if(!u){v+=y[1].length}}while(!y[2]);if(C.length>1){throw"Illegal"}return{r:B,keyword_count:t,value:q}}catch(G){if(G=="Illegal"){return{r:0,keyword_count:0,value:m(D)}}else{throw G}}}function f(t){var r={keyword_count:0,r:0,value:m(t)};var q=r;for(var p in d){if(!d.hasOwnProperty(p)){continue}var s=e(p,t);s.language=p;if(s.keyword_count+s.r>q.keyword_count+q.r){q=s}if(s.keyword_count+s.r>r.keyword_count+r.r){q=r;r=s}}if(q.language){r.second_best=q}return r}function h(r,q,p){if(q){r=r.replace(/^((<[^>]+>|\t)+)/gm,function(t,w,v,u){return w.replace(/\t/g,q)})}if(p){r=r.replace(/\n/g,"` blocks. If you use +custom markup you should modify styles accordingly. + +For full reference list of classes see [classref.txt][cr]. + +[cr]: http://github.com/isagalaev/highlight.js/blob/master/classref.txt + + +## Export + +File export.html contains a little program that allows you to paste in a code +snippet and then copy and paste the resulting HTML code generated by the +highlighter. This is useful in situations when you can't use the script itself +on a site. + + +## Heuristics + +Autodetection of a code's language is done using a simple heuristic: +the program tries to highlight a fragment with all available languages and +counts all syntactic structures that it finds along the way. The language +with greatest count wins. + +This means that in short fragments the probability of an error is high +(and it really happens sometimes). In this cases you can set the fragment's +language explicitly by assigning a class to the `` element: + +```html +
+``` + +You can use class names recommended in HTML5: "language-html", +"language-php". Classes also can be assigned to the `...
` element. + +To disable highlighting of a fragment altogether use "no-highlight" class: + +```html ++``` + +## Meta + +- Version: 6.2 +- URL: http://softwaremaniacs.org/soft/highlight/en/ +- Author: Ivan Sagalaev (...
) + +For the license terms see LICENSE files. +For the list of contributors see AUTHORS.en.txt file. diff --git a/output/Scratch/js/highlight/README.ru.md b/output/Scratch/js/highlight/README.ru.md new file mode 100644 index 000000000..ec0c156d6 --- /dev/null +++ b/output/Scratch/js/highlight/README.ru.md @@ -0,0 +1,144 @@ +# Highlight.js + +Highlight.js нужен для подсветки синтаксиса в примерах кода в блогах, +форумах и вообще на любых веб-страницах. Пользоваться им очень просто, +потому что работает он автоматически: сам находит блоки кода, сам +определяет язык, сам подсвечивает. + +Автоопределением языка можно управлять, когда оно не справляется само (см. +дальше "Эвристика"). + + +## Подключение и использование + +В загруженном архиве лежит файл "highlight.pack.js" -- полная сжатая версия +библиотеки для работы. Все несжатые исходные файлы также есть в пакете, поэтому +не стесняйтесь в них смотреть! + +Скрипт подключается одним файлом и одним вызовом инициализирующей +функции: + +```html + + +``` + +Также вы можете заменить символы TAB ('\x09'), используемые для отступов, на +фиксированное количество пробелов или на отдельный ``, чтобы задать ему +какой-нибудь специальный стиль: + +```html + +``` + +Дальше скрипт ищет на странице конструкции ` `, +которые традиционно используются для написания кода, и код в них +размечается на куски, помеченные разными значениями классов. + + +### Инициализация вручную + +Если вы используете другие теги для блоков кода, вы можете инициализировать их +явно с помощью функции `highlightBlock(code, tabReplace)`. Она принимает +DOM-элемент с текстом расцвечиваемого кода и опционально - строчку для замены +символов TAB. + +Например с использованием jQuery код инициализации может выглядеть так: + +```javascript +$(document).ready(function() { + $('pre code').each(function(i, e) {hljs.highlightBlock(e, ' ')}); +}); +``` + +Если ваш блок кода использует `...
` вместо переводов строки (т.е. если это не +``), передайте `true` третьим параметром в `highlightBlock`: + +```javascript +$('div.code').each(function(i, e) {hljs.highlightBlock(e, null, true)}); +``` + +### Выбор стилей + +Размеченным классами элементам кода можно задать желаемые стили например так: + +```css +.comment { + color: gray; +} + +.keyword { + font-weight: bold; +} + +.python .string { + color: blue; +} + +.html .atribute .value { + color: green; +} +``` + +В комплекте с highlight.js идут несколько стилевых тем в директории styles, +которые можно использовать напрямую или как основу для собственных экспериментов. + +**Внимание**: приложенные стили работают для кода, определённого внутри блоков +`':''; + result += markup; + end_level--; + modes.length--; + } + var last_ended_mode = modes[modes.length - 1]; + modes.length--; + modes[modes.length - 1].buffer = ''; + if (last_ended_mode.starts) { + startNewMode(last_ended_mode.starts, ''); + } + return current_mode.returnEnd; + } + + if (isIllegal(lexem, current_mode)) + throw 'Illegal'; + } + + var language = languages[language_name]; + var modes = [language.defaultMode]; + var relevance = 0; + var keyword_count = 0; + var result = ''; + try { + var mode_info, index = 0; + language.defaultMode.buffer = ''; + do { + mode_info = eatModeChunk(value, index); + var return_lexem = processModeInfo(mode_info[0], mode_info[1], mode_info[2]); + index += mode_info[0].length; + if (!return_lexem) { + index += mode_info[1].length; + } + } while (!mode_info[2]); + if(modes.length > 1) + throw 'Illegal'; + return { + relevance: relevance, + keyword_count: keyword_count, + value: result + }; + } catch (e) { + if (e == 'Illegal') { + return { + relevance: 0, + keyword_count: 0, + value: escape(value) + }; + } else { + throw e; + } + } + } + + /* + Highlighting with language detection. Accepts a string with the code to + highlight. Returns an object with the following properties: + + - language (detected language) + - relevance (int) + - keyword_count (int) + - value (an HTML string with highlighting markup) + - second_best (object with the same structure for second-best heuristically + detected language, may be absent) + + */ + function highlightAuto(text) { + var result = { + keyword_count: 0, + relevance: 0, + value: escape(text) + }; + var second_best = result; + for (var key in languages) { + if (!languages.hasOwnProperty(key)) + continue; + var current = highlight(key, text); + current.language = key; + if (current.keyword_count + current.relevance > second_best.keyword_count + second_best.relevance) { + second_best = current; + } + if (current.keyword_count + current.relevance > result.keyword_count + result.relevance) { + second_best = result; + result = current; + } + } + if (second_best.language) { + result.second_best = second_best; + } + return result; + } + + /* + Post-processing of the highlighted markup: + + - replace TABs with something more useful + - replace real line-breaks with '`. Если вы используете собственную разметку, стили нужно исправить +соответствующим образом. + +Полный список классов приведён в файле [crossref.txt][cr]. + +[cr]: http://github.com/isagalaev/highlight.js/blob/master/classref.txt + + +## Экспорт + +В файле export.html находится небольшая программка, которая показывает и дает +скопировать непосредственно HTML-код подсветки для любого заданного фрагмента кода. +Это может понадобится например на сайте, на котором нельзя подключить сам скрипт +highlight.js. + + +## Эвристика + +Определение языка, на котором написан фрагмент, делается с помощью +довольно простой эвристики: программа пытается расцветить фрагмент всеми +языками подряд, и для каждого языка считает количество подошедших +синтаксически конструкций и ключевых слов. Для какого языка нашлось больше, +тот и выбирается. + +Это означает, что в коротких фрагментах высока вероятность ошибки, что +периодически и случается. Чтобы указать язык фрагмента явно, надо написать +его название в виде класса к элементу ``: + +```html +
+``` + +Можно использовать рекомендованные в HTML5 названия классов: +"language-html", "language-php". Также можно назначать классы на элемент +`...
`. + +Чтобы запретить расцветку фрагмента вообще, используется класс "no-highlight": + +```html ++``` + +## Координаты + +- Версия: 6.2 +- URL: http://softwaremaniacs.org/soft/highlight/ +- Автор: Иван Сагалаев (...
) + +Лицензионное соглашение читайте в файле LICENSE. +Список соавторов читайте в файле AUTHORS.ru.txt diff --git a/output/Scratch/js/highlight/classref.txt b/output/Scratch/js/highlight/classref.txt new file mode 100644 index 000000000..b7707f418 --- /dev/null +++ b/output/Scratch/js/highlight/classref.txt @@ -0,0 +1,497 @@ +This is a full list of available classes corresponding to languages' +syntactic structures. The parentheses after language name contain identifiers +used as class names in ` ` element. + +Python ("python"): + + keyword keyword + built_in built-in objects (None, False, True and Ellipsis) + number number + string string (of any type) + comment comment + decorator @-decorator for functions + function function header "def some_name(...):" + class class header "class SomeName(...):" + title name of a function or a class inside a header + params everything inside parentheses in a function's or class' header + +Python profiler results ("profile"): + + number number + string string + builtin builtin function entry + filename filename in an entry + summary profiling summary + header header of table of results + keyword column header + function function name in an entry (including parentheses) + title actual name of a function in an entry (excluding parentheses) + +Ruby ("ruby"): + + keyword keyword + string string + subst in-string substitution (#{...}) + comment comment + yardoctag YARD tag + function function header "def some_name(...):" + class class header "class SomeName(...):" + title name of a function or a class inside a header + parent name of a parent class + symbol symbol + instancevar instance variable + +Perl ("perl"): + + keyword keyword + comment comment + number number + string string + regexp regular expression + sub subroutine header (from "sub" till "{") + variable variable starting with "$", "%", "@" + operator operator + pod plain old doc + +PHP ("php"): + + keyword keyword + number number + string string (of any type) + comment comment + phpdoc phpdoc params in comments + variable variable starting with "$" + preprocessor preprocessor marks: "" + +Scala ("scala"): + + keyword keyword + number number + string string + comment comment + annotaion annotation + javadoc javadoc comment + javadoctag @-tag in javadoc + class class header + title class name inside a header + params everything in parentheses inside a class header + inheritance keywords "extends" and "with" inside class header + +Go language ("go"): + comment comment + string string constant + number number + keyword language keywords + constant true false nil iota + typename built-in plain types (int, string etc.) + built_in built-in functions + +XML ("xml"): + + tag any tag from "<" till ">" + comment comment + pi processing instruction ( ... ?>) + cdata CDATA section + attribute attribute + value attribute's value + +HTML ("html"): + + keyword HTML tag + tag any tag from "<" till ">" + comment comment + doctype declaration + attribute tag's attribute with or without value + value attribute's value + +CSS ("css"): + + tag HTML tag in selectors + id #some_name in selectors + class .some_name in selectors + at_rule @-rule till first "{" or ";" + attr_selector attribute selector (square brackets in a[href^=http://]) + pseudo pseudo classes and elemens (:after, ::after etc.) + comment comment + rules everything from "{" till "}" + property property name inside a rule + value property value inside a rule, from ":" till ";" or + till the end of rule block + number number within a value + string string within a value + hexcolor hex color (#FFFFFF) within a value + function CSS function within a value + params everything between "(" and ")" within a function + important "!important" symbol + +Markdown ("markdown"): + + header header + bullet list bullet + emphasis emphasis + strong strong emphasis + blockquote blockquote + code code + horizontal_rule horizontal rule + link_label link label + link_url link url + +Django ("django"): + + keyword HTML tag in HTML, default tags and default filters in templates + tag any tag from "<" till ">" + comment comment + doctype declaration + attribute tag's attribute with or withou value + value attribute's value + template_tag template tag {% .. %} + variable template variable {{ .. }} + template_comment template comment, both {# .. #} and {% comment %} + filter filter from "|" till the next filter or the end of tag + argument filter argument + +JavaScript ("javascript"): + + keyword keyword + comment comment + number number + literal special literal: "true", "false" and "null" + string string + regexp regular expression + function header of a function + title name of a function inside a header + params parentheses and everything inside them in a function's header + +CoffeeScript ("coffeescript"): + + keyword keyword + comment comment + number number + literal special literal: "true", "false" and "null" + string string + regexp regular expression + function header of a function + title name of a function variable inside a header + params parentheses and everything inside them in a function's header + +VBScript ("vbscript"): + + keyword keyword + number number + string string + comment comment + built_in built-in function + +Lua ("lua"): + + keyword keyword + number number + string string + comment comment + built_in built-in operator + function header of a function + title name of a function inside a header + params everything inside parentheses in a function's header + long_brackets multiline string in [=[ .. ]=] + +Delphi ("delphi"): + + keyword keyword + comment comment (of any type) + number number + string string + function header of a function, procedure, constructor and destructor + title name of a function, procedure, constructor or destructor + inside a header + params everything inside parentheses in a function's header + class class' body from "= class" till "end;" + +Java ("java"): + + keyword keyword + number number + string string + comment commment + annotaion annotation + javadoc javadoc comment + class class header from "class" till "{" + title class name inside a header + params everything in parentheses inside a class header + inheritance keywords "extends" and "implements" inside class header + +C++ ("cpp"): + + keyword keyword + number number + string string and character + comment comment + preprocessor preprocessor directive + stl_container instantiation of STL containers ("vector<...>") + +Objective C ("objectivec"): + keyword keyword + built_in Cocoa/Cocoa Touch constants and classes + number number + string string + comment comment + preprocessor preprocessor directive + class interface/implementation, protocol and forward class declaration + +Vala ("vala"): + + keyword keyword + number number + string string + comment comment + class class definitions + title in class definition + constant ALL_UPPER_CASE + +C# ("cs"): + + keyword keyword + number number + string string + comment commment + xmlDocTag xmldoc tag ("///", "", "<..>") + +RenderMan RSL ("rsl"): + + keyword keyword + number number + string string (including @"..") + comment comment + preprocessor preprocessor directive + shader sahder keywords + shading shading keywords + built_in built-in function + +RenderMan RIB ("rib"): + + keyword keyword + number number + string string + comment comment + commands command + +Maya Embedded Language ("mel"): + + keyword keyword + number number + string string + comment comment + variable variable + +SQL ("sql"): + + keyword keyword (mostly SQL'92 and SQL'99) + number number + string string (of any type: "..", '..', `..`) + comment comment + aggregate aggregate function + +Smalltalk ("smalltalk"): + + keyword keyword + number number + string string + comment commment + symbol symbol + array array + class name of a class + char char + localvars block of local variables + +Lisp ("lisp"): + + keyword keyword + number number + string string + comment commment + variable variable + literal b, t and nil + list non-quoted list + title first symbol in a non-quoted list + body remainder of the non-quoted list + quoted quoted list, both "(quote .. )" and "'(..)" + +Ini ("ini"): + + title title of a section + value value of a setting of any type + string string + number number + keyword boolean value keyword + +Apache ("apache"): + + keyword keyword + number number + comment commment + literal On and Off + sqbracket variables in rewrites "%{..}" + cbracket options in rewrites "[..]" + tag begin and end of a configuration section + +Nginx ("nginx"): + + keyword keyword + string string + number number + comment comment + built_in built-in constant + variable $-variable + +Diff ("diff"): + + header file header + chunk chunk header within a file + addition added lines + deletion deleted lines + change changed lines + +DOS ("dos"): + + keyword keyword + flow batch control keyword + stream DOS special files ("con", "prn", ...) + winutils some commands (see dos.js specifically) + envvar environment variables + +Bash ("bash"): + + keyword keyword + string string + number number + comment comment + literal special literal: "true" и "false" + variable variable + shebang script interpreter header + +CMake ("cmake") + + keyword keyword + number number + string string + comment commment + envvar $-variable + +Axapta ("axapta"): + + keyword keyword + number number + string string + comment commment + class class header from "class" till "{" + title class name inside a header + params everything in parentheses inside a class header + inheritance keywords "extends" and "implements" inside class header + preprocessor preprocessor directive + +1C ("1c"): + + keyword keyword + number number + date date + string string + comment commment + function header of function or procudure + title function name inside a header + params everything in parentheses inside a function header + preprocessor preprocessor directive + +AVR assembler ("avrasm"): + + keyword keyword + built_in pre-defined register + number number + string string + comment commment + label label + preprocessor preprocessor directive + localvars substitution in .macro + +VHDL ("vhdl") + + keyword keyword + number number + string string + comment commment + literal signal logical value + +Parser3 ("parser3"): + + keyword keyword + number number + comment commment + variable variable starting with "$" + preprocessor preprocessor directive + title user-defined name starting with "@" + +TeX ("tex"): + + comment comment + number number + command command + parameter parameter + formula formula + special special symbol + +Haskell ("haskell"): + + keyword keyword + built_in built-in typeclass/functions (Bool, Int) + number number + string string + comment comment + class type classes and other data types + title function name + label type class name + +Erlang ("erlang"): + + comment comment + string string + number number + keyword keyword + record_name record access (#record_name) + title name of declaration function + variable variable (starts with capital letter or with _) + pp.keywords module's attribute (-attribute) + function_name atom or atom:atom in case of function call + +Rust ("rust"): + + comment comment + string string + number number + keyword keyword + title name of declaration + preprocessor preprocessor directive + +ActionScript ("actionscript"): + + comment comment + string string + number number + keyword keywords + literal literal + reserved reserved keyword + title name of declaration (package, class or function) + preprocessor preprocessor directive (import, include) + type type of returned value (for functions) + package package (named or not) + class class/interface + function function + param params of function + rest_arg rest argument of function + +Matlab ("matlab"): + + comment comment + string string + number number + keyword keyword + title function name + function function + param params of function diff --git a/output/Scratch/js/highlight/export.html b/output/Scratch/js/highlight/export.html new file mode 100644 index 000000000..86ac89284 --- /dev/null +++ b/output/Scratch/js/highlight/export.html @@ -0,0 +1,87 @@ + + + + + + + +
Highlited code export + + + + + + + + + ++
++ ++ + + +Write a code snippet +Get HTML to paste anywhere (for actual styles and colors see sample.css) ++
+ + + Export script: Vladimir Gubarkov+ ++ +
+ Highlighting: highlight.js + + + diff --git a/output/Scratch/js/highlight/highlight.js b/output/Scratch/js/highlight/highlight.js new file mode 100644 index 000000000..72fbc3a46 --- /dev/null +++ b/output/Scratch/js/highlight/highlight.js @@ -0,0 +1,643 @@ +/* +Syntax highlighting with language autodetection. +http://softwaremaniacs.org/soft/highlight/ +*/ + +var hljs = new function() { + + /* Utility functions */ + + function escape(value) { + return value.replace(/&/gm, '&').replace(/'; + } + + while (stream1.length || stream2.length) { + var current = selectStream().splice(0, 1)[0]; + result += escape(value.substr(processed, current.offset - processed)); + processed = current.offset; + if ( current.event == 'start') { + result += open(current.node); + nodeStack.push(current.node); + } else if (current.event == 'stop') { + var node, i = nodeStack.length; + do { + i--; + node = nodeStack[i]; + result += ('' + node.nodeName.toLowerCase() + '>'); + } while (node != current.node); + nodeStack.splice(i, 1); + while (i < nodeStack.length) { + result += open(nodeStack[i]); + i++; + } + } + } + return result + escape(value.substr(processed)); + } + + /* Initialization */ + + function compileModes() { + + function compileMode(mode, language, is_default) { + if (mode.compiled) + return; + var group; + + if (!is_default) { + mode.beginRe = langRe(language, mode.begin ? mode.begin : '\\B|\\b'); + if (!mode.end && !mode.endsWithParent) + mode.end = '\\B|\\b'; + if (mode.end) + mode.endRe = langRe(language, mode.end); + } + if (mode.illegal) + mode.illegalRe = langRe(language, mode.illegal); + if (mode.relevance === undefined) + mode.relevance = 1; + if (mode.keywords) { + mode.lexemsRe = langRe(language, mode.lexems || hljs.IDENT_RE, true); + for (var className in mode.keywords) { + if (!mode.keywords.hasOwnProperty(className)) + continue; + if (mode.keywords[className] instanceof Object) { + group = mode.keywords[className]; + } else { + group = mode.keywords; + className = 'keyword'; + } + for (var keyword in group) { + if (!group.hasOwnProperty(keyword)) + continue; + mode.keywords[keyword] = [className, group[keyword]]; + } + } + } + if (!mode.contains) { + mode.contains = []; + } + // compiled flag is set before compiling submodes to avoid self-recursion + // (see lisp where quoted_list contains quoted_list) + mode.compiled = true; + for (var i = 0; i < mode.contains.length; i++) { + if (mode.contains[i] == 'self') { + mode.contains[i] = mode; + } + compileMode(mode.contains[i], language, false); + } + if (mode.starts) { + compileMode(mode.starts, language, false); + } + } + + for (var i in languages) { + if (!languages.hasOwnProperty(i)) + continue; + compileMode(languages[i].defaultMode, languages[i], true); + } + } + + /* + Core highlighting function. Accepts a language name and a string with the + code to highlight. Returns an object with the following properties: + + - relevance (int) + - keyword_count (int) + - value (an HTML string with highlighting markup) + + */ + function highlight(language_name, value) { + if (!compileModes.called) { + compileModes(); + compileModes.called = true; + } + + function subMode(lexem, mode) { + for (var i = 0; i < mode.contains.length; i++) { + if (mode.contains[i].beginRe.test(lexem)) { + return mode.contains[i]; + } + } + } + + function endOfMode(mode_index, lexem) { + if (modes[mode_index].end && modes[mode_index].endRe.test(lexem)) + return 1; + if (modes[mode_index].endsWithParent) { + var level = endOfMode(mode_index - 1, lexem); + return level ? level + 1 : 0; + } + return 0; + } + + function isIllegal(lexem, mode) { + return mode.illegal && mode.illegalRe.test(lexem); + } + + function compileTerminators(mode, language) { + var terminators = []; + + for (var i = 0; i < mode.contains.length; i++) { + terminators.push(mode.contains[i].begin); + } + + var index = modes.length - 1; + do { + if (modes[index].end) { + terminators.push(modes[index].end); + } + index--; + } while (modes[index + 1].endsWithParent); + + if (mode.illegal) { + terminators.push(mode.illegal); + } + + return langRe(language, '(' + terminators.join('|') + ')', true); + } + + function eatModeChunk(value, index) { + var mode = modes[modes.length - 1]; + if (!mode.terminators) { + mode.terminators = compileTerminators(mode, language); + } + mode.terminators.lastIndex = index; + var match = mode.terminators.exec(value); + if (match) + return [value.substr(index, match.index - index), match[0], false]; + else + return [value.substr(index), '', true]; + } + + function keywordMatch(mode, match) { + var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0]; + var value = mode.keywords[match_str]; + if (value && value instanceof Array) + return value; + return false; + } + + function processKeywords(buffer, mode) { + buffer = escape(buffer); + if (!mode.keywords) + return buffer; + var result = ''; + var last_index = 0; + mode.lexemsRe.lastIndex = 0; + var match = mode.lexemsRe.exec(buffer); + while (match) { + result += buffer.substr(last_index, match.index - last_index); + var keyword_match = keywordMatch(mode, match); + if (keyword_match) { + keyword_count += keyword_match[1]; + result += '' + match[0] + ''; + } else { + result += match[0]; + } + last_index = mode.lexemsRe.lastIndex; + match = mode.lexemsRe.exec(buffer); + } + return result + buffer.substr(last_index, buffer.length - last_index); + } + + function processBuffer(buffer, mode) { + if (mode.subLanguage && languages[mode.subLanguage]) { + var result = highlight(mode.subLanguage, buffer); + keyword_count += result.keyword_count; + return result.value; + } else { + return processKeywords(buffer, mode); + } + } + + function startNewMode(mode, lexem) { + var markup = mode.className?'':''; + if (mode.returnBegin) { + result += markup; + mode.buffer = ''; + } else if (mode.excludeBegin) { + result += escape(lexem) + markup; + mode.buffer = ''; + } else { + result += markup; + mode.buffer = lexem; + } + modes.push(mode); + relevance += mode.relevance; + } + + function processModeInfo(buffer, lexem, end) { + var current_mode = modes[modes.length - 1]; + if (end) { + result += processBuffer(current_mode.buffer + buffer, current_mode); + return false; + } + + var new_mode = subMode(lexem, current_mode); + if (new_mode) { + result += processBuffer(current_mode.buffer + buffer, current_mode); + startNewMode(new_mode, lexem); + return new_mode.returnBegin; + } + + var end_level = endOfMode(modes.length - 1, lexem); + if (end_level) { + var markup = current_mode.className?'':''; + if (current_mode.returnEnd) { + result += processBuffer(current_mode.buffer + buffer, current_mode) + markup; + } else if (current_mode.excludeEnd) { + result += processBuffer(current_mode.buffer + buffer, current_mode) + markup + escape(lexem); + } else { + result += processBuffer(current_mode.buffer + buffer + lexem, current_mode) + markup; + } + while (end_level > 1) { + markup = modes[modes.length - 2].className?'
' for non-pre containers + + */ + function fixMarkup(value, tabReplace, useBR) { + if (tabReplace) { + value = value.replace(/^((<[^>]+>|\t)+)/gm, function(match, p1, offset, s) { + return p1.replace(/\t/g, tabReplace); + }); + } + if (useBR) { + value = value.replace(/\n/g, '
'); + } + return value; + } + + /* + Applies highlighting to a DOM node containing code. Accepts a DOM node and + two optional parameters for fixMarkup. + */ + function highlightBlock(block, tabReplace, useBR) { + var text = blockText(block, useBR); + var language = blockLanguage(block); + var result, pre; + if (language == 'no-highlight') + return; + if (language) { + result = highlight(language, text); + } else { + result = highlightAuto(text); + language = result.language; + } + var original = nodeStream(block); + if (original.length) { + pre = document.createElement('pre'); + pre.innerHTML = result.value; + result.value = mergeStreams(original, nodeStream(pre), text); + } + result.value = fixMarkup(result.value, tabReplace, useBR); + + var class_name = block.className; + if (!class_name.match('(\\s|^)(language-)?' + language + '(\\s|$)')) { + class_name = class_name ? (class_name + ' ' + language) : language; + } + if (/MSIE [678]/.test(navigator.userAgent) && block.tagName == 'CODE' && block.parentNode.tagName == 'PRE') { + // This is for backwards compatibility only. IE needs this strange + // hack becasue it cannot just cleanly replaceblock contents. + pre = block.parentNode; + var container = document.createElement('div'); + container.innerHTML = '
'; + block = container.firstChild.firstChild; + container.firstChild.className = pre.className; + pre.parentNode.replaceChild(container.firstChild, pre); + } else { + block.innerHTML = result.value; + } + block.className = class_name; + block.result = { + language: language, + kw: result.keyword_count, + re: result.relevance + }; + if (result.second_best) { + block.second_best = { + language: result.second_best.language, + kw: result.second_best.keyword_count, + re: result.second_best.relevance + }; + } + } + + /* + Applies highlighting to all' + result.value + '
blocks on a page. + */ + function initHighlighting() { + if (initHighlighting.called) + return; + initHighlighting.called = true; + var pres = document.getElementsByTagName('pre'); + for (var i = 0; i < pres.length; i++) { + var code = findCode(pres[i]); + if (code) + highlightBlock(code, hljs.tabReplace); + } + } + + /* + Attaches highlighting to the page load event. + */ + function initHighlightingOnLoad() { + if (window.addEventListener) { + window.addEventListener('DOMContentLoaded', initHighlighting, false); + window.addEventListener('load', initHighlighting, false); + } else if (window.attachEvent) + window.attachEvent('onload', initHighlighting); + else + window.onload = initHighlighting; + } + + var languages = {}; // a shortcut to avoid writing "this." everywhere + + /* Interface definition */ + + this.LANGUAGES = languages; + this.highlight = highlight; + this.highlightAuto = highlightAuto; + this.fixMarkup = fixMarkup; + this.highlightBlock = highlightBlock; + this.initHighlighting = initHighlighting; + this.initHighlightingOnLoad = initHighlightingOnLoad; + + // Common regexps + this.IDENT_RE = '[a-zA-Z][a-zA-Z0-9_]*'; + this.UNDERSCORE_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_]*'; + this.NUMBER_RE = '\\b\\d+(\\.\\d+)?'; + this.C_NUMBER_RE = '\\b(0[xX][a-fA-F0-9]+|(\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float + this.BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b... + this.RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~'; + + // Common modes + this.BACKSLASH_ESCAPE = { + begin: '\\\\.', relevance: 0 + }; + this.APOS_STRING_MODE = { + className: 'string', + begin: '\'', end: '\'', + illegal: '\\n', + contains: [this.BACKSLASH_ESCAPE], + relevance: 0 + }; + this.QUOTE_STRING_MODE = { + className: 'string', + begin: '"', end: '"', + illegal: '\\n', + contains: [this.BACKSLASH_ESCAPE], + relevance: 0 + }; + this.C_LINE_COMMENT_MODE = { + className: 'comment', + begin: '//', end: '$' + }; + this.C_BLOCK_COMMENT_MODE = { + className: 'comment', + begin: '/\\*', end: '\\*/' + }; + this.HASH_COMMENT_MODE = { + className: 'comment', + begin: '#', end: '$' + }; + this.NUMBER_MODE = { + className: 'number', + begin: this.NUMBER_RE, + relevance: 0 + }; + this.C_NUMBER_MODE = { + className: 'number', + begin: this.C_NUMBER_RE, + relevance: 0 + }; + this.BINARY_NUMBER_MODE = { + className: 'number', + begin: this.BINARY_NUMBER_RE, + relevance: 0 + }; + + // Utility functions + this.inherit = function(parent, obj) { + var result = {} + for (var key in parent) + result[key] = parent[key]; + if (obj) + for (var key in obj) + result[key] = obj[key]; + return result; + } +}(); diff --git a/output/Scratch/js/highlight/highlight.pack.js b/output/Scratch/js/highlight/highlight.pack.js new file mode 100644 index 000000000..b0b5859e4 --- /dev/null +++ b/output/Scratch/js/highlight/highlight.pack.js @@ -0,0 +1 @@ +var hljs=new function(){function m(p){return p.replace(/&/gm,"&").replace(/"}while(y.length||z.length){var v=u().splice(0,1)[0];w+=m(x.substr(r,v.offset-r));r=v.offset;if(v.event=="start"){w+=s(v.node);t.push(v.node)}else{if(v.event=="stop"){var p,q=t.length;do{q--;p=t[q];w+=(""+p.nodeName.toLowerCase()+">")}while(p!=v.node);t.splice(q,1);while(q..
'+L[0]+"
"+w.value+"
";u=v.firstChild.firstChild;v.firstChild.cN=r.cN;r.parentNode.replaceChild(v.firstChild,r)}else{u.innerHTML=w.value}u.className=t;u.result={language:s,kw:w.keyword_count,re:w.r};if(w.second_best){u.second_best={language:w.second_best.language,kw:w.second_best.keyword_count,re:w.second_best.r}}}function k(){if(k.called){return}k.called=true;var r=document.getElementsByTagName("pre");for(var p=0;pThis is a demo/test page showing all languages supported by highlight.js. +Most snippets do not contain working code :-). + +
...
+Python + |
+
+
+
+ |
---|---|
Python's profiler output + |
+
+
+ |
Ruby + |
+
+
+ |
Perl + |
+
+
+ |
PHP + |
+
+
+ |
Scala + |
+
+
+ |
Go + |
+
+
+ |
XML + |
+
+
+ |
HTML (with inline css and javascript) + |
+
+
+ |
Markdown + |
+
+
+
+ |
Django templates + |
+
+
+ |
CSS + |
+
+
+ |
JavaScript + |
+
+
+ |
CoffeeScript + |
+
+
+ |
ActionScript + |
+
+
+ |
VBScript + |
+
+
+ |
Lua + |
+
+
+ |
Delphi + |
+
+
+ |
Java + |
+
+
+ |
C++ + |
+
+
+ |
Objective C + |
+
+
+
+ |
Vala + |
+
+
+ |
C# + |
+
+
+ |
RenderMan RSL + |
+
+
+ |
RenderMan RIB + |
+
+
+ |
MEL (Maya Embedded Language) + |
+
+
+ |
SQL + |
+
+
+ |
SmallTalk + |
+
+
+ |
Lisp + |
+
+
+ |
Ini file + |
+
+
+ |
Apache + |
+
+
+ |
nginx + |
+
+
+ |
Diff + |
+
+
+ |
DOS batch files + |
+
+
+ |
Bash + |
+
+
+ |
CMake + |
+
+
+ |
Axapta + |
+
+
+ |
1С + |
+
+
+ |
AVR Assembler + |
+
+
+ |
VHDL + |
+
+
+ |
Parser 3 + |
+
+
+ |
TeX + |
+
+
+
+ |
Haskell + |
+
+
+
+ |
Erlang + |
+
+
+ |
Erlang REPL + |
+
+
+ |
Rust + |
+
+
+
+ |
Matlab + |
+
+
+ |
Explicit Python highlighting + |
+
+
+ |
---|---|
Language set on <pre> + |
+
+
+ |
HTML5-style language class (language-python) + |
+
+
+ |
Replacing TAB with 4 spaces + |
+
+
+ |
Custom markup + |
+
+
+ |
Custom markup + TAB replacement + |
+
+
+ |
Non-pre container + |
+ for x in [1, 2, 3]:
+
+
+ + count(x) + |
Disabled highlighting + |
+
+
+ |