0
|
1 // Minimal framing needed to use CodeMirror-style parsers to highlight
|
|
2 // code. Load this along with tokenize.js, stringstream.js, and your
|
|
3 // parser. Then call highlightText, passing a string as the first
|
|
4 // argument, and as the second argument either a callback function
|
|
5 // that will be called with an array of SPAN nodes for every line in
|
|
6 // the code, or a DOM node to which to append these spans, and
|
|
7 // optionally (not needed if you only loaded one parser) a parser
|
|
8 // object.
|
|
9
|
|
10 // Stuff from util.js that the parsers are using.
|
|
11 var StopIteration = {toString: function() {return "StopIteration"}};
|
|
12
|
|
13 var Editor = {};
|
|
14 var indentUnit = 2;
|
|
15
|
|
16 (function(){
|
|
17 function normaliseString(string) {
|
|
18 var tab = "";
|
|
19 for (var i = 0; i < indentUnit; i++) tab += " ";
|
|
20
|
|
21 string = string.replace(/\t/g, tab).replace(/\u00a0/g, " ").replace(/\r\n?/g, "\n");
|
|
22 var pos = 0, parts = [], lines = string.split("\n");
|
|
23 for (var line = 0; line < lines.length; line++) {
|
|
24 if (line != 0) parts.push("\n");
|
|
25 parts.push(lines[line]);
|
|
26 }
|
|
27
|
|
28 return {
|
|
29 next: function() {
|
|
30 if (pos < parts.length) return parts[pos++];
|
|
31 else throw StopIteration;
|
|
32 }
|
|
33 };
|
|
34 }
|
|
35
|
|
36 window.highlightText = function(string, callback, parser) {
|
|
37 parser = (parser || Editor.Parser).make(stringStream(normaliseString(string)));
|
|
38 var line = [];
|
|
39 if (callback.nodeType == 1) {
|
|
40 var node = callback;
|
|
41 callback = function(line) {
|
|
42 for (var i = 0; i < line.length; i++)
|
|
43 node.appendChild(line[i]);
|
|
44 node.appendChild(document.createElement("br"));
|
|
45 };
|
|
46 }
|
|
47
|
|
48 try {
|
|
49 while (true) {
|
|
50 var token = parser.next();
|
|
51 if (token.value == "\n") {
|
|
52 callback(line);
|
|
53 line = [];
|
|
54 }
|
|
55 else {
|
|
56 var span = document.createElement("span");
|
|
57 span.className = token.style;
|
|
58 span.appendChild(document.createTextNode(token.value));
|
|
59 line.push(span);
|
|
60 }
|
|
61 }
|
|
62 }
|
|
63 catch (e) {
|
|
64 if (e != StopIteration) throw e;
|
|
65 }
|
|
66 if (line.length) callback(line);
|
|
67 }
|
|
68 })();
|