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
10
// Stuff from util.js that the parsers are using.
11
var StopIteration = {toString: function() {return "StopIteration"}};
17
function normaliseString(string) {
19
for (var i = 0; i < indentUnit; i++) tab += " ";
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]);
30
if (pos < parts.length) return parts[pos++];
31
else throw StopIteration;
36
window.highlightText = function(string, callback, parser) {
37
parser = (parser || Editor.Parser).make(stringStream(normaliseString(string)));
39
if (callback.nodeType == 1) {
41
callback = function(line) {
42
for (var i = 0; i < line.length; i++)
43
node.appendChild(line[i]);
44
node.appendChild(document.createElement("BR"));
50
var token = parser.next();
51
if (token.value == "\n") {
56
var span = document.createElement("SPAN");
57
span.className = token.style;
58
span.appendChild(document.createTextNode(token.value));
64
if (e != StopIteration) throw e;
66
if (line.length) callback(line);