From e71ddd38c496cd511bdd934e12c82b5474cb8e39 Mon Sep 17 00:00:00 2001 From: Estelle Weyl Date: Sun, 18 Mar 2012 19:03:41 -0700 Subject: [PATCH] console --- console/EventSource.js | 164 ++++ console/codecomplete.js | 82 ++ console/console.css | 223 +++++ console/console.js | 1025 +++++++++++++++++++++++ console/index.html | 19 + console/inject.html | 18 + console/inject.js | 38 + console/package.json | 11 + console/prettify.js | 1479 +++++++++++++++++++++++++++++++++ console/prettify.packed.js | 40 + console/remote-debugging.html | 96 +++ console/remote.html | 36 + console/remote.js | 205 +++++ console/server.js | 82 ++ 14 files changed, 3518 insertions(+) create mode 100644 console/EventSource.js create mode 100644 console/codecomplete.js create mode 100644 console/console.css create mode 100644 console/console.js create mode 100644 console/index.html create mode 100644 console/inject.html create mode 100644 console/inject.js create mode 100644 console/package.json create mode 100644 console/prettify.js create mode 100644 console/prettify.packed.js create mode 100644 console/remote-debugging.html create mode 100644 console/remote.html create mode 100644 console/remote.js create mode 100644 console/server.js diff --git a/console/EventSource.js b/console/EventSource.js new file mode 100644 index 0000000..a1c3ec9 --- /dev/null +++ b/console/EventSource.js @@ -0,0 +1,164 @@ +;(function (global) { + +if ("EventSource" in window) return; + +var reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g; + +var EventSource = function (url) { + var eventsource = this, + interval = 500, // polling interval + lastEventId = null, + cache = ''; + + if (!url || typeof url != 'string') { + throw new SyntaxError('Not enough arguments'); + } + + this.URL = url; + this.readyState = this.CONNECTING; + this._pollTimer = null; + this._xhr = null; + + function pollAgain() { + eventsource._pollTimer = setTimeout(function () { + poll.call(eventsource); + }, interval); + } + + function poll() { + try { // force hiding of the error message... insane? + if (eventsource.readyState == eventsource.CLOSED) return; + + var xhr = new XMLHttpRequest(); + xhr.open('GET', eventsource.URL, true); + xhr.setRequestHeader('Accept', 'text/event-stream'); + xhr.setRequestHeader('Cache-Control', 'no-cache'); + + // we must make use of this on the server side if we're working with Android - because they don't trigger + // readychange until the server connection is closed + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + + if (lastEventId != null) xhr.setRequestHeader('Last-Event-ID', lastEventId); + cache = ''; + + xhr.timeout = 50000; + xhr.onreadystatechange = function () { + if ((this.readyState == 3 || this.readyState == 4) && this.status == 200) { + // on success + if (eventsource.readyState == eventsource.CONNECTING) { + eventsource.readyState = eventsource.OPEN; + eventsource.dispatchEvent('open', { type: 'open' }); + } + + // process this.responseText + var parts = this.responseText.substr(cache.length).split("\n"), + data = [], + i = 0, + line = ''; + + cache = this.responseText; + + // TODO handle 'event' (for buffer name), retry + for (; i < parts.length; i++) { + line = parts[i].replace(reTrim, ''); + if (line.indexOf('data') == 0) { + data.push(line.replace(/data:?\s*/, '')); + } else if (line.indexOf('id:') == 0) { + lastEventId = line.replace(/id:?\s*/, ''); + } else if (line.indexOf('id') == 0) { // this resets the id + lastEventId = null; + } else if (line == '') { + if (data.length) { + var event = new MessageEvent(data.join('\n'), eventsource.url, lastEventId); + eventsource.dispatchEvent('message', event); + data = []; + } + } + } + + if (this.readyState == 4) pollAgain(); + // don't need to poll again, because we're long-loading + } else if (eventsource.readyState !== eventsource.CLOSED) { + if (this.readyState == 4) { // and some other status + // dispatch error + eventsource.readyState = eventsource.CONNECTING; + eventsource.dispatchEvent('error', { type: 'error' }); + pollAgain(); + } else if (this.readyState == 0) { // likely aborted + pollAgain(); + } + } + }; + + xhr.send(); + + setTimeout(function () { + if (true || xhr.readyState == 3) xhr.abort(); + }, xhr.timeout); + + eventsource._xhr = xhr; + + } catch (e) { // in an attempt to silence the errors + eventsource.dispatchEvent('error', { type: 'error', data: e.message }); // ??? + } + }; + + poll(); // init now +}; + +EventSource.prototype = { + close: function () { + // closes the connection - disabling the polling + this.readyState = this.CLOSED; + clearInterval(this._pollTimer); + this._xhr.abort(); + }, + CONNECTING: 0, + OPEN: 1, + CLOSED: 2, + dispatchEvent: function (type, event) { + var handlers = this['_' + type + 'Handlers']; + if (handlers) { + for (var i = 0; i < handlers.length; i++) { + handlers.call(this, event); + } + } + + if (this['on' + type]) { + this['on' + type].call(this, event); + } + }, + addEventListener: function (type, handler) { + if (!this['_' + type + 'Handlers']) { + this['_' + type + 'Handlers'] = []; + } + + this['_' + type + 'Handlers'].push(handler); + }, + removeEventListener: function () { + // TODO + }, + onerror: null, + onmessage: null, + onopen: null, + readyState: 0, + URL: '' +}; + +var MessageEvent = function (data, origin, lastEventId) { + this.data = data; + this.origin = origin; + this.lastEventId = lastEventId || ''; +}; + +MessageEvent.prototype = { + data: null, + type: 'message', + lastEventId: '', + origin: '' +}; + +if ('module' in global) module.exports = EventSource; +global.EventSource = EventSource; + +})(this); diff --git a/console/codecomplete.js b/console/codecomplete.js new file mode 100644 index 0000000..c3b8c5d --- /dev/null +++ b/console/codecomplete.js @@ -0,0 +1,82 @@ +var ccCache = {}; +var ccPosition = false; + +function getProps(cmd) { + var surpress = {}; + + if (!ccCache[cmd]) { + try { + // surpress alert boxes because they'll actually do something when we're looking + // up properties inside of the command we're running + surpress.alert = sandboxframe.contentWindow.alert; + sandboxframe.contentWindow.alert = function () {}; + + // loop through all of the properties available on the command (that's evaled) + ccCache[cmd] = sandboxframe.contentWindow.eval('console.props(' + cmd + ')').sort(); + + // return alert back to it's former self + sandboxframe.contentWindow.alert = surpress.alert; + } catch (e) { + ccCache[cmd] = []; + } + + // if the return value is undefined, then it means there's no props, so we'll + // empty the code completion + if (ccCache[cmd][0] == 'undefined') ccOptions[cmd] = []; + ccPosition = 0; + } + + return ccCache[cmd]; +} + +function codeComplete(event) { + var cmd = cursor.textContent.split(/[;\s]+/g).pop(), + which = whichKey(event), + cc, + props = []; + + if (cmd) { + if (cmd.substr(-1) == '.') { + // get the command without the '.' so we can eval it and lookup the properties + cmd = cmd.substr(0, cmd.length - 1); + + props = getProps(cmd); + } else { + props = getProps(cmd); + } + + if (props.length) { + if (which == 9) { // tabbing cycles through the code completion + if (event.shiftKey) { + // backwards + ccPosition = ccPosition == 0 ? props.length - 1 : ccPosition-1; + } else { + ccPosition = ccPosition == props.length - 1 ? 0 : ccPosition+1; + } + + } else { + ccPosition = 0; + } + + // position the code completion next to the cursor + if (!cursor.nextSibling) { + cc = document.createElement('span'); + cc.className = 'suggest'; + exec.appendChild(cc); + } + + cursor.nextSibling.innerHTML = props[ccPosition]; + exec.value = exec.textContent; + + if (which == 9) return false; + } + } else { + ccPosition = false; + } + + if (ccPosition === false && cursor.nextSibling) { + exec.removeChild(cursor.nextSibling); + } + + exec.value = exec.textContent; +} \ No newline at end of file diff --git a/console/console.css b/console/console.css new file mode 100644 index 0000000..1200d49 --- /dev/null +++ b/console/console.css @@ -0,0 +1,223 @@ +* { + -webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */ +/* make transparent link selection, adjust last value opacity 0 to 1.0 */ + -webkit-tap-highlight-color: rgba(0,0,0,0); + margin: 0; + padding: 0; +} + +html { height: 100%; background: #fff; } +body { height: 100%; overflow: hidden; border: 0; margin: 0; padding: 0; font-family: "helvetica neue", arial, helvetica; width: 100%; overflow-x: hidden; } +input, textarea { margin: 0; padding: 0; position: relative; font-size: 18px; width: 100%; -webkit-border-radius: 0; -webkit-appearance: none; } /* webkit-mobile adds rounded corners :( */ +input { padding: 2px; } + +/*#console { position: absolute; left: 0; right: 0; width: 100%; bottom: 0; overflow: auto; border-bottom: 1px solid #5B5C5B; }*/ + +/* HACK attempt to allow multiline */ +body { overflow: auto; } +#console { bottom: 35px; left: 0; right: 0; width: 100%; margin-bottom: 35px; overflow: auto; /*border-bottom: 1px solid #5B5C5B;*/ } + +#output { list-style: none; } +#output li { margin: 5px 0; padding: 5px; border-top: 1px solid #EEEFEE; white-space: pre-wrap; } +#output li:last-child { border-bottom: 0;} +#output > li > div { margin-left: 20px; line-height: 20px; } +#console span.gutter { float: left; display: block; width: 5px; } + +#output li div { position: relative; } +#output .echo .permalink { position: absolute; right: 0; overflow: hidden; display: block; background: url(link.png) no-repeat center; height: 20px; width: 30px; text-indent: -200px; top: 0; opacity: 0.5; } + +@media only screen and (-webkit-min-device-pixel-ratio: 2) { + -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ + + #output .echo .permalink { + background: url(link@2x.png) no-repeat center; + background-size: 16px 16px; + } +} + + +#output .echo .permalink:hover { opacity: 1; } + +/* log types */ +#output span.gutter:before { position: absolute; } +#output .echo span.gutter:before { content: '> '; color: #3583FC; font-size: 18px; font-weight: bold; } +#output .info span.gutter:before { content: 'i '; color: #27A700; font-size: 18px; font-weight: bold; } +#output .error span.gutter:before { content: '\0000D7 '; color: #E81D20; font-size: 28px; font-weight: bold; margin-right: -10px; line-height: 24px; } +#output .response span.gutter:before { content: '« '; color: #BDC3CD; font-size: 18px; font-weight: normal; margin-right: -10px; line-height: 18px; } + +/* if response is directly next to echo, don't give it a line - only consoles get lines */ +#output li.echo + li.response { border-width: 0px; } + +/* hard line on new echo */ +#output li.response + li.echo { border-width: 2px; border-color: #DFDFDF; } +#output li.error + li.echo { border-width: 2px; border-color: #DFDFDF; } +#output li.log + li.echo { border-width: 2px; border-color: #DFDFDF; } +#output li.info + li.echo { border-width: 2px; border-color: #DFDFDF; } +/*#output li.info .response span { line-height: 30px; }*/ + +#output li.echo:first-child { border-width: 0;} +#output li:first-child { border-width: 0; padding-top: 0; } + +iframe { display: none; } + +/* input style - note: moz-shadow purposely omitted because it affects layout */ +form { padding: 5px; border-bottom: 1px solid #AAABB8; background: #E6E8F2; -webkit-box-shadow: 0px 2px 10px rgba(0,0,0,.3); -o-box-shadow: 0px 2px 10px rgba(0,0,0,.3); box-shadow: 0px 2px 10px rgba(0,0,0,.3); } +#exec, .fakeInput { resize: none; position: absolute; left: 0; right: 0; border: 0; /*padding: 5px; */outline: 0; background: #E6E8F2; color: #000; height: 24px; line-height: 24px; overflow: hidden; } + +/* HACK */ +form { position: fixed; top: 0; width: 100%; z-index: 2; } +#console { padding-top: 35px; } +#exec, .fakeInput { position: relative; height: auto; } + +/* bottom position */ +.bottom form { bottom: 0; top: auto; } +.bottom form { border-bottom: 0; border-top: 1px solid #AAABB8; background: #E6E8F2; -webkit-box-shadow: 0px -2px 10px rgba(0,0,0,.3); -o-box-shadow: 0px -2px 10px rgba(0,0,0,.3); box-shadow: 0px -2px 10px rgba(0,0,0,.3); } + +/* footer, credit, etc */ +#footer { position: fixed; bottom: 0; left: 0; right: 0; height: 34px; background-color: #9E9E9E; color: #9E9F9E; color: rgba(158, 158, 158, 0.5); width: 100%; color: #fff; text-shadow: 1px 1px 0 #000; line-height: 24px; border-top: 1px solid #CED1CE; -webkit-transition: background-color ease-out 100ms; -moz-transition: background-color ease-out 100ms; -o-transition: background-color ease-out 100ms; transition: background-color ease-out 100ms; } +#footer:hover { background: #727372; } +#footer a { line-height: 34px; text-transform: lowercase; margin: 0 5px; color: #fff; text-decoration: none; text-shadow: 1px 1px 0 #000; } + +/* font size control */ +/*#console { top: 35px; bottom: 35px; }*/ +#output li, #exec, .fakeInput { min-height: 20px; font-size: 15px; font-family: "Menlo", consolas, monospace; } + +/* code complete visual tweaks */ +#cursor { display: inline-block; height: 24px; min-width: 1px; outline: 0; top: 0; left: 0; z-index: 999;} + +/* HACK */ +#cursor { height: auto; white-space: pre-wrap; } + +#exec, .fakeInput { cursor: text; } +#exec .suggest { color: #999; } + +/* large command input */ +body.large #console { top: 0; padding-top: 0; bottom: 0; margin-bottom: 0; right: 40%; width: auto; position: absolute; } +body.large form { right: 0; width: 40%; bottom: 0; background: none; border: 0; padding: 0; } +body.large #exec { position: absolute; width: 100%; padding: 0; border-bottom: 0; top: 0; bottom: 0; height: 100%; z-index: 10; background: #E6E8F2; color: #000; -webkit-box-shadow: none; border-left: 1px solid #AAABB8; left: auto; } +body.large #cursor { padding: 5px; } +/* with footer - which I've removed temporarily */ +/* body.large #console { + bottom: 35px; +} */ + +/* syntax highlighting */ +/** Pretty printing styles. Used with prettify.js. */ + +.str { color: #080; } +.kwd { color: #008; } +.com { color: #800; } +.typ { color: #606; } +.lit { color: #066; } +.pun { color: #660; } +.pln { color: #000; } +.tag { color: #008; } +.atn { color: #606; } +.atv { color: #080; } +.dec { color: #606; } +.error span { color: #E81D20;} + +/* hide the footer after a short amount of time */ +#footer { + transition: opacity 200ms ease-out; + -webkit-transition: opacity 200ms ease-out; + -moz-transition: opacity 200ms ease-out; + -o-transition: opacity 200ms ease-out; + -ms-transition: opacity 200ms ease-out; + opacity: 1; +} + +#footer.hidden { + opacity: 0; +} + +#footer:hover { + opacity: 1; +} + +.fakeInput { + display: block; + position: absolute; + top: 0; + left: 0; + padding: 5px; + border: 0; + color: red; + opacity: 0; + /* pointer-events: auto !important;*/ +} + +/*#footer { + -webkit-animation-name: hidefooter; + -webkit-animation-duration: 200ms; + -webkit-animation-delay: 1s; + -webkit-animation-iteration-count: 1; + -webkit-animation-fill-mode: none; + -webkit-transition: opacity 200ms ease-out; + opacity: 1; +} + +#footer:hover { + opacity: 1 !important; +} + +@-webkit-keyframes hidefooter { + 0% { + opacity: 1; + } + 100% { + opacity: 0; + } +} +*/ +/* difference display types */ + +/* iPhone type display */ +@media screen and (max-device-width: 480px) { + -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ + + html, body { height: auto; overflow-y: auto; overflow-x: hidden; } + #console { overflow: auto; bottom: 0; border-bottom: 0; margin-bottom: 0; padding-top: 5px; } + #console { margin-top: 35px; } + #output .echo .permalink { width: 18px; height: 20px; } + #footer { display: none; } + + #exec, .fakeInput { font-weight: bold; padding-right: 10px; } + + #output li { min-height: 20px; font-size: 14px; padding: 2px 5px 0 5px; } + #output > li > div { margin-left: 12px; line-height: 20px; } + + #output > li:last-child { padding-bottom: 0; margin-bottom: 0; } + + #output .gutter { line-height: 20px; } + #output .echo { padding-top: 5px; } + #output .echo span.gutter:before, + #output .info span.gutter:before, + #output .response span.gutter:before { font-size: 14px; line-height: 18px; height: 14px; } + #output .error span.gutter:before { font-size: 18px; line-height: 18px; } + +/* .info span { line-height: 30px; }*/ +} + +@media screen and (max-device-width: 768px) { + #footer { display: none; } +} + +/* allow the debug to be printed */ +@media print { + body { overflow: auto; } + #console { overflow: visible; } +} + +@media print { + .str { color: #060; } + .kwd { color: #006; font-weight: bold; } + .com { color: #600; font-style: italic; } + .typ { color: #404; font-weight: bold; } + .lit { color: #044; } + .pun { color: #440; } + .pln { color: #000; } + .tag { color: #006; font-weight: bold; } + .atn { color: #404; } + .atv { color: #060; } +} diff --git a/console/console.js b/console/console.js new file mode 100644 index 0000000..3399f9f --- /dev/null +++ b/console/console.js @@ -0,0 +1,1025 @@ +(function (window) { + +function sortci(a, b) { + return a.toLowerCase() < b.toLowerCase() ? -1 : 1; +} + +// custom because I want to be able to introspect native browser objects *and* functions +function stringify(o, simple, visited) { + var json = '', i, vi, type = '', parts = [], names = [], circular = false; + visited = visited || []; + + try { + type = ({}).toString.call(o); + } catch (e) { // only happens when typeof is protected (...randomly) + type = '[object Object]'; + } + + // check for circular references + for (vi = 0; vi < visited.length; vi++) { + if (o === visited[vi]) { + circular = true; + break; + } + } + + if (circular) { + json = '[circular]'; + } else if (type == '[object String]') { + json = '"' + o.replace(/"/g, '\\"') + '"'; + } else if (type == '[object Array]') { + visited.push(o); + + json = '['; + for (i = 0; i < o.length; i++) { + parts.push(stringify(o[i], simple, visited)); + } + json += parts.join(', ') + ']'; + json; + } else if (type == '[object Object]') { + visited.push(o); + + json = '{'; + for (i in o) { + names.push(i); + } + names.sort(sortci); + for (i = 0; i < names.length; i++) { + parts.push( stringify(names[i], undefined, visited) + ': ' + stringify(o[ names[i] ], simple, visited) ); + } + json += parts.join(', ') + '}'; + } else if (type == '[object Number]') { + json = o+''; + } else if (type == '[object Boolean]') { + json = o ? 'true' : 'false'; + } else if (type == '[object Function]') { + json = o.toString(); + } else if (o === null) { + json = 'null'; + } else if (o === undefined) { + json = 'undefined'; + } else if (simple == undefined) { + visited.push(o); + + json = type + '{\n'; + for (i in o) { + names.push(i); + } + names.sort(sortci); + for (i = 0; i < names.length; i++) { + try { + parts.push(names[i] + ': ' + stringify(o[names[i]], true, visited)); // safety from max stack + } catch (e) { + if (e.name == 'NS_ERROR_NOT_IMPLEMENTED') { + // do nothing - not sure it's useful to show this error when the variable is protected + // parts.push(names[i] + ': NS_ERROR_NOT_IMPLEMENTED'); + } + } + } + json += parts.join(',\n') + '\n}'; + } else { + try { + json = o+''; // should look like an object + } catch (e) {} + } + return json; +} + +function cleanse(s) { + return (s||'').replace(/[<&]/g, function (m) { return {'&':'&','<':'<'}[m];}); +} + +function run(cmd) { + var rawoutput = null, + className = 'response', + internalCmd = internalCommand(cmd); + + if (internalCmd) { + return ['info', internalCmd]; + } else if (remoteId !== null) { + // send the remote event + var xhr = new XMLHttpRequest(), + params = 'data=' + encodeURIComponent(cmd); + + xhr.open('POST', '/remote/' + remoteId + '/run', true); + xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); + xhr.send(params); + setCursorTo(''); + return ['info', 'sent remote command']; + } else { + try { + if ('CoffeeScript' in sandboxframe.contentWindow) cmd = sandboxframe.contentWindow.CoffeeScript.compile(cmd, {bare:true}); + rawoutput = sandboxframe.contentWindow.eval(cmd); + } catch (e) { + rawoutput = e.message; + className = 'error'; + } + return [className, cleanse(stringify(rawoutput))]; + } +} + +function post(cmd, blind, response /* passed in when echoing from remote console */) { + cmd = trim(cmd); + + if (blind === undefined) { + history.push(cmd); + setHistory(history); + + if (historySupported) { + window.history.pushState(cmd, cmd, '?' + encodeURIComponent(cmd)); + } + } + + if (!remoteId || response) echo(cmd); + + // order so it appears at the top + var el = document.createElement('div'), + li = document.createElement('li'), + span = document.createElement('span'), + parent = output.parentNode; + + response = response || run(cmd); + + if (response !== undefined) { + el.className = 'response'; + span.innerHTML = response[1]; + + if (response[0] != 'info') prettyPrint([span]); + el.appendChild(span); + + li.className = response[0]; + li.innerHTML = ''; + li.appendChild(el); + + appendLog(li); + + output.parentNode.scrollTop = 0; + if (!body.className) { + exec.value = ''; + if (enableCC) { + try { + document.getElementsByTagName('a')[0].focus(); + cursor.focus(); + document.execCommand('selectAll', false, null); + document.execCommand('delete', false, null); + } catch (e) {} + } + } + } + pos = history.length; +} + +function log(msg, className) { + var li = document.createElement('li'), + div = document.createElement('div'); + + div.innerHTML = msg; + prettyPrint([div]); + li.className = className || 'log'; + li.innerHTML = ''; + li.appendChild(div); + + appendLog(li); +} + +function echo(cmd) { + var li = document.createElement('li'); + + li.className = 'echo'; + li.innerHTML = '
' + cleanse(cmd) + '
'; + + logAfter = null; + + if (output.querySelector) { + logAfter = output.querySelector('li.echo') || null; + } else { + var lis = document.getElementsByTagName('li'), + len = lis.length, + i; + for (i = 0; i < len; i++) { + if (lis[i].className.indexOf('echo') !== -1) { + logAfter = lis[i]; + break; + } + } + } + + // logAfter = output.querySelector('li.echo') || null; + appendLog(li, true); +} + +window.info = function(cmd) { + var li = document.createElement('li'); + + li.className = 'info'; + li.innerHTML = '
' + cleanse(cmd) + '
'; + + // logAfter = output.querySelector('li.echo') || null; + // appendLog(li, true); + appendLog(li); +} + +function appendLog(el, echo) { + if (echo) { + if (!output.firstChild) { + output.appendChild(el); + } else { + output.insertBefore(el, output.firstChild); + } + } else { + // if (!output.lastChild) { + // output.appendChild(el); + // // console.log('ok'); + // } else { + // console.log(output.lastChild.nextSibling); + output.insertBefore(el, logAfter ? logAfter : output.lastChild.nextSibling); // ? output.lastChild.nextSibling : output.firstChild + // } + } +} + +function changeView(event){ + if (false && enableCC) return; + + var which = event.which || event.keyCode; + if (which == 38 && event.shiftKey == true) { + body.className = ''; + cursor.focus(); + try { + localStorage.large = 0; + } catch (e) {} + return false; + } else if (which == 40 && event.shiftKey == true) { + body.className = 'large'; + try { + localStorage.large = 1; + } catch (e) {} + cursor.focus(); + return false; + } +} + +function internalCommand(cmd) { + var parts = [], c; + if (cmd.substr(0, 1) == ':') { + parts = cmd.substr(1).split(' '); + c = parts.shift(); + return (commands[c] || noop).apply(this, parts); + } +} + +function noop() {} + +function showhelp() { + var commands = [ + ':load <url> - to inject new DOM', + ':load <script_url> - to inject external library', + ' load also supports following shortcuts:
jquery, underscore, prototype, mootools, dojo, rightjs, coffeescript, yui.
eg. :load jquery', + ':listen [id] - to start remote debugging session', + ':clear - to clear the history (accessed using cursor keys)', + ':history - list current session history', + ':about', + '', + 'Directions to inject JS Console in to any page (useful for mobile debugging)' + ]; + + if (injected) { + commands.push(':close - to hide the JS Console'); + } + + // commands = commands.concat([ + // 'up/down - cycle history', + // 'shift+up - single line command', + // 'shift+down - multiline command', + // 'shift+enter - to run command in multiline mode' + // ]); + + return commands.join('\n'); +} + +function load(url) { + if (navigator.onLine) { + if (arguments.length > 1 || libraries[url] || url.indexOf('.js') !== -1) { + return loadScript.apply(this, arguments); + } else { + return loadDOM(url); + } + } else { + return "You need to be online to use :load"; + } +} + +function loadScript() { + var doc = sandboxframe.contentDocument || sandboxframe.contentWindow.document; + for (var i = 0; i < arguments.length; i++) { + (function (url) { + var script = document.createElement('script'); + script.src = url + script.onload = function () { + window.top.info('Loaded ' + url, 'http://' + window.location.hostname); + if (url == libraries.coffeescript) window.top.info('Now you can type CoffeeScript instead of plain old JS!'); + }; + script.onerror = function () { + log('Failed to load ' + url, 'error'); + } + doc.body.appendChild(script); + })(libraries[arguments[i]] || arguments[i]); + } + return "Loading script..."; +} + +function loadDOM(url) { + var doc = sandboxframe.contentWindow.document, + script = document.createElement('script'), + cb = 'loadDOM' + +new Date; + + script.src = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22' + encodeURIComponent(url) + '%22&format=xml&callback=' + cb; + + window[cb] = function (yql) { + if (yql.results.length) { + var html = yql.results[0].replace(/type="text\/javascript"/ig,'type="x"').replace(//, '').replace(/<\/body>/, ''); + + doc.body.innerHTML = html; + window.top.info('DOM load complete'); + } else { + log('Failed to load DOM', 'error'); + } + try { + window[cb] = null; + delete window[cb]; + } catch (e) {} + + }; + + document.body.appendChild(script); + + return "Loading url into DOM..."; +} + +function checkTab(evt) { + var t = evt.target, + ss = t.selectionStart, + se = t.selectionEnd, + tab = " "; + + + // Tab key - insert tab expansion + if (evt.keyCode == 9) { + evt.preventDefault(); + + // Special case of multi line selection + if (ss != se && t.value.slice(ss,se).indexOf("\n") != -1) { + // In case selection was not of entire lines (e.g. selection begins in the middle of a line) + // we ought to tab at the beginning as well as at the start of every following line. + var pre = t.value.slice(0,ss); + var sel = t.value.slice(ss,se).replace(/\n/g,"\n"+tab); + var post = t.value.slice(se,t.value.length); + t.value = pre.concat(tab).concat(sel).concat(post); + + t.selectionStart = ss + tab.length; + t.selectionEnd = se + tab.length; + } + + // "Normal" case (no selection or selection on one line only) + else { + t.value = t.value.slice(0,ss).concat(tab).concat(t.value.slice(ss,t.value.length)); + if (ss == se) { + t.selectionStart = t.selectionEnd = ss + tab.length; + } + else { + t.selectionStart = ss + tab.length; + t.selectionEnd = se + tab.length; + } + } + } + + // Backspace key - delete preceding tab expansion, if exists + else if (evt.keyCode==8 && t.value.slice(ss - 4,ss) == tab) { + evt.preventDefault(); + + t.value = t.value.slice(0,ss - 4).concat(t.value.slice(ss,t.value.length)); + t.selectionStart = t.selectionEnd = ss - tab.length; + } + + // Delete key - delete following tab expansion, if exists + else if (evt.keyCode==46 && t.value.slice(se,se + 4) == tab) { + evt.preventDefault(); + + t.value = t.value.slice(0,ss).concat(t.value.slice(ss + 4,t.value.length)); + t.selectionStart = t.selectionEnd = ss; + } + // Left/right arrow keys - move across the tab in one go + else if (evt.keyCode == 37 && t.value.slice(ss - 4,ss) == tab) { + evt.preventDefault(); + t.selectionStart = t.selectionEnd = ss - 4; + } + else if (evt.keyCode == 39 && t.value.slice(ss,ss + 4) == tab) { + evt.preventDefault(); + t.selectionStart = t.selectionEnd = ss + 4; + } +} + +function trim(s) { + return (s||"").replace(/^\s+|\s+$/g,""); +} + +var ccCache = {}; +var ccPosition = false; + +function getProps(cmd, filter) { + var surpress = {}, props = []; + + if (!ccCache[cmd]) { + try { + // surpress alert boxes because they'll actually do something when we're looking + // up properties inside of the command we're running + surpress.alert = sandboxframe.contentWindow.alert; + sandboxframe.contentWindow.alert = function () {}; + + // loop through all of the properties available on the command (that's evaled) + ccCache[cmd] = sandboxframe.contentWindow.eval('console.props(' + cmd + ')').sort(); + + // return alert back to it's former self + delete sandboxframe.contentWindow.alert; + } catch (e) { + ccCache[cmd] = []; + } + + // if the return value is undefined, then it means there's no props, so we'll + // empty the code completion + if (ccCache[cmd][0] == 'undefined') ccOptions[cmd] = []; + ccPosition = 0; + props = ccCache[cmd]; + } else if (filter) { + // console.log('>>' + filter, cmd); + for (var i = 0, p; i < ccCache[cmd].length, p = ccCache[cmd][i]; i++) { + if (p.indexOf(filter) === 0) { + if (p != filter) { + props.push(p.substr(filter.length, p.length)); + } + } + } + } else { + props = ccCache[cmd]; + } + + return props; +} + +function codeComplete(event) { + var cmd = cursor.textContent.split(/[;\s]+/g).pop(), + parts = cmd.split('.'), + which = whichKey(event), + cc, + props = []; + + if (cmd) { + // get the command without the dot to allow us to introspect + if (cmd.substr(-1) == '.') { + // get the command without the '.' so we can eval it and lookup the properties + cmd = cmd.substr(0, cmd.length - 1); + + // returns an array of all the properties from the command + props = getProps(cmd); + } else { + props = getProps(parts.slice(0, parts.length - 1).join('.') || 'window', parts[parts.length - 1]); + } + if (props.length) { + if (which == 9) { // tabbing cycles through the code completion + // however if there's only one selection, it'll auto complete + if (props.length === 1) { + ccPosition = false; + } else { + if (event.shiftKey) { + // backwards + ccPosition = ccPosition == 0 ? props.length - 1 : ccPosition-1; + } else { + ccPosition = ccPosition == props.length - 1 ? 0 : ccPosition+1; + } + } + } else { + ccPosition = 0; + } + + if (ccPosition === false) { + completeCode(); + } else { + // position the code completion next to the cursor + if (!cursor.nextSibling) { + cc = document.createElement('span'); + cc.className = 'suggest'; + exec.appendChild(cc); + } + + cursor.nextSibling.innerHTML = props[ccPosition]; + exec.value = exec.textContent; + } + + if (which == 9) return false; + } else { + ccPosition = false; + } + } else { + ccPosition = false; + } + + if (ccPosition === false && cursor.nextSibling) { + removeSuggestion(); + } + + exec.value = exec.textContent; +} + +function removeSuggestion() { + if (!enableCC) exec.setAttribute('rows', 1); + if (enableCC && cursor.nextSibling) cursor.parentNode.removeChild(cursor.nextSibling); +} + +window._console = { + log: function () { + var l = arguments.length, i = 0; + for (; i < l; i++) { + log(stringify(arguments[i], true)); + } + }, + dir: function () { + var l = arguments.length, i = 0; + for (; i < l; i++) { + log(stringify(arguments[i])); + } + }, + props: function (obj) { + var props = [], realObj; + try { + for (var p in obj) props.push(p); + } catch (e) {} + return props; + } +}; + +function showHistory() { + var h = getHistory(); + h.shift(); + return h.join("\n"); +} + +function getHistory() { + var history = ['']; + + if (typeof JSON == 'undefined') return history; + + try { + // because FF with cookies disabled goes nuts, and because sometimes WebKit goes nuts too... + history = JSON.parse(sessionStorage.getItem('history') || '[""]'); + } catch (e) {} + return history; +} + +// I should do this onunload...but I'm being lazy and hacky right now +function setHistory(history) { + if (typeof JSON == 'undefined') return; + + try { + // because FF with cookies disabled goes nuts, and because sometimes WebKit goes nuts too... + sessionStorage.setItem('history', JSON.stringify(history)); + } catch (e) {} +} + +function about() { + return 'Built by @rem'; +} + + +document.addEventListener ? + window.addEventListener('message', function (event) { + post(event.data); + }, false) : + window.attachEvent('onmessage', function () { + post(window.event.data); + }); + +var exec = document.getElementById('exec'), + form = exec.form || {}, + output = document.getElementById('output'), + cursor = document.getElementById('exec'), + injected = typeof window.top['JSCONSOLE'] !== 'undefined', + sandboxframe = injected ? window.top['JSCONSOLE'] : document.createElement('iframe'), + sandbox = null, + fakeConsole = 'window.top._console', + history = getHistory(), + liveHistory = (window.history.pushState !== undefined), + pos = 0, + libraries = { + jquery: 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', + prototype: 'http://ajax.googleapis.com/ajax/libs/prototype/1/prototype.js', + dojo: 'http://ajax.googleapis.com/ajax/libs/dojo/1/dojo/dojo.xd.js', + mootools: 'http://ajax.googleapis.com/ajax/libs/mootools/1/mootools-yui-compressed.js', + underscore: 'http://documentcloud.github.com/underscore/underscore-min.js', + rightjs: 'http://rightjs.org/hotlink/right.js', + coffeescript: 'http://jashkenas.github.com/coffee-script/extras/coffee-script.js', + yui: 'http://yui.yahooapis.com/3.2.0/build/yui/yui-min.js' + }, + body = document.getElementsByTagName('body')[0], + logAfter = null, + historySupported = !!(window.history && window.history.pushState), + sse = null, + lastCmd = null, + remoteId = null, + codeCompleteTimer = null, + keypressTimer = null, + commands = { + help: showhelp, + about: about, + // loadjs: loadScript, + load: load, + history: showHistory, + clear: function () { + setTimeout(function () { output.innerHTML = ''; }, 10); + return 'clearing...'; + }, + close: function () { + if (injected) { + JSCONSOLE.console.style.display = 'none'; + return 'hidden'; + } else { + return 'noop'; + } + }, + listen: function (id) { + // place script request for new listen ID and start SSE + var script = document.createElement('script'), + callback = '_cb' + +new Date; + script.src = '/remote/' + (id||'') + '?callback=' + callback; + + window[callback] = function (id) { + remoteId = id; + if (sse !== null) sse.close(); + + sse = new EventSource('/remote/' + id + '/log'); + sse.onopen = function () { + remoteId = id; + window.top.info('Connected to "' + id + '"\n\n'); + }; + + sse.onmessage = function (event) { + var data = JSON.parse(event.data); + if (data.type && data.type == 'error') { + post(data.cmd, true, ['error', data.response]); + } else if (data.type && data.type == 'info') { + window.top.info(data.response); + } else { + if (data.cmd != 'remote console.log') data.response = data.response.substr(1, data.response.length - 2); // fiddle to remove the [] around the repsonse + echo(data.cmd); + log(data.response, 'response'); + } + }; + + sse.onclose = function () { + window.top.info('Remote connection closed'); + remoteId = null; + }; + + try { + body.removeChild(script); + delete window[callback]; + } catch (e) {} + }; + body.appendChild(script); + return 'Creating connection...'; + } + }, + fakeInput = null, + // I hate that I'm browser sniffing, but there's issues with Firefox and execCommand so code completion won't work + iOSMobile = navigator.userAgent.indexOf('AppleWebKit') !== -1 && navigator.userAgent.indexOf('Mobile') !== -1, + // FIXME Remy, seriously, don't sniff the agent like this, it'll bite you in the arse. + enableCC = navigator.userAgent.indexOf('AppleWebKit') !== -1 && navigator.userAgent.indexOf('Mobile') === -1 || navigator.userAgent.indexOf('OS 5_') !== -1; + +if (enableCC) { + exec.parentNode.innerHTML = '
'; + exec = document.getElementById('exec'); + cursor = document.getElementById('cursor'); +} + +if (enableCC && iOSMobile) { + fakeInput = document.createElement('input'); + fakeInput.className = 'fakeInput'; + fakeInput.setAttribute('spellcheck', 'false'); + fakeInput.setAttribute('autocorrect', 'off'); + fakeInput.setAttribute('autocapitalize', 'off'); + exec.parentNode.appendChild(fakeInput); +} + +if (!injected) { + body.appendChild(sandboxframe); + sandboxframe.setAttribute('id', 'sandbox'); +} + +sandbox = sandboxframe.contentDocument || sandboxframe.contentWindow.document; + +if (!injected) { + sandbox.open(); + // stupid jumping through hoops if Firebug is open, since overwriting console throws error + sandbox.write(''); + sandbox.close(); +} else { + sandboxframe.contentWindow.eval('(function () { var fakeConsole = ' + fakeConsole + '; if (console != undefined) { for (var k in fakeConsole) { console[k] = fakeConsole[k]; } } else { console = fakeConsole; } })();'); +} + +// tweaks to interface to allow focus +// if (!('autofocus' in document.createElement('input'))) exec.focus(); +cursor.focus(); +output.parentNode.tabIndex = 0; + +function whichKey(event) { + var keys = {38:1, 40:1, Up:38, Down:40, Enter:10, 'U+0009':9, 'U+0008':8, 'U+0190':190, 'Right':39, + // these two are ignored + 'U+0028': 57, 'U+0026': 55 }; + return keys[event.keyIdentifier] || event.which || event.keyCode; +} + +function setCursorTo(str) { + str = enableCC ? cleanse(str) : str; + exec.value = str; + + if (enableCC) { + document.execCommand('selectAll', false, null); + document.execCommand('delete', false, null); + document.execCommand('insertHTML', false, str); + } else { + var rows = str.match(/\n/g); + exec.setAttribute('rows', rows !== null ? rows.length + 1 : 1); + } + cursor.focus(); + window.scrollTo(0,0); +} + +output.ontouchstart = output.onclick = function (event) { + event = event || window.event; + if (event.target.nodeName == 'A' && event.target.className == 'permalink') { + var command = decodeURIComponent(event.target.search.substr(1)); + setCursorTo(command); + + if (liveHistory) { + window.history.pushState(command, command, event.target.href); + } + + return false; + } +}; + +exec.ontouchstart = function () { + window.scrollTo(0,0); +}; + +exec.onkeyup = function (event) { + var which = whichKey(event); + + if (enableCC && which != 9 && which != 16) { + clearTimeout(codeCompleteTimer); + codeCompleteTimer = setTimeout(function () { + codeComplete(event); + }, 200); + } +}; + +if (enableCC) { + // disabled for now + cursor.__onpaste = function (event) { + setTimeout(function () { + // this causes the field to lose focus - I'll leave it here for a while, see how we get on. + // what I need to do is rip out the contenteditable and replace it with something entirely different + cursor.innerHTML = cursor.innerText; + // setCursorTo(cursor.innerText); + }, 10); + }; +} + +function findNode(list, node) { + var pos = 0; + for (var i = 0; i < list.length; i++) { + if (list[i] == node) { + return pos; + } + pos += list[i].nodeValue.length; + } + return -1; +} + +exec.onkeydown = function (event) { + event = event || window.event; + var keys = {38:1, 40:1}, + wide = body.className == 'large', + which = whichKey(event); + + if (typeof which == 'string') which = which.replace(/\/U\+/, '\\u'); + if (keys[which]) { + if (event.shiftKey) { + changeView(event); + } else if (!wide) { // history cycle + if (enableCC && window.getSelection) { + window.selObj = window.getSelection(); + var selRange = selObj.getRangeAt(0); + + cursorPos = findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset; + var value = exec.value, + firstnl = value.indexOf('\n'), + lastnl = value.lastIndexOf('\n'); + + if (firstnl !== -1) { + if (which == 38 && cursorPos > firstnl) { + return; + } else if (which == 40 && cursorPos < lastnl) { + return; + } + } + } + + if (which == 38) { // cycle up + pos--; + if (pos < 0) pos = 0; //history.length - 1; + } else if (which == 40) { // down + pos++; + if (pos >= history.length) pos = history.length; //0; + } + if (history[pos] != undefined && history[pos] !== '') { + removeSuggestion(); + setCursorTo(history[pos]) + return false; + } else if (pos == history.length) { + removeSuggestion(); + setCursorTo(''); + return false; + } + } + } else if ((which == 13 || which == 10) && event.shiftKey == false) { // enter (what about the other one) + removeSuggestion(); + if (event.shiftKey == true || event.metaKey || event.ctrlKey || !wide) { + var command = exec.textContent || exec.value; + if (command.length) post(command); + return false; + } + } else if ((which == 13 || which == 10) && !enableCC && event.shiftKey == true) { + // manually expand the textarea when we don't have code completion turned on + var rows = exec.value.match(/\n/g); + rows = rows != null ? rows.length + 2 : 2; + exec.setAttribute('rows', rows); + } else if (which == 9 && wide) { + checkTab(event); + } else if (event.shiftKey && event.metaKey && which == 8) { + output.innerHTML = ''; + } else if ((which == 39 || which == 35) && ccPosition !== false) { // complete code + completeCode(); + } else if (event.ctrlKey && which == 76) { + output.innerHTML = ''; + } else if (enableCC) { // try code completion + if (ccPosition !== false && which == 9) { + codeComplete(event); // cycles available completions + return false; + } else if (ccPosition !== false && cursor.nextSibling) { + removeSuggestion(); + } + } +}; + +if (enableCC && iOSMobile) { + fakeInput.onkeydown = function (event) { + removeSuggestion(); + var which = whichKey(event); + + if (which == 13 || which == 10) { + post(this.value); + this.value = ''; + cursor.innerHTML = ''; + return false; + } + }; + + fakeInput.onkeyup = function (event) { + cursor.innerHTML = cleanse(this.value); + var which = whichKey(event); + if (enableCC && which != 9 && which != 16) { + clearTimeout(codeCompleteTimer); + codeCompleteTimer = setTimeout(function () { + codeComplete(event); + }, 200); + } + }; + + var fakeInputFocused = false; + + var dblTapTimer = null, + taps = 0; + + form.addEventListener('touchstart', function (event) { + // window.scrollTo(0,0); + if (ccPosition !== false) { + event.preventDefault(); + clearTimeout(dblTapTimer); + taps++; + + if (taps === 2) { + completeCode(); + fakeInput.value = cursor.textContent; + removeSuggestion(); + fakeInput.focus(); + } else { + dblTapTimer = setTimeout(function () { + taps = 0; + codeComplete({ which: 9 }); + }, 200); + } + } + + return false; + }); +} + +function completeCode(focus) { + var tmp = exec.textContent, l = tmp.length; + removeSuggestion(); + + cursor.innerHTML = tmp; + ccPosition = false; + + // daft hack to move the focus elsewhere, then back on to the cursor to + // move the cursor to the end of the text. + document.getElementsByTagName('a')[0].focus(); + cursor.focus(); + + var range, selection; + if (document.createRange) {//Firefox, Chrome, Opera, Safari, IE 9+ + range = document.createRange();//Create a range (a range is a like the selection but invisible) + range.selectNodeContents(cursor);//Select the entire contents of the element with the range + range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start + selection = window.getSelection();//get the selection object (allows you to change selection) + selection.removeAllRanges();//remove any selections already made + selection.addRange(range);//make the range you have just created the visible selection + } else if (document.selection) {//IE 8 and lower + range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible) + range.moveToElementText(cursor);//Select the entire contents of the element with the range + range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start + range.select();//Select the range (make it the visible selection + } +} + +form.onsubmit = function (event) { + event = event || window.event; + event.preventDefault && event.preventDefault(); + removeSuggestion(); + post(exec.textContent || exec.value); + return false; +}; + +document.onkeydown = function (event) { + event = event || window.event; + var which = event.which || event.keyCode; + + if (event.shiftKey && event.metaKey && which == 8) { + output.innerHTML = ''; + cursor.focus(); + } else if (event.target == output.parentNode && which == 32) { // space + output.parentNode.scrollTop += 5 + output.parentNode.offsetHeight * (event.shiftKey ? -1 : 1); + } + + return changeView(event); +}; + +exec.onclick = function () { + cursor.focus(); +} +if (window.location.search) { + post(decodeURIComponent(window.location.search.substr(1))); +} else { + //post(':help', true); +} + +window.onpopstate = function (event) { + setCursorTo(event.state || ''); +}; + +setTimeout(function () { + window.scrollTo(0, 1); +}, 500); + +setTimeout(function () { + document.getElementById('footer').className = 'hidden'; +}, 5000); + +getProps('window'); // cache + +try { + if (!!(localStorage.large*1)) { + document.body.className = 'large'; + } +} catch (e) {} + + +if (document.addEventListener) document.addEventListener('deviceready', function () { + cursor.focus(); +}, false); + +// if (iOSMobile) { +// document.getElementById('footer').style.display = 'none'; +// alert('hidden'); +// } + +})(this); diff --git a/console/index.html b/console/index.html new file mode 100644 index 0000000..b03ea3b --- /dev/null +++ b/console/index.html @@ -0,0 +1,19 @@ + + + + +JavaScript console + + + +
+ +
+
+
    +
    + + + + + diff --git a/console/inject.html b/console/inject.html new file mode 100644 index 0000000..e77eb9c --- /dev/null +++ b/console/inject.html @@ -0,0 +1,18 @@ + + + + +Inject JS Console + + + + + +

    This page should redirect right away to the correct url, once it does, bookmarket it on your mobile phone, then remove the http://jsconsole.com/inject.html? (including the question mark) part to get the bookmarklet to work.

    +

    Alternatively, to inject JS Console, bookmarket this: JS Console and sync to your phone.

    + + \ No newline at end of file diff --git a/console/inject.js b/console/inject.js new file mode 100644 index 0000000..96da286 --- /dev/null +++ b/console/inject.js @@ -0,0 +1,38 @@ +(function (window, document) { + var iframe, doc; + + window.JSCONSOLE = { + contentWindow: window, + contentDocument: document, + console: iframe + }; + + if (iframe = document.getElementById('jsconsole')) { + document.getElementById('jsconsole').style.display = 'block'; + } else { + iframe = document.createElement('iframe'); + + document.body.appendChild(iframe); + + iframe.id = 'jsconsole'; + iframe.style.display = 'block'; + iframe.style.background = '#fff'; + iframe.style.zIndex = '9999'; + iframe.style.position = 'absolute'; + iframe.style.top = '0px'; + iframe.style.left = '0px'; + iframe.style.width = '100%'; + iframe.style.height = '100%'; + iframe.style.border = '0'; + + doc = iframe.contentDocument || iframe.contentWindow.document; + + doc.open(); + /* doc.write('jsconsole
      ');*/ + doc.close(); + + iframe.contentWindow.onload = function () { + this.document.getElementById('exec').focus(); + } + } +})(this, document); diff --git a/console/package.json b/console/package.json new file mode 100644 index 0000000..02d31c6 --- /dev/null +++ b/console/package.json @@ -0,0 +1,11 @@ +{ + "name": "jsconsole", + "version": "1.1.1", + "author": "Remy Sharp ", + "dependencies": { + "connect": ">= 1.4.0", + "node-uuid": ">= 1.1.0" + }, + "main": "server.js", + "private": true +} \ No newline at end of file diff --git a/console/prettify.js b/console/prettify.js new file mode 100644 index 0000000..93ba9a4 --- /dev/null +++ b/console/prettify.js @@ -0,0 +1,1479 @@ +// Copyright (C) 2006 Google Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +/** + * @fileoverview + * some functions for browser-side pretty printing of code contained in html. + * + * The lexer should work on a number of languages including C and friends, + * Java, Python, Bash, SQL, HTML, XML, CSS, Javascript, and Makefiles. + * It works passably on Ruby, PHP and Awk and a decent subset of Perl, but, + * because of commenting conventions, doesn't work on Smalltalk, Lisp-like, or + * CAML-like languages. + * + * If there's a language not mentioned here, then I don't know it, and don't + * know whether it works. If it has a C-like, Bash-like, or XML-like syntax + * then it should work passably. + * + * Usage: + * 1) include this source file in an html page via + * + * 2) define style rules. See the example page for examples. + * 3) mark the
       and  tags in your source with class=prettyprint.
      + *    You can also use the (html deprecated)  tag, but the pretty printer
      + *    needs to do more substantial DOM manipulations to support that, so some
      + *    css styles may not be preserved.
      + * That's it.  I wanted to keep the API as simple as possible, so there's no
      + * need to specify which language the code is in.
      + *
      + * Change log:
      + * cbeust, 2006/08/22
      + *   Java annotations (start with "@") are now captured as literals ("lit")
      + */
      +
      +var PR_keywords = {};
      +/** initialize the keyword list for our target languages. */
      +(function () {
      +  var CPP_KEYWORDS = "abstract bool break case catch char class const " +
      +    "const_cast continue default delete deprecated dllexport dllimport do " +
      +    "double dynamic_cast else enum explicit extern false float for friend " +
      +    "goto if inline int long mutable naked namespace new noinline noreturn " +
      +    "nothrow novtable operator private property protected public register " +
      +    "reinterpret_cast return selectany short signed sizeof static " +
      +    "static_cast struct switch template this thread throw true try typedef " +
      +    "typeid typename union unsigned using declaration, directive uuid " +
      +    "virtual void volatile while typeof";
      +  var CSHARP_KEYWORDS = "as base by byte checked decimal delegate descending " +
      +    "event finally fixed foreach from group implicit in interface internal " +
      +    "into is lock null object out override orderby params readonly ref sbyte " +
      +    "sealed stackalloc string select uint ulong unchecked unsafe ushort var";
      +  var JAVA_KEYWORDS = "package synchronized boolean implements import throws " +
      +    "instanceof transient extends final strictfp native super";
      +  var JSCRIPT_KEYWORDS = "debugger export function with NaN Infinity";
      +  var PERL_KEYWORDS = "require sub unless until use elsif BEGIN END";
      +  var PYTHON_KEYWORDS = "and assert def del elif except exec global lambda " +
      +    "not or pass print raise yield False True None";
      +  var RUBY_KEYWORDS = "then end begin rescue ensure module when undef next " +
      +    "redo retry alias defined";
      +  var SH_KEYWORDS = "done fi";
      +
      +  var KEYWORDS = [CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS,
      +                  JSCRIPT_KEYWORDS, PERL_KEYWORDS, PYTHON_KEYWORDS,
      +                  RUBY_KEYWORDS, SH_KEYWORDS];
      +  for (var k = 0; k < KEYWORDS.length; k++) {
      +    var kw = KEYWORDS[k].split(' ');
      +    for (var i = 0; i < kw.length; i++) {
      +      if (kw[i]) { PR_keywords[kw[i]] = true; }
      +    }
      +  }
      +}).call(this);
      +
      +// token style names.  correspond to css classes
      +/** token style for a string literal */
      +var PR_STRING = 'str';
      +/** token style for a keyword */
      +var PR_KEYWORD = 'kwd';
      +/** token style for a comment */
      +var PR_COMMENT = 'com';
      +/** token style for a type */
      +var PR_TYPE = 'typ';
      +/** token style for a literal value.  e.g. 1, null, true. */
      +var PR_LITERAL = 'lit';
      +/** token style for a punctuation string. */
      +var PR_PUNCTUATION = 'pun';
      +/** token style for a punctuation string. */
      +var PR_PLAIN = 'pln';
      +
      +/** token style for an sgml tag. */
      +var PR_TAG = 'tag';
      +/** token style for a markup declaration such as a DOCTYPE. */
      +var PR_DECLARATION = 'dec';
      +/** token style for embedded source. */
      +var PR_SOURCE = 'src';
      +/** token style for an sgml attribute name. */
      +var PR_ATTRIB_NAME = 'atn';
      +/** token style for an sgml attribute value. */
      +var PR_ATTRIB_VALUE = 'atv';
      +
      +/** the number of characters between tab columns */
      +var PR_TAB_WIDTH = 2;
      +
      +/** the position of the end of a token during.  A division of a string into
      +  * n tokens can be represented as a series n - 1 token ends, as long as
      +  * runs of whitespace warrant their own token.
      +  * @private
      +  */
      +function PR_TokenEnd(end, style) {
      +  if (undefined === style) { throw new Error('BAD'); }
      +  if ('number' != typeof(end)) { throw new Error('BAD'); }
      +  this.end = end;
      +  this.style = style;
      +}
      +PR_TokenEnd.prototype.toString = function () {
      +  return '[PR_TokenEnd ' + this.end +
      +    (this.style ? ':' + this.style : '') + ']';
      +};
      +
      +
      +/** a chunk of text with a style.  These are used to represent both the output
      +  * from the lexing functions as well as intermediate results.
      +  * @constructor
      +  * @param token the token text
      +  * @param style one of the token styles defined in designdoc-template, or null
      +  *   for a styleless token, such as an embedded html tag.
      +  * @private
      +  */
      +function PR_Token(token, style) {
      +  if (undefined === style) { throw new Error('BAD'); }
      +  this.token = token;
      +  this.style = style;
      +}
      +
      +PR_Token.prototype.toString = function () {
      +  return '[PR_Token ' + this.token + (this.style ? ':' + this.style : '') + ']';
      +};
      +
      +
      +/** a helper class that decodes common html entities used to escape special
      +  * characters in source code.
      +  * @constructor
      +  * @private
      +  */
      +function PR_DecodeHelper() {
      +  this.next = 0;
      +  this.ch = '\0';
      +}
      +
      +var PR_NAMED_ENTITIES = {
      +  'lt':   '<',
      +  'gt':   '>',
      +  'quot': '"',
      +  'apos': "'",
      +  'amp':  '&'   // reencoding requires that & always be decoded properly
      +};
      +
      +PR_DecodeHelper.prototype.decode = function (s, i) {
      +  var next = i + 1;
      +  var ch = s.charAt(i);
      +  if ('&' === ch) {
      +    var semi = s.indexOf(';', next);
      +    if (semi >= 0 && semi < next + 4) {
      +      var entityName = s.substring(next, semi);
      +      var decoded = null;
      +      if (entityName.charAt(0) === '#') {  // check for numeric entity
      +        var ch1 = entityName.charAt(1);
      +        var charCode;
      +        if (ch1 === 'x' || ch1 === 'X') {  // like &#xA0;
      +          charCode = parseInt(entityName.substring(2), 16);
      +        } else {  // like &#160;
      +          charCode = parseInt(entityName.substring(1), 10);
      +        }
      +        if (!isNaN(charCode)) {
      +          decoded = String.fromCharCode(charCode);
      +        }
      +      }
      +      if (!decoded) {
      +        decoded = PR_NAMED_ENTITIES[entityName.toLowerCase()];
      +      }
      +      if (decoded) {
      +        ch = decoded;
      +        next = semi + 1;
      +      } else {  // skip over unrecognized entity
      +        next = i + 1;
      +        ch = '\0';
      +      }
      +    }
      +  }
      +  this.next = next;
      +  this.ch = ch;
      +  return this.ch;
      +};
      +
      +
      +// some string utilities
      +function PR_isWordChar(ch) {
      +  return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
      +}
      +
      +function PR_isIdentifierStart(ch) {
      +  return PR_isWordChar(ch) || ch == '_' || ch == '$' || ch == '@';
      +}
      +
      +function PR_isIdentifierPart(ch) {
      +  return PR_isIdentifierStart(ch) || PR_isDigitChar(ch);
      +}
      +
      +function PR_isSpaceChar(ch) {
      +  return "\t \r\n".indexOf(ch) >= 0;
      +}
      +
      +function PR_isDigitChar(ch) {
      +  return ch >= '0' && ch <= '9';
      +}
      +
      +function PR_trim(s) {
      +  var i = 0, j = s.length - 1;
      +  while (i <= j && PR_isSpaceChar(s.charAt(i))) { ++i; }
      +  while (j > i && PR_isSpaceChar(s.charAt(j))) { --j; }
      +  return s.substring(i, j + 1);
      +}
      +
      +function PR_startsWith(s, prefix) {
      +  return s.length >= prefix.length && prefix == s.substring(0, prefix.length);
      +}
      +
      +function PR_endsWith(s, suffix) {
      +  return s.length >= suffix.length &&
      +         suffix == s.substring(s.length - suffix.length, s.length);
      +}
      +
      +/** true iff prefix matches the first prefix characters in chars[0:len].
      +  * @private
      +  */
      +function PR_prefixMatch(chars, len, prefix) {
      +  if (len < prefix.length) { return false; }
      +  for (var i = 0, n = prefix.length; i < n; ++i) {
      +    if (prefix.charAt(i) != chars[i]) { return false; }
      +  }
      +  return true;
      +}
      +
      +/** like textToHtml but escapes double quotes to be attribute safe. */
      +function PR_attribToHtml(str) {
      +  return str.replace(/&/g, '&amp;')
      +    .replace(/</g, '&lt;')
      +    .replace(/>/g, '&gt;')
      +    .replace(/\"/g, '&quot;')
      +    .replace(/\xa0/, '&nbsp;');
      +}
      +
      +/** escapest html special characters to html. */
      +function PR_textToHtml(str) {
      +  return str.replace(/&/g, '&amp;')
      +    .replace(/</g, '&lt;')
      +    .replace(/>/g, '&gt;')
      +    .replace(/\xa0/g, '&nbsp;');
      +}
      +
      +/** is the given node's innerHTML normally unescaped? */
      +function PR_isRawContent(node) {
      +  return 'XMP' == node.tagName;
      +}
      +
      +var PR_innerHtmlWorks = null;
      +function PR_getInnerHtml(node) {
      +  // inner html is hopelessly broken in Safari 2.0.4 when the content is
      +  // an html description of well formed XML and the containing tag is a PRE
      +   // tag, so we detect that case and emulate innerHTML.
      +  if (null == PR_innerHtmlWorks) {
      +    var testNode = document.createElement('PRE');
      +    testNode.appendChild(
      +        document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
      +    PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
      +  }
      +
      +  if (PR_innerHtmlWorks) {
      +    var content = node.innerHTML;
      +    // XMP tags contain unescaped entities so require special handling.
      +    if (PR_isRawContent(node)) {
      +       content = PR_textToHtml(content);
      +    }
      +    return content;
      +  }
      +
      +  var out = [];
      +  for (var child = node.firstChild; child; child = child.nextSibling) {
      +    PR_normalizedHtml(child, out);
      +  }
      +  return out.join('');
      +}
      +
      +/**
      + * walks the DOM returning a properly escaped version of innerHTML.
      + */
      +function PR_normalizedHtml(node, out) {
      +  switch (node.nodeType) {
      +    case 1:  // an element
      +      var name = node.tagName.toLowerCase();
      +      out.push('\074', name);
      +      for (var i = 0; i < node.attributes.length; ++i) {
      +        var attr = node.attributes[i];
      +        if (!attr.specified) { continue; }
      +        out.push(' ');
      +        PR_normalizedHtml(attr, out);
      +      }
      +      out.push('>');
      +      for (var child = node.firstChild; child; child = child.nextSibling) {
      +        PR_normalizedHtml(child, out);
      +      }
      +      if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
      +        out.push('<\/', name, '>');
      +      }
      +      break;
      +    case 2: // an attribute
      +      out.push(node.name.toLowerCase(), '="', PR_attribToHtml(node.value), '"');
      +      break;
      +    case 3: case 4: // text
      +      out.push(PR_textToHtml(node.nodeValue));
      +      break;
      +  }
      +}
      +
      +/** expand tabs to spaces
      +  * @param {Array} chunks PR_Tokens possibly containing tabs
      +  * @param {Number} tabWidth number of spaces between tab columns
      +  * @return {Array} chunks with tabs replaced with spaces
      +  */
      +function PR_expandTabs(chunks, tabWidth) {
      +  var SPACES = '                ';
      +
      +  var charInLine = 0;
      +  var decodeHelper = new PR_DecodeHelper();
      +
      +  var chunksOut = []
      +  for (var chunkIndex = 0; chunkIndex < chunks.length; ++chunkIndex) {
      +    var chunk = chunks[chunkIndex];
      +    if (chunk.style == null) {
      +      chunksOut.push(chunk);
      +      continue;
      +    }
      +
      +    var s = chunk.token;
      +    var pos = 0;  // index of last character output
      +    var out = [];
      +
      +    // walk over each character looking for tabs and newlines.
      +    // On tabs, expand them.  On newlines, reset charInLine.
      +    // Otherwise increment charInLine
      +    for (var charIndex = 0, n = s.length; charIndex < n;
      +         charIndex = decodeHelper.next) {
      +      decodeHelper.decode(s, charIndex);
      +      var ch = decodeHelper.ch;
      +
      +      switch (ch) {
      +        case '\t':
      +          out.push(s.substring(pos, charIndex));
      +          // calculate how much space we need in front of this part
      +          // nSpaces is the amount of padding -- the number of spaces needed to
      +          // move us to the next column, where columns occur at factors of
      +          // tabWidth.
      +          var nSpaces = tabWidth - (charInLine % tabWidth);
      +          charInLine += nSpaces;
      +          for (; nSpaces >= 0; nSpaces -= SPACES.length) {
      +            out.push(SPACES.substring(0, nSpaces));
      +          }
      +          pos = decodeHelper.next;
      +          break;
      +        case '\n': case '\r':
      +          charInLine = 0;
      +          break;
      +        default:
      +          ++charInLine;
      +      }
      +    }
      +    out.push(s.substring(pos));
      +    chunksOut.push(new PR_Token(out.join(''), chunk.style));
      +  }
      +  return chunksOut
      +}
      +
      +/** split markup into chunks of html tags (style null) and
      +  * plain text (style {@link #PR_PLAIN}).
      +  *
      +  * @param {String} s html.
      +  * @return {Array} of PR_Tokens of style PR_PLAIN, and null.
      +  * @private
      +  */
      +function PR_chunkify(s) {
      +  // The below pattern matches one of the following
      +  // (1) /[^<]+/ : A run of characters other than '<'
      +  // (2) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted
      +  // (3) /</ : A '<' that does not begin a larger chunk.  Treated as 1
      +  var chunkPattern = /(?:[^<]+|<\/?[a-zA-Z][^>]*>|<)/g;
      +  // since the pattern has the 'g' modifier and defines no capturing groups,
      +  // this will return a list of all chunks which we then classify and wrap as
      +  // PR_Tokens
      +  var matches = s.match(chunkPattern);
      +  var chunks = [];
      +  if (matches) {
      +    var lastChunk = null;
      +    for (var i = 0, n = matches.length; i < n; ++i) {
      +      var chunkText = matches[i];
      +      var style;
      +      if (chunkText.length < 2 || chunkText.charAt(0) !== '<') {
      +        if (lastChunk && lastChunk.style === PR_PLAIN) {
      +          lastChunk.token += chunkText;
      +          continue;
      +        }
      +        style = PR_PLAIN;
      +      } else {  // a tag
      +        style = null;
      +      }
      +      lastChunk = new PR_Token(chunkText, style);
      +      chunks.push(lastChunk);
      +    }
      +  }
      +  return chunks;
      +}
      +
      +/** walk the tokenEnds list and the chunk list in parallel to generate a list
      +  * of split tokens.
      +  * @private
      +  */
      +function PR_splitChunks(chunks, tokenEnds) {
      +  var tokens = [];  // the output
      +
      +  var ci = 0;  // index into chunks
      +  // position of beginning of amount written so far in absolute space.
      +  var posAbs = 0;
      +  // position of amount written so far in chunk space
      +  var posChunk = 0;
      +
      +  // current chunk
      +  var chunk = new PR_Token('', null);
      +
      +  for (var ei = 0, ne = tokenEnds.length, lastEnd = 0; ei < ne; ++ei) {
      +    var tokenEnd = tokenEnds[ei];
      +    var end = tokenEnd.end;
      +    if (end === lastEnd) { continue; }  // skip empty regions
      +
      +    var tokLen = end - posAbs;
      +    var remainingInChunk = chunk.token.length - posChunk;
      +    while (remainingInChunk <= tokLen) {
      +      if (remainingInChunk > 0) {
      +        tokens.push(
      +            new PR_Token(chunk.token.substring(posChunk, chunk.token.length),
      +                         null == chunk.style ? null : tokenEnd.style));
      +      }
      +      posAbs += remainingInChunk;
      +      posChunk = 0;
      +      if (ci < chunks.length) {
      +        chunk = chunks[ci++];
      +      }
      +
      +      tokLen = end - posAbs;
      +      remainingInChunk = chunk.token.length - posChunk;
      +    }
      +
      +    if (tokLen) {
      +      tokens.push(
      +          new PR_Token(chunk.token.substring(posChunk, posChunk + tokLen),
      +                       tokenEnd.style));
      +      posAbs += tokLen;
      +      posChunk += tokLen;
      +    }
      +  }
      +
      +  return tokens;
      +}
      +
      +/** splits markup tokens into declarations, tags, and source chunks.
      +  * @private
      +  */
      +function PR_splitMarkup(chunks) {
      +  // A state machine to split out declarations, tags, etc.
      +  // This state machine deals with absolute space in the text, indexed by k,
      +  // and position in the current chunk, indexed by pos and tokenStart to
      +  // generate a list of the ends of tokens.
      +  // Absolute space is calculated by considering the chunks as appended into
      +  // one big string, as they were before being split.
      +
      +  // Known failure cases
      +  // Server side scripting sections such as <?...?> in attributes.
      +  // i.e. <span class="<? foo ?>">
      +  // Handling this would require a stack, and we don't use PHP.
      +
      +  // The output: a list of pairs of PR_TokenEnd instances
      +  var tokenEnds = [];
      +
      +  var state = 0;  // FSM state variable
      +  var k = 0;  // position in absolute space of the start of the current chunk
      +  var tokenStart = -1;  // the start of the current token
      +
      +  // Try to find a closing tag for any open <style> or <script> tags
      +  // We can't do this at a later stage because then the following case
      +  // would fail:
      +  // <script>document.writeln('<!--');</script>
      +
      +  // We use tokenChars[:tokenCharsI] to accumulate the tag name so that we
      +  // can check whether to enter into a no scripting section when the tag ends.
      +  var tokenChars = new Array(12);
      +  var tokenCharsI = 0;
      +  // if non null, the tag prefix that we need to see to break out.
      +  var endScriptTag = null;
      +  var decodeHelper = new PR_DecodeHelper();
      +
      +  for (var ci = 0, nc = chunks.length; ci < nc; ++ci) {
      +    var chunk = chunks[ci];
      +    if (PR_PLAIN != chunk.style) {
      +      k += chunk.token.length;
      +      continue;
      +    }
      +
      +    var s = chunk.token;
      +    var pos = 0;  // the position past the last character processed so far in s
      +
      +    for (var i = 0, n = s.length; i < n; /* i = next at bottom */) {
      +      decodeHelper.decode(s, i);
      +      var ch = decodeHelper.ch;
      +      var next = decodeHelper.next;
      +
      +      var tokenStyle = null;
      +      switch (state) {
      +        case 0:
      +          if ('<' == ch) { state = 1; }
      +          break;
      +        case 1:
      +          tokenCharsI = 0;
      +          if ('/' == ch) {  // only consider close tags if we're in script/style
      +            state = 7;
      +          } else if (null == endScriptTag) {
      +            if ('!' == ch) {
      +              state = 2;
      +            } else if (PR_isWordChar(ch)) {
      +              state = 8;
      +            } else if ('?' == ch) {
      +              state = 9;
      +            } else if ('%' == ch) {
      +              state = 11;
      +            } else if ('<' != ch) {
      +              state = 0;
      +            }
      +          } else if ('<' != ch) {
      +            state = 0;
      +          }
      +          break;
      +        case 2:
      +          if ('-' == ch) {
      +            state = 4;
      +          } else if (PR_isWordChar(ch)) {
      +            state = 3;
      +          } else if ('<' == ch) {
      +            state = 1;
      +          } else {
      +            state = 0;
      +          }
      +          break;
      +        case 3:
      +          if ('>' == ch) {
      +            state = 0;
      +            tokenStyle = PR_DECLARATION;
      +          }
      +          break;
      +        case 4:
      +          if ('-' == ch) { state = 5; }
      +          break;
      +        case 5:
      +          if ('-' == ch) { state = 6; }
      +          break;
      +        case 6:
      +          if ('>' == ch) {
      +            state = 0;
      +            tokenStyle = PR_COMMENT;
      +          } else if ('-' == ch) {
      +            state = 6;
      +          } else {
      +            state = 4;
      +          }
      +          break;
      +        case 7:
      +          if (PR_isWordChar(ch)) {
      +            state = 8;
      +          } else if ('<' == ch) {
      +            state = 1;
      +          } else {
      +            state = 0;
      +          }
      +          break;
      +        case 8:
      +          if ('>' == ch) {
      +            state = 0;
      +            tokenStyle = PR_TAG;
      +          }
      +          break;
      +        case 9:
      +          if ('?' == ch) { state = 10; }
      +          break;
      +        case 10:
      +          if ('>' == ch) {
      +            state = 0;
      +            tokenStyle = PR_SOURCE;
      +          } else if ('?' != ch) {
      +            state = 9;
      +          }
      +          break;
      +        case 11:
      +          if ('%' == ch) { state = 12; }
      +          break;
      +        case 12:
      +          if ('>' == ch) {
      +            state = 0;
      +            tokenStyle = PR_SOURCE;
      +          } else if ('%' != ch) {
      +            state = 11;
      +          }
      +          break;
      +      }
      +
      +      if (tokenCharsI < tokenChars.length) {
      +        tokenChars[tokenCharsI++] = ch.toLowerCase();
      +      }
      +      if (1 == state) { tokenStart = k + i; }
      +      i = next;
      +      if (tokenStyle != null) {
      +        if (null != tokenStyle) {
      +          if (endScriptTag) {
      +            if (PR_prefixMatch(tokenChars, tokenCharsI, endScriptTag)) {
      +              endScriptTag = null;
      +            }
      +          } else {
      +            if (PR_prefixMatch(tokenChars, tokenCharsI, 'script')) {
      +              endScriptTag = '/script';
      +            } else if (PR_prefixMatch(tokenChars, tokenCharsI, 'style')) {
      +              endScriptTag = '/style';
      +            } else if (PR_prefixMatch(tokenChars, tokenCharsI, 'xmp')) {
      +              endScriptTag = '/xmp';
      +            }
      +          }
      +          // disallow the tag if endScriptTag is set and this was not an open
      +          // tag.
      +          if (endScriptTag && tokenCharsI && '/' == tokenChars[0]) {
      +            tokenStyle = null;
      +          }
      +        }
      +        if (null != tokenStyle) {
      +          tokenEnds.push(new PR_TokenEnd(tokenStart, PR_PLAIN));
      +          tokenEnds.push(new PR_TokenEnd(k + next, tokenStyle));
      +        }
      +      }
      +    }
      +    k += chunk.token.length;
      +  }
      +  tokenEnds.push(new PR_TokenEnd(k, PR_PLAIN));
      +
      +  return tokenEnds;
      +}
      +
      +/** splits the given string into comment, string, and "other" tokens.
      +  * @return {Array} of PR_Tokens with style in
      +  *   (PR_STRING, PR_COMMENT, PR_PLAIN, null)
      +  *   The result array may contain spurious zero length tokens.  Ignore them.
      +  *
      +  * @private
      +  */
      +function PR_splitStringAndCommentTokens(chunks) {
      +  // a state machine to split out comments, strings, and other stuff
      +  var tokenEnds = [];  // positions of ends of tokens in absolute space
      +  var state = 0;  // FSM state variable
      +  var delim = -1;  // string delimiter
      +  var k = 0;  // absolute position of beginning of current chunk
      +
      +  for (var ci = 0, nc = chunks.length; ci < nc; ++ci) {
      +    var chunk = chunks[ci];
      +    var s = chunk.token;
      +    if (PR_PLAIN == chunk.style) {
      +      var decodeHelper = new PR_DecodeHelper();
      +      var last = -1;
      +      var next;
      +      for (var i = 0, n = s.length; i < n; last = i, i = next) {
      +        decodeHelper.decode(s, i);
      +        var ch = decodeHelper.ch;
      +        next = decodeHelper.next;
      +        if (0 == state) {
      +          if (ch == '"' || ch == '\'' || ch == '`') {
      +            tokenEnds.push(new PR_TokenEnd(k + i, PR_PLAIN));
      +            state = 1;
      +            delim = ch;
      +          } else if (ch == '/') {
      +            state = 3;
      +          } else if (ch == '#') {
      +            tokenEnds.push(new PR_TokenEnd(k + i, PR_PLAIN));
      +            state = 4;
      +          }
      +        } else if (1 == state) {
      +          if (ch == delim) {
      +            state = 0;
      +            tokenEnds.push(new PR_TokenEnd(k + next, PR_STRING));
      +          } else if (ch == '\\') {
      +            state = 2;
      +          }
      +        } else if (2 == state) {
      +          state = 1;
      +        } else if (3 == state) {
      +          if (ch == '/') {
      +            state = 4;
      +            tokenEnds.push(new PR_TokenEnd(k + last, PR_PLAIN));
      +          } else if (ch == '*') {
      +            state = 5;
      +            tokenEnds.push(new PR_TokenEnd(k + last, PR_PLAIN));
      +          } else {
      +            state = 0;
      +            // next loop will reenter state 0 without same value of i, so
      +            // ch will be reconsidered as start of new token.
      +            next = i;
      +          }
      +        } else if (4 == state) {
      +          if (ch == '\r' || ch == '\n') {
      +            state = 0;
      +            tokenEnds.push(new PR_TokenEnd(k + i, PR_COMMENT));
      +          }
      +        } else if (5 == state) {
      +          if (ch == '*') {
      +            state = 6;
      +          }
      +        } else if (6 == state) {
      +          if (ch == '/') {
      +            state = 0;
      +            tokenEnds.push(new PR_TokenEnd(k + next, PR_COMMENT));
      +          } else if (ch != '*') {
      +            state = 5;
      +          }
      +        }
      +      }
      +    }
      +    k += s.length;
      +  }
      +  var endTokenType;
      +  switch (state) {
      +    case 1: case 2:
      +      endTokenType = PR_STRING;
      +      break;
      +    case 4: case 5: case 6:
      +      endTokenType = PR_COMMENT;
      +      break;
      +    default:
      +      endTokenType = PR_PLAIN;
      +      break;
      +  }
      +  // handle unclosed token which can legally happen for line comments (state 4)
      +  tokenEnds.push(new PR_TokenEnd(k, endTokenType));  // a token ends at the end
      +
      +  return PR_splitChunks(chunks, tokenEnds);
      +}
      +
      +/** used by lexSource to split a non string, non comment token.
      +  * @private
      +  */
      +function PR_splitNonStringNonCommentToken(s, outlist) {
      +  var pos = 0;
      +  var state = 0;
      +
      +  var decodeHelper = new PR_DecodeHelper();
      +  var next;
      +  for (var i = 0; i <= s.length; i = next) {
      +    if (i == s.length) {
      +      // nstate will not be equal to state, so it will append the token
      +      nstate = -2;
      +      next = i + 1;
      +    } else {
      +      decodeHelper.decode(s, i);
      +      next = decodeHelper.next;
      +      var ch = decodeHelper.ch;
      +
      +      // the next state.
      +      // if set to -1 then it will cause a reentry to state 0 without consuming
      +      // another character.
      +      var nstate = state;
      +
      +      switch (state) {
      +      case 0:  // whitespace state
      +        if (PR_isIdentifierStart(ch)) {
      +          nstate = 1;
      +        } else if (PR_isDigitChar(ch)) {
      +          nstate = 2;
      +        } else if (!PR_isSpaceChar(ch)) {
      +          nstate = 3;
      +        }
      +        if (nstate && pos < i) {
      +          var t = s.substring(pos, i);
      +          outlist.push(new PR_Token(t, PR_PLAIN));
      +          pos = i;
      +        }
      +        break;
      +      case 1:  // identifier state
      +        if (!PR_isIdentifierPart(ch)) {
      +          nstate = -1;
      +        }
      +        break;
      +      case 2:  // number literal state
      +        // handle numeric literals like
      +        // 0x7f 300UL 100_000
      +
      +        // this does not treat floating point values as a single literal
      +        //   0.1 and 3e-6
      +        // are each split into multiple tokens
      +        if (!(PR_isDigitChar(ch) || PR_isWordChar(ch) || ch == '_')) {
      +          nstate = -1;
      +        }
      +        break;
      +      case 3:  // punctuation state
      +        if (PR_isIdentifierStart(ch) || PR_isDigitChar(ch) ||
      +            PR_isSpaceChar(ch)) {
      +          nstate = -1;
      +        }
      +        break;
      +      }
      +    }
      +
      +    if (nstate != state) {
      +      if (nstate < 0) {
      +        if (i > pos) {
      +          var t = s.substring(pos, i);
      +          var wordDecodeHelper = new PR_DecodeHelper();
      +          wordDecodeHelper.decode(t, 0);
      +          var ch0 = wordDecodeHelper.ch;
      +          var isSingleCharacter = wordDecodeHelper.next == t.length;
      +          var style;
      +          if (PR_isIdentifierStart(ch0)) {
      +            if (PR_keywords[t]) {
      +              style = PR_KEYWORD;
      +            } else if (ch0 === '@') {
      +              style = PR_LITERAL;
      +            } else {
      +              // Treat any word that starts with an uppercase character and
      +              // contains at least one lowercase character as a type, or
      +              // ends with _t.
      +              // This works perfectly for Java, pretty well for C++, and
      +              // passably for Python.  The _t catches C structs.
      +              var isType = false;
      +              if (ch0 >= 'A' && ch0 <= 'Z') {
      +                for (var j = wordDecodeHelper.next;
      +                     j < t.length; j = wordDecodeHelper.next) {
      +                  wordDecodeHelper.decode(t, j);
      +                  var ch1 = wordDecodeHelper.ch;
      +                  if (ch1 >= 'a' && ch1 <= 'z') {
      +                    isType = true;
      +                    break;
      +                  }
      +                }
      +                if (!isType && !isSingleCharacter &&
      +                    t.substring(t.length - 2) == '_t') {
      +                  isType = true;
      +                }
      +              }
      +              style = isType ? PR_TYPE : PR_PLAIN;
      +            }
      +          } else if (PR_isDigitChar(ch0)) {
      +            style = PR_LITERAL;
      +          } else if (!PR_isSpaceChar(ch0)) {
      +            style = PR_PUNCTUATION;
      +          } else {
      +            style = PR_PLAIN;
      +          }
      +          pos = i;
      +          outlist.push(new PR_Token(t, style));
      +        }
      +
      +        state = 0;
      +        if (nstate == -1) {
      +          // don't increment.  This allows us to use state 0 to redispatch based
      +          // on the current character.
      +          next = i;
      +          continue;
      +        }
      +      }
      +      state = nstate;
      +    }
      +  }
      +
      +}
      +
      +/** split a group of chunks of markup.
      +  * @private
      +  */
      +function PR_tokenizeMarkup(chunks) {
      +  if (!(chunks && chunks.length)) { return chunks; }
      +
      +  var tokenEnds = PR_splitMarkup(chunks);
      +  return PR_splitChunks(chunks, tokenEnds);
      +}
      +
      +/** split tags attributes and their values out from the tag name, and
      +  * recursively lex source chunks.
      +  * @private
      +  */
      +function PR_splitTagAttributes(tokens) {
      +  var tokensOut = [];
      +  var state = 0;
      +  var stateStyle = PR_TAG;
      +  var delim = null;  // attribute delimiter for quoted value state.
      +  var decodeHelper = new PR_DecodeHelper();
      +  for (var ci = 0; ci < tokens.length; ++ci) {
      +    var tok = tokens[ci];
      +    if (PR_TAG == tok.style) {
      +      var s = tok.token;
      +      var start = 0;
      +      for (var i = 0; i < s.length; /* i = next at bottom */) {
      +        decodeHelper.decode(s, i);
      +        var ch = decodeHelper.ch;
      +        var next = decodeHelper.next;
      +
      +        var emitEnd = null;  // null or position of end of chunk to emit.
      +        var nextStyle = null;  // null or next value of stateStyle
      +        if (ch == '>') {
      +          if (PR_TAG != stateStyle) {
      +            emitEnd = i;
      +            nextStyle = PR_TAG;
      +          }
      +        } else {
      +          switch (state) {
      +            case 0:
      +              if ('<' == ch) { state = 1; }
      +              break;
      +            case 1:
      +              if (PR_isSpaceChar(ch)) { state = 2; }
      +              break;
      +            case 2:
      +              if (!PR_isSpaceChar(ch)) {
      +                nextStyle = PR_ATTRIB_NAME;
      +                emitEnd = i;
      +                state = 3;
      +              }
      +              break;
      +            case 3:
      +              if ('=' == ch) {
      +                emitEnd = i;
      +                nextStyle = PR_TAG;
      +                state = 5;
      +              } else if (PR_isSpaceChar(ch)) {
      +                emitEnd = i;
      +                nextStyle = PR_TAG;
      +                state = 4;
      +              }
      +              break;
      +            case 4:
      +              if ('=' == ch) {
      +                state = 5;
      +              } else if (!PR_isSpaceChar(ch)) {
      +                emitEnd = i;
      +                nextStyle = PR_ATTRIB_NAME;
      +                state = 3;
      +              }
      +              break;
      +            case 5:
      +              if ('"' == ch || '\'' == ch) {
      +                emitEnd = i;
      +                nextStyle = PR_ATTRIB_VALUE;
      +                state = 6;
      +                delim = ch;
      +              } else if (!PR_isSpaceChar(ch)) {
      +                emitEnd = i;
      +                nextStyle = PR_ATTRIB_VALUE;
      +                state = 7;
      +              }
      +              break;
      +            case 6:
      +              if (ch == delim) {
      +                emitEnd = next;
      +                nextStyle = PR_TAG;
      +                state = 2;
      +              }
      +              break;
      +            case 7:
      +              if (PR_isSpaceChar(ch)) {
      +                emitEnd = i;
      +                nextStyle = PR_TAG;
      +                state = 2;
      +              }
      +              break;
      +          }
      +        }
      +        if (emitEnd) {
      +          if (emitEnd > start) {
      +            tokensOut.push(
      +                new PR_Token(s.substring(start, emitEnd), stateStyle));
      +            start = emitEnd;
      +          }
      +          stateStyle = nextStyle;
      +        }
      +        i = next;
      +      }
      +      if (s.length > start) {
      +        tokensOut.push(new PR_Token(s.substring(start, s.length), stateStyle));
      +      }
      +    } else {
      +      if (tok.style) {
      +        state = 0;
      +        stateStyle = PR_TAG;
      +      }
      +      tokensOut.push(tok);
      +    }
      +  }
      +  return tokensOut;
      +}
      +
      +/** identify regions of markup that are really source code, and recursivley
      +  * lex them.
      +  * @private
      +  */
      +function PR_splitSourceNodes(tokens) {
      +  var tokensOut = [];
      +  // when we see a <script> tag, store '/' here so that we know to end the
      +  // source processing
      +  var endScriptTag = null;
      +  var decodeHelper = new PR_DecodeHelper();
      +
      +  var sourceChunks = null;
      +
      +  for (var ci = 0, nc = tokens.length; /* break below */; ++ci) {
      +    var tok;
      +
      +    if (ci < nc) {
      +      tok = tokens[ci];
      +      if (null == tok.style) {
      +        tokens.push(tok);
      +        continue;
      +      }
      +    } else if (!endScriptTag) {
      +      break;
      +    } else {
      +      // else pretend there's an end tag so we can gracefully handle
      +      // unclosed source blocks
      +      tok = new PR_Token('', null);
      +    }
      +
      +    var s = tok.token;
      +
      +    if (null == endScriptTag) {
      +      if (PR_SOURCE == tok.style) {
      +        // split off any starting and trailing <?, <%
      +        if ('<' == decodeHelper.decode(s, 0)) {
      +          decodeHelper.decode(s, decodeHelper.next);
      +          if ('%' == decodeHelper.ch || '?' == decodeHelper.ch) {
      +            endScriptTag = decodeHelper.ch;
      +            tokensOut.push(new PR_Token(s.substring(0, decodeHelper.next),
      +                                        PR_TAG));
      +            s = s.substring(decodeHelper.next, s.length);
      +          }
      +        }
      +      } else if (PR_TAG == tok.style) {
      +        if ('<' == decodeHelper.decode(s, 0) &&
      +            '/' != s.charAt(decodeHelper.next)) {
      +          var tagContent = s.substring(decodeHelper.next).toLowerCase();
      +          // FIXME(msamuel): this does not mirror exactly the code in
      +          // in PR_splitMarkup that defers splitting tags inside script and
      +          // style blocks.
      +          if (PR_startsWith(tagContent, 'script') ||
      +              PR_startsWith(tagContent, 'style') ||
      +              PR_startsWith(tagContent, 'xmp')) {
      +            endScriptTag = '/';
      +          }
      +        }
      +      }
      +    }
      +
      +    if (null != endScriptTag) {
      +      var endTok = null;
      +      if (PR_SOURCE == tok.style) {
      +        if (endScriptTag == '%' || endScriptTag == '?') {
      +          var pos = s.lastIndexOf(endScriptTag);
      +          if (pos >= 0 && '>' == decodeHelper.decode(s, pos + 1) &&
      +              s.length == decodeHelper.next) {
      +            endTok = new PR_Token(s.substring(pos, s.length), PR_TAG);
      +            s = s.substring(0, pos);
      +          }
      +        }
      +        if (null == sourceChunks) { sourceChunks = []; }
      +        sourceChunks.push(new PR_Token(s, PR_PLAIN));
      +      } else if (PR_PLAIN == tok.style) {
      +        if (null == sourceChunks) { sourceChunks = []; }
      +        sourceChunks.push(tok);
      +      } else if (PR_TAG == tok.style) {
      +        // if it starts with </ then it must be the end tag.
      +        if ('<' == decodeHelper.decode(tok.token, 0) &&
      +            tok.token.length > decodeHelper.next &&
      +            '/' == decodeHelper.decode(tok.token, decodeHelper.next)) {
      +          endTok = tok;
      +        } else {
      +          tokensOut.push(tok);
      +        }
      +      } else if (ci >= nc) {
      +        // force the token to close
      +        endTok = tok;
      +      } else {
      +        if (sourceChunks) {
      +          sourceChunks.push(tok);
      +        } else {
      +          // push remaining tag and attribute tokens from the opening tag
      +          tokensOut.push(tok);
      +        }
      +      }
      +      if (endTok) {
      +        if (sourceChunks) {
      +          var sourceTokens = PR_lexSource(sourceChunks);
      +          tokensOut.push(new PR_Token('<span class=embsrc>', null));
      +          for (var si = 0, ns = sourceTokens.length; si < ns; ++si) {
      +            tokensOut.push(sourceTokens[si]);
      +          }
      +          tokensOut.push(new PR_Token('</span>', null));
      +          sourceChunks = null;
      +        }
      +        if (endTok.token) { tokensOut.push(endTok); }
      +        endScriptTag = null;
      +      }
      +    } else {
      +      tokensOut.push(tok);
      +    }
      +  }
      +  return tokensOut;
      +}
      +
      +/** splits the quotes from an attribute value.
      +  * ['"foo"'] -> ['"', 'foo', '"']
      +  * @private
      +  */
      +function PR_splitAttributeQuotes(tokens) {
      +  var firstPlain = null, lastPlain = null;
      +  for (var i = 0; i < tokens.length; ++i) {
      +    if (PR_PLAIN == tokens[i].style) {
      +      firstPlain = i;
      +      break;
      +    }
      +  }
      +  for (var i = tokens.length; --i >= 0;) {
      +    if (PR_PLAIN == tokens[i].style) {
      +      lastPlain = i;
      +      break;
      +    }
      +  }
      +  if (null == firstPlain) { return tokens; }
      +
      +  var decodeHelper = new PR_DecodeHelper();
      +  var fs = tokens[firstPlain].token;
      +  var fc = decodeHelper.decode(fs, 0);
      +  if ('"' != fc && '\'' != fc) {
      +    return tokens;
      +  }
      +  var fpos = decodeHelper.next;
      +
      +  var ls = tokens[lastPlain].token;
      +  var lpos = ls.lastIndexOf('&');
      +  if (lpos < 0) { lpos = ls.length - 1; }
      +  var lc = decodeHelper.decode(ls, lpos);
      +  if (lc != fc || decodeHelper.next != ls.length) {
      +    lc = null;
      +    lpos = ls.length;
      +  }
      +
      +  var tokensOut = [];
      +  for (var i = 0; i < firstPlain; ++i) {
      +    tokensOut.push(tokens[i]);
      +  }
      +  tokensOut.push(new PR_Token(fs.substring(0, fpos), PR_ATTRIB_VALUE));
      +  if (lastPlain == firstPlain) {
      +    tokensOut.push(new PR_Token(fs.substring(fpos, lpos), PR_PLAIN));
      +  } else {
      +    tokensOut.push(new PR_Token(fs.substring(fpos, fs.length), PR_PLAIN));
      +    for (var i = firstPlain + 1; i < lastPlain; ++i) {
      +      tokensOut.push(tokens[i]);
      +    }
      +    if (lc) {
      +      tokens.push(new PR_Token(ls.substring(0, lpos), PR_PLAIN));
      +    } else {
      +      tokens.push(tokens[lastPlain]);
      +    }
      +  }
      +  if (lc) {
      +    tokensOut.push(new PR_Token(ls.substring(lpos, ls.length), PR_PLAIN));
      +  }
      +  for (var i = lastPlain + 1; i < tokens.length; ++i) {
      +    tokensOut.push(tokens[i]);
      +  }
      +  return tokensOut;
      +}
      +
      +/** identify attribute values that really contain source code and recursively
      +  * lex them.
      +  * @private
      +  */
      +function PR_splitSourceAttributes(tokens) {
      +  var tokensOut = [];
      +
      +  var sourceChunks = null;
      +  var inSource = false;
      +  var name = '';
      +
      +  for (var ci = 0, nc = tokens.length; ci < nc; ++ci) {
      +    var tok = tokens[ci];
      +    var outList = tokensOut;
      +    if (PR_TAG == tok.style) {
      +      if (inSource) {
      +        inSource = false;
      +        name = '';
      +        if (sourceChunks) {
      +          tokensOut.push(new PR_Token('<span class=embsrc>', null));
      +          var sourceTokens =
      +            PR_lexSource(PR_splitAttributeQuotes(sourceChunks));
      +          for (var si = 0, ns = sourceTokens.length; si < ns; ++si) {
      +            tokensOut.push(sourceTokens[si]);
      +          }
      +          tokensOut.push(new PR_Token('</span>', null));
      +          sourceChunks = null;
      +        }
      +      } else if (name && tok.token.indexOf('=') >= 0) {
      +        var nameLower = name.toLowerCase();
      +        if (PR_startsWith(nameLower, 'on') || 'style' == nameLower) {
      +          inSource = true;
      +        }
      +      } else {
      +        name = '';
      +      }
      +    } else if (PR_ATTRIB_NAME == tok.style) {
      +      name += tok.token;
      +    } else if (PR_ATTRIB_VALUE == tok.style) {
      +      if (inSource) {
      +        if (null == sourceChunks) { sourceChunks = []; }
      +        outList = sourceChunks;
      +        tok = new PR_Token(tok.token, PR_PLAIN);
      +      }
      +    } else {
      +      if (sourceChunks) {
      +        outList = sourceChunks;
      +      }
      +    }
      +    outList.push(tok);
      +  }
      +  return tokensOut;
      +}
      +
      +/** returns a list of PR_Token objects given chunks of source code.
      +  *
      +  * This code treats ", ', and ` as string delimiters, and \ as a string escape.
      +  * It does not recognize perl's qq() style strings.  It has no special handling
      +  * for double delimiter escapes as in basic, or tje tripled delimiters used in
      +  * python, but should work on those regardless although in those cases a single
      +  * string literal may be broken up into multiple adjacent string literals.
      +  *
      +  * It recognizes C, C++, and shell style comments.
      +  *
      +  * @param chunks PR_Tokens with style in (null, PR_PLAIN)
      +  */
      +function PR_lexSource(chunks) {
      +  // split into strings, comments, and other.
      +  // We do this because strings and comments are easily recognizable and can
      +  // contain stuff that looks like other tokens, so we want to mark those early
      +  // so we don't recurse into them.
      +  var tokens = PR_splitStringAndCommentTokens(chunks);
      +
      +  // split non comment|string tokens on whitespace and word boundaries
      +  var tokensOut = [];
      +  for (var i = 0; i < tokens.length; ++i) {
      +    var tok = tokens[i];
      +    if (PR_PLAIN === tok.style) {
      +      PR_splitNonStringNonCommentToken(tok.token, tokensOut);
      +      continue;
      +    }
      +    tokensOut.push(tok);
      +  }
      +
      +  return tokensOut;
      +}
      +
      +/** returns a list of PR_Token objects given a string of markup.
      +  *
      +  * This code assumes that < tokens are html escaped, but " are not.
      +  * It will do a resonable job with <, but will not recognize an &quot;
      +  * as starting a string.
      +  *
      +  * This code recognizes a number of constructs.
      +  * <!-- ... --> comment
      +  * <!\w ... >   declaration
      +  * <\w ... >    tag
      +  * </\w ... >   tag
      +  * <?...?>      embedded source
      +  * &[#\w]...;   entity
      +  *
      +  * It does not recognizes %foo; entities.
      +  *
      +  * It will recurse into any <style>, <script>, and on* attributes using
      +  * PR_lexSource.
      +  */
      +function PR_lexMarkup(chunks) {
      +  // This function works as follows:
      +  // 1) Start by splitting the markup into text and tag chunks
      +  //    Input:  String s
      +  //    Output: List<PR_Token> where style in (PR_PLAIN, null)
      +  // 2) Then split the text chunks further into comments, declarations,
      +  //    tags, etc.
      +  //    After each split, consider whether the token is the start of an
      +  //    embedded source section, i.e. is an open <script> tag.  If it is,
      +  //    find the corresponding close token, and don't bother to lex in between.
      +  //    Input:  List<String>
      +  //    Output: List<PR_Token> with style in (PR_TAG, PR_PLAIN, PR_SOURCE, null)
      +  // 3) Finally go over each tag token and split out attribute names and values.
      +  //    Input:  List<PR_Token>
      +  //    Output: List<PR_Token> where style in
      +  //            (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null)
      +  var tokensOut = PR_tokenizeMarkup(chunks);
      +  tokensOut = PR_splitTagAttributes(tokensOut);
      +  tokensOut = PR_splitSourceNodes(tokensOut);
      +  tokensOut = PR_splitSourceAttributes(tokensOut);
      +  return tokensOut;
      +}
      +
      +/**
      + * classify the string as either source or markup and lex appropriately.
      + * @param {String} html
      + */
      +function PR_lexOne(html) {
      +  var chunks = PR_expandTabs(PR_chunkify(html), PR_TAB_WIDTH);
      +
      +  // treat it as markup if the first non whitespace character is a < and the
      +  // last non-whitespace character is a >
      +  var isMarkup = false;
      +  for (var i = 0; i < chunks.length; ++i) {
      +    if (PR_PLAIN == chunks[i].style) {
      +      if (PR_startsWith(PR_trim(chunks[i].token), '&lt;')) {
      +        for (var j = chunks.length; --j >= 0;) {
      +          if (PR_PLAIN == chunks[j].style) {
      +            isMarkup = PR_endsWith(PR_trim(chunks[j].token), '&gt;');
      +            break;
      +          }
      +        }
      +      }
      +      break;
      +    }
      +  }
      +
      +  return isMarkup ? PR_lexMarkup(chunks) : PR_lexSource(chunks);
      +}
      +
      +/** pretty print a chunk of code.
      +  *
      +  * @param s code as html
      +  * @return code as html, but prettier
      +  */
      +function prettyPrintOne(s) {
      +  try {
      +    var tokens = PR_lexOne(s);
      +    var out = [];
      +    var lastStyle = null;
      +    for (var i = 0; i < tokens.length; i++) {
      +      var t = tokens[i];
      +      if (t.style != lastStyle) {
      +        if (lastStyle != null) {
      +          out.push('</span>');
      +        }
      +        if (t.style != null) {
      +          out.push('<span class=', t.style, '>');
      +        }
      +        lastStyle = t.style;
      +      }
      +      var html = t.token;
      +      if (null != t.style) {
      +        // This interacts badly with some wikis which introduces paragraph tags
      +        // into pre blocks for some strange reason.
      +        // It's necessary for IE though which seems to lose the preformattedness
      +        // of <pre> tags when their innerHTML is assigned.
      +        // http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
      +        html = html
      +               .replace(/(\r\n?|\n| ) /g, '$1&nbsp;')
      +               .replace(/\r\n?|\n/g, '<br>');
      +      }
      +      out.push(html);
      +    }
      +    if (lastStyle != null) {
      +      out.push('</span>');
      +    }
      +    return out.join('');
      +  } catch (e) {
      +    if ('console' in window) {
      +      console.log(e);
      +      console.trace();
      +    }
      +    return s;
      +  }
      +}
      +
      +/** find all the < pre > and < code > tags in the DOM with class=prettyprint and
      +  * prettify them.
      +  */
      +function prettyPrint(elements) {
      +  // fetch a list of nodes to rewrite
      +  var codeSegments = [];
      +  elements = elements || [];
      +  
      +  if (elements.length == 0) {
      +    codeSegments = [ document.getElementsByTagName('pre'),
      +        document.getElementsByTagName('code'),
      +        document.getElementsByTagName('xmp') ];
      +        
      +    for (var i = 0; i < codeSegments.length; ++i) {
      +      for (var j = 0; j < codeSegments[i].length; ++j) {
      +        elements.push(codeSegments[i][j]);
      +      }
      +    }
      +    codeSegments = null;
      +    
      +  }
      +
      +  // the loop is broken into a series of continuations to make sure that we
      +  // don't make the browser unresponsive when rewriting a large page.
      +  var k = 0;
      +
      +  function doWork() {
      +    var endTime = new Date().getTime() + 250;
      +    for (; k < elements.length && new Date().getTime() < endTime; k++) {
      +      var cs = elements[k];
      +      if (true || cs.className && cs.className.indexOf('prettyprint') >= 0) {
      +        // make sure this is not nested in an already prettified element
      +        var nested = false;
      +        for (var p = cs.parentNode; p != null; p = p.parentNode) {
      +          if ((p.tagName == 'pre' || p.tagName == 'code' ||
      +               p.tagName == 'xmp') &&
      +              p.className && p.className.indexOf('prettyprint') >= 0 || true) {
      +            nested = true;
      +            break;
      +          }
      +        }
      +        if (!nested) {
      +          // fetch the content as a snippet of properly escaped HTML.
      +          // Firefox adds newlines at the end.
      +          var content = PR_getInnerHtml(cs);
      +          content = content.replace(/(?:\r\n?|\n)$/, '');
      +
      +          // do the pretty printing
      +          var newContent = prettyPrintOne(content);
      +
      +          // push the prettified html back into the tag.
      +          if (!PR_isRawContent(cs)) {
      +            // just replace the old html with the new
      +            cs.innerHTML = newContent;
      +          } else {
      +            // we need to change the tag to a <pre> since <xmp>s do not allow
      +            // embedded tags such as the span tags used to attach styles to
      +            // sections of source code.
      +            var pre = document.createElement('PRE');
      +            for (var i = 0; i < cs.attributes.length; ++i) {
      +              var a = cs.attributes[i];
      +              if (a.specified) {
      +                pre.setAttribute(a.name, a.value);
      +              }
      +            }
      +            pre.innerHTML = newContent;
      +            // remove the old
      +            cs.parentNode.replaceChild(pre, cs);
      +          }
      +        }
      +      }
      +    }
      +    if (k < elements.length) {
      +      // finish up in a continuation
      +      setTimeout(doWork, 250);
      +    }
      +  }
      +
      +  doWork();
      +}
      \ No newline at end of file
      diff --git a/console/prettify.packed.js b/console/prettify.packed.js
      new file mode 100644
      index 0000000..52d2571
      --- /dev/null
      +++ b/console/prettify.packed.js
      @@ -0,0 +1,40 @@
      +// Copyright (C) 2006 Google Inc.
      +//
      +// Licensed under the Apache License, Version 2.0 (the "License");
      +// you may not use this file except in compliance with the License.
      +// You may obtain a copy of the License at
      +//
      +//      http://www.apache.org/licenses/LICENSE-2.0
      +//
      +// Unless required by applicable law or agreed to in writing, software
      +// distributed under the License is distributed on an "AS IS" BASIS,
      +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      +// See the License for the specific language governing permissions and
      +// limitations under the License.
      +
      +// RS modified to support any element being passed in (and compressed)
      +
      +(function(){function s(b,d){if(undefined===d)throw new Error("BAD");if("number"!=typeof b)throw new Error("BAD");this.end=b;this.style=d}function p(b,d){if(undefined===d)throw new Error("BAD");this.token=b;this.style=d}function v(){this.next=0;this.ch="\u0000"}function w(b){return b>="a"&&b<="z"||b>="A"&&b<="Z"}function z(b){return w(b)||b=="_"||b=="$"||b=="@"}function Q(b){return z(b)||x(b)}function t(b){return"\t \r\n".indexOf(b)>=0}function x(b){return b>="0"&&b<="9"}function I(b){for(var d=0,
      +a=b.length-1;d<=a&&t(b.charAt(d));)++d;for(;a>d&&t(b.charAt(a));)--a;return b.substring(d,a+1)}function y(b,d){return b.length>=d.length&&d==b.substring(0,d.length)}function R(b,d){return b.length>=d.length&&d==b.substring(b.length-d.length,b.length)}function A(b,d,a){if(d<a.length)return false;d=0;for(var c=a.length;d<c;++d)if(a.charAt(d)!=b[d])return false;return true}function S(b){return b.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\"/g,"&quot;").replace(/\xa0/,"&nbsp;")}
      +function J(b){return b.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\xa0/g,"&nbsp;")}function K(b){return"XMP"==b.tagName}function T(b){if(null==E){var d=document.createElement("PRE");d.appendChild(document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));E=!/</.test(d.innerHTML)}if(E){d=b.innerHTML;if(K(b))d=J(d);return d}d=[];for(b=b.firstChild;b;b=b.nextSibling)F(b,d);return d.join("")}function F(b,d){switch(b.nodeType){case 1:var a=b.tagName.toLowerCase();
      +d.push("<",a);for(var c=0;c<b.attributes.length;++c){var i=b.attributes[c];if(i.specified){d.push(" ");F(i,d)}}d.push(">");for(c=b.firstChild;c;c=c.nextSibling)F(c,d);if(b.firstChild||!/^(?:br|link|img)$/.test(a))d.push("</",a,">");break;case 2:d.push(b.name.toLowerCase(),'="',S(b.value),'"');break;case 3:case 4:d.push(J(b.nodeValue));break}}function U(b,d){for(var a=0,c=new v,i=[],h=0;h<b.length;++h){var j=b[h];if(j.style==null)i.push(j);else{for(var e=j.token,f=0,g=[],k=0,m=e.length;k<m;k=c.next){c.decode(e,
      +k);switch(c.ch){case "\t":g.push(e.substring(f,k));f=d-a%d;for(a+=f;f>=0;f-=16)g.push("                ".substring(0,f));f=c.next;break;case "\n":case "\r":a=0;break;default:++a}}g.push(e.substring(f));i.push(new p(g.join(""),j.style))}}return i}function V(b){b=b.match(/(?:[^<]+|<\/?[a-zA-Z][^>]*>|<)/g);var d=[];if(b)for(var a=null,c=0,i=b.length;c<i;++c){var h=b[c];if(h.length<2||h.charAt(0)!=="<"){if(a&&a.style===n){a.token+=h;continue}a=n}else a=null;a=new p(h,a);d.push(a)}return d}function L(b,
      +d){for(var a=[],c=0,i=0,h=0,j=new p("",null),e=0,f=d.length;e<f;++e){var g=d[e],k=g.end;if(k!==0){for(var m=k-i,q=j.token.length-h;q<=m;){if(q>0)a.push(new p(j.token.substring(h,j.token.length),null==j.style?null:g.style));i+=q;h=0;if(c<b.length)j=b[c++];m=k-i;q=j.token.length-h}if(m){a.push(new p(j.token.substring(h,h+m),g.style));i+=m;h+=m}}}return a}function W(b){for(var d=[],a=0,c=0,i=-1,h=new Array(12),j=0,e=null,f=new v,g=0,k=b.length;g<k;++g){var m=b[g];if(n==m.style)for(var q=m.token,l=0,
      +X=q.length;l<X;){f.decode(q,l);var o=f.ch,M=f.next,u=null;switch(a){case 0:if("<"==o)a=1;break;case 1:j=0;if("/"==o)a=7;else if(null==e)if("!"==o)a=2;else if(w(o))a=8;else if("?"==o)a=9;else if("%"==o)a=11;else{if("<"!=o)a=0}else if("<"!=o)a=0;break;case 2:a="-"==o?4:w(o)?3:"<"==o?1:0;break;case 3:if(">"==o){a=0;u=Y}break;case 4:if("-"==o)a=5;break;case 5:if("-"==o)a=6;break;case 6:if(">"==o){a=0;u=B}else a="-"==o?6:4;break;case 7:a=w(o)?8:"<"==o?1:0;break;case 8:if(">"==o){a=0;u=r}break;case 9:if("?"==
      +o)a=10;break;case 10:if(">"==o){a=0;u=C}else if("?"!=o)a=9;break;case 11:if("%"==o)a=12;break;case 12:if(">"==o){a=0;u=C}else if("%"!=o)a=11;break}if(j<h.length)h[j++]=o.toLowerCase();if(1==a)i=c+l;l=M;if(u!=null){if(null!=u){if(e){if(A(h,j,e))e=null}else if(A(h,j,"script"))e="/script";else if(A(h,j,"style"))e="/style";else if(A(h,j,"xmp"))e="/xmp";if(e&&j&&"/"==h[0])u=null}if(null!=u){d.push(new s(i,n));d.push(new s(c+M,u))}}}c+=m.token.length}d.push(new s(c,n));return d}function Z(b){for(var d=
      +[],a=0,c=-1,i=0,h=0,j=b.length;h<j;++h){var e=b[h],f=e.token;if(n==e.style){e=new v;for(var g=-1,k,m=0,q=f.length;m<q;g=m,m=k){e.decode(f,m);var l=e.ch;k=e.next;if(0==a)if(l=='"'||l=="'"||l=="`"){d.push(new s(i+m,n));a=1;c=l}else if(l=="/")a=3;else{if(l=="#"){d.push(new s(i+m,n));a=4}}else if(1==a)if(l==c){a=0;d.push(new s(i+k,N))}else{if(l=="\\")a=2}else if(2==a)a=1;else if(3==a)if(l=="/"){a=4;d.push(new s(i+g,n))}else if(l=="*"){a=5;d.push(new s(i+g,n))}else{a=0;k=m}else if(4==a){if(l=="\r"||l==
      +"\n"){a=0;d.push(new s(i+m,B))}}else if(5==a){if(l=="*")a=6}else if(6==a)if(l=="/"){a=0;d.push(new s(i+k,B))}else if(l!="*")a=5}}i+=f.length}switch(a){case 1:case 2:a=N;break;case 4:case 5:case 6:a=B;break;default:a=n;break}d.push(new s(i,a));return L(b,d)}function $(b,d){for(var a=0,c=0,i=new v,h,j=0;j<=b.length;j=h){if(j==b.length){f=-2;h=j+1}else{i.decode(b,j);h=i.next;var e=i.ch,f=c;switch(c){case 0:if(z(e))f=1;else if(x(e))f=2;else t(e)||(f=3);if(f&&a<j){e=b.substring(a,j);d.push(new p(e,n));
      +a=j}break;case 1:Q(e)||(f=-1);break;case 2:x(e)||w(e)||e=="_"||(f=-1);break;case 3:if(z(e)||x(e)||t(e))f=-1;break}}if(f!=c){if(f<0){if(j>a){e=b.substring(a,j);a=new v;a.decode(e,0);var g=a.ch;c=a.next==e.length;if(z(g))if(O[e])c=aa;else if(g==="@")c=P;else{var k=false;if(g>="A"&&g<="Z"){for(g=a.next;g<e.length;g=a.next){a.decode(e,g);g=a.ch;if(g>="a"&&g<="z"){k=true;break}}if(!k&&!c&&e.substring(e.length-2)=="_t")k=true}c=k?ba:n}else c=x(g)?P:t(g)?n:ca;a=j;d.push(new p(e,c))}c=0;if(f==-1){h=j;continue}}c=
      +f}}}function da(b){if(!(b&&b.length))return b;var d=W(b);return L(b,d)}function ea(b){for(var d=[],a=0,c=r,i=null,h=new v,j=0;j<b.length;++j){var e=b[j];if(r==e.style){e=e.token;for(var f=0,g=0;g<e.length;){h.decode(e,g);var k=h.ch,m=h.next,q=null,l=null;if(k==">"){if(r!=c){q=g;l=r}}else switch(a){case 0:if("<"==k)a=1;break;case 1:if(t(k))a=2;break;case 2:if(!t(k)){l=G;q=g;a=3}break;case 3:if("="==k){q=g;l=r;a=5}else if(t(k)){q=g;l=r;a=4}break;case 4:if("="==k)a=5;else if(!t(k)){q=g;l=G;a=3}break;
      +case 5:if('"'==k||"'"==k){q=g;l=D;a=6;i=k}else if(!t(k)){q=g;l=D;a=7}break;case 6:if(k==i){q=m;l=r;a=2}break;case 7:if(t(k)){q=g;l=r;a=2}break}if(q){if(q>f){d.push(new p(e.substring(f,q),c));f=q}c=l}g=m}e.length>f&&d.push(new p(e.substring(f,e.length),c))}else{if(e.style){a=0;c=r}d.push(e)}}return d}function fa(b){for(var d=[],a=null,c=new v,i=null,h=0,j=b.length;;++h){var e;if(h<j){e=b[h];if(null==e.style){b.push(e);continue}}else if(a)e=new p("",null);else break;var f=e.token;if(null==a)if(C==e.style){if("<"==
      +c.decode(f,0)){c.decode(f,c.next);if("%"==c.ch||"?"==c.ch){a=c.ch;d.push(new p(f.substring(0,c.next),r));f=f.substring(c.next,f.length)}}}else if(r==e.style)if("<"==c.decode(f,0)&&"/"!=f.charAt(c.next)){var g=f.substring(c.next).toLowerCase();if(y(g,"script")||y(g,"style")||y(g,"xmp"))a="/"}if(null!=a){g=null;if(C==e.style){if(a=="%"||a=="?"){e=f.lastIndexOf(a);if(e>=0&&">"==c.decode(f,e+1)&&f.length==c.next){g=new p(f.substring(e,f.length),r);f=f.substring(0,e)}}if(null==i)i=[];i.push(new p(f,n))}else if(n==
      +e.style){if(null==i)i=[];i.push(e)}else if(r==e.style)if("<"==c.decode(e.token,0)&&e.token.length>c.next&&"/"==c.decode(e.token,c.next))g=e;else d.push(e);else if(h>=j)g=e;else i?i.push(e):d.push(e);if(g){if(i){a=H(i);d.push(new p("<span class=embsrc>",null));i=0;for(f=a.length;i<f;++i)d.push(a[i]);d.push(new p("</span>",null));i=null}g.token&&d.push(g);a=null}}else d.push(e)}return d}function ga(b){for(var d=null,a=null,c=0;c<b.length;++c)if(n==b[c].style){d=c;break}for(c=b.length;--c>=0;)if(n==
      +b[c].style){a=c;break}if(null==d)return b;c=new v;var i=b[d].token,h=c.decode(i,0);if('"'!=h&&"'"!=h)return b;var j=c.next,e=b[a].token,f=e.lastIndexOf("&");if(f<0)f=e.length-1;var g=c.decode(e,f);if(g!=h||c.next!=e.length){g=null;f=e.length}h=[];for(c=0;c<d;++c)h.push(b[c]);h.push(new p(i.substring(0,j),D));if(a==d)h.push(new p(i.substring(j,f),n));else{h.push(new p(i.substring(j,i.length),n));for(c=d+1;c<a;++c)h.push(b[c]);g?b.push(new p(e.substring(0,f),n)):b.push(b[a])}g&&h.push(new p(e.substring(f,
      +e.length),n));for(c=a+1;c<b.length;++c)h.push(b[c]);return h}function ha(b){for(var d=[],a=null,c=false,i="",h=0,j=b.length;h<j;++h){var e=b[h],f=d;if(r==e.style)if(c){c=false;i="";if(a){d.push(new p("<span class=embsrc>",null));a=H(ga(a));for(var g=0,k=a.length;g<k;++g)d.push(a[g]);d.push(new p("</span>",null));a=null}}else if(i&&e.token.indexOf("=")>=0){g=i.toLowerCase();if(y(g,"on")||"style"==g)c=true}else i="";else if(G==e.style)i+=e.token;else if(D==e.style){if(c){if(null==a)a=[];f=a;e=new p(e.token,
      +n)}}else if(a)f=a;f.push(e)}return d}function H(b){b=Z(b);for(var d=[],a=0;a<b.length;++a){var c=b[a];n===c.style?$(c.token,d):d.push(c)}return d}function ia(b){b=da(b);b=ea(b);b=fa(b);return b=ha(b)}function ja(b){b=U(V(b),ka);for(var d=false,a=0;a<b.length;++a)if(n==b[a].style){if(y(I(b[a].token),"&lt;"))for(a=b.length;--a>=0;)if(n==b[a].style){d=R(I(b[a].token),"&gt;");break}break}return d?ia(b):H(b)}function la(b){try{for(var d=ja(b),a=[],c=null,i=0;i<d.length;i++){var h=d[i];if(h.style!=c){c!=
      +null&&a.push("</span>");h.style!=null&&a.push("<span class=",h.style,">");c=h.style}var j=h.token;if(null!=h.style)j=j.replace(/(\r\n?|\n| ) /g,"$1&nbsp;").replace(/\r\n?|\n/g,"<br>");a.push(j)}c!=null&&a.push("</span>");return a.join("")}catch(e){if("console"in window){console.log(e);console.trace()}return b}}function ma(b){function d(){for(var j=(new Date).getTime()+250;h<b.length&&(new Date).getTime()<j;h++){for(var e=b[h],f=false,g=e.parentNode;g!=null;g=g.parentNode)if((g.tagName=="pre"||g.tagName==
      +"code"||g.tagName=="xmp")&&g.className&&g.className.indexOf("prettyprint")>=0||1){f=true;break}if(!f){f=T(e);f=f.replace(/(?:\r\n?|\n)$/,"");f=la(f);if(K(e)){g=document.createElement("PRE");for(var k=0;k<e.attributes.length;++k){var m=e.attributes[k];m.specified&&g.setAttribute(m.name,m.value)}g.innerHTML=f;e.parentNode.replaceChild(g,e)}else e.innerHTML=f}}h<b.length&&setTimeout(d,250)}var a=[];b=b||[];if(b.length==0){a=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),
      +document.getElementsByTagName("xmp")];for(var c=0;c<a.length;++c)for(var i=0;i<a[c].length;++i)b.push(a[c][i]);a=null}var h=0;d()}var O={};(function(){for(var b=["abstract bool break case catch char class const const_cast continue default delete deprecated dllexport dllimport do double dynamic_cast else enum explicit extern false float for friend goto if inline int long mutable naked namespace new noinline noreturn nothrow novtable operator private property protected public register reinterpret_cast return selectany short signed sizeof static static_cast struct switch template this thread throw true try typedef typeid typename union unsigned using declaration, directive uuid virtual void volatile while typeof",
      +"as base by byte checked decimal delegate descending event finally fixed foreach from group implicit in interface internal into is lock null object out override orderby params readonly ref sbyte sealed stackalloc string select uint ulong unchecked unsafe ushort var","package synchronized boolean implements import throws instanceof transient extends final strictfp native super","debugger export function with NaN Infinity","require sub unless until use elsif BEGIN END","and assert def del elif except exec global lambda not or pass print raise yield False True None",
      +"then end begin rescue ensure module when undef next redo retry alias defined","done fi"],d=0;d<b.length;d++)for(var a=b[d].split(" "),c=0;c<a.length;c++)if(a[c])O[a[c]]=true}).call(this);var N="str",aa="kwd",B="com",ba="typ",P="lit",ca="pun",n="pln",r="tag",Y="dec",C="src",G="atn",D="atv",ka=2;s.prototype.toString=function(){return"[PR_TokenEnd "+this.end+(this.style?":"+this.style:"")+"]"};p.prototype.toString=function(){return"[PR_Token "+this.token+(this.style?":"+this.style:"")+"]"};var na={lt:"<",
      +gt:">",quot:'"',apos:"'",amp:"&"};v.prototype.decode=function(b,d){var a=d+1,c=b.charAt(d);if("&"===c){var i=b.indexOf(";",a);if(i>=0&&i<a+4){a=b.substring(a,i);c=null;if(a.charAt(0)==="#"){var h=a.charAt(1);h=h==="x"||h==="X"?parseInt(a.substring(2),16):parseInt(a.substring(1),10);isNaN(h)||(c=String.fromCharCode(h))}c||(c=na[a.toLowerCase()]);if(c){c=c;a=i+1}else{a=d+1;c="\u0000"}}}this.next=a;return this.ch=c};var E=null;window.prettyPrint=ma})();
      \ No newline at end of file
      diff --git a/console/remote-debugging.html b/console/remote-debugging.html
      new file mode 100644
      index 0000000..2705aca
      --- /dev/null
      +++ b/console/remote-debugging.html
      @@ -0,0 +1,96 @@
      +<!DOCTYPE html>
      +<html lang="en">
      +<head>
      +<meta charset=utf-8 />
      +<title>Remotely debugging mobile web apps</title>
      +<style>
      +  body {
      +    max-width: 720px;
      +    margin: 20px auto;
      +    padding: 0 20px;
      +    font: 1.0em/1.4em georgia, times;
      +    color: #212112;
      +  }
      +  
      +  h1, h2 {
      +    text-shadow: 0px 1px 5px #ddd;
      +  }
      +  
      +  h1 {
      +    margin: 1em 0;
      +  }
      +  
      +  h2 {
      +    margin-top: 1.4em;
      +  }
      +  
      +  p {
      +    margin: 1.4em 0;
      +  }
      +  
      +  code {
      +    font-size: 0.9em;
      +  }
      +  
      +  pre {
      +    border: 1px dashed #ddd;
      +    background: #f1f1f1;
      +    padding: 0.8em;
      +    overflow: auto;
      +  }
      +  
      +  iframe {
      +    margin: 0 auto;
      +    display: block;
      +  }
      +</style>
      +</head>
      +<body>
      +<h1>Remotely debug a mobile web app</h1>
      +<p><a href="/">jsconsole.com</a> is a simple JavaScript command line tool. However, it also provides the ability to bridge across to other browser windows to remotely control and debug that window - be it in another browser or another device altogether.</p>
      +<p>In fact, mobile web app debugging is so damn tricky, that I gave up, and decided to build <em>this</em> very tool instead. See the <a href="#videos">videos examples</a> if you'd rather see this in action now.</p>
      +
      +<h2>Creating a session</h2>
      +<p>To create a new session, in the jsconsole prompt, <a target="_blank" href="/?:listen">simply run</a>:</p>
      +<pre><code>:listen</code></pre>
      +<p>This will yield a unique key along the lines of <code>FAE031CD-74A0-46D3-AE36-757BAB262BEA</code>. Now using this unique key, include a <code>&lt;script&gt;</code> anywhere in the web app that you wish to debug:</p>
      +<pre><code>&lt;script src=&quot;http://jsconsole.com/remote.js?FAE031CD-74A0-46D3-AE36-757BAB262BEA&quot;&gt;&lt;/script&gt;</code></pre>
      +
      +<p>Now any calls to <code>console.log</code> from your web app will display the result in the jsconsole session that is listening to your key. Equally, if you run a command in the jsconsole session, the code will injected in to your web app and the result returned to jsconsole.</p>
      +
      +<p>In addition to generating a new code with <code>:listen</code>, you can also ask jsconsole to listen to a predefined code (but for your own security, try to chose something unique that only you know):</p>
      +
      +<pre><code>:listen FAE031CD-74A0-46D3-AE36-757BAB262BEA</code></pre>
      +
      +<p>Now I can use the same remote key in my web app to avoid having to regenerate a new code each time. Note that only the last remote client (i.e. your web app) to connect to jsconsole will recieve remote debug calls - previous windows will be ignored.</p>
      +
      +<p>To know when the web app has connected, jsconsole will notify you by showing your the <code>userAgent</code> string for the device:</p>
      +
      +<pre><code>:listen FAE031CD-74A0-46D3-AE36-757BAB262BEA
      +Creating connection...
      +Connected to "FAE031CD-74A0-46D3-AE36-757BAB262BEA"
      +Connection established with Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8</code></pre>
      +
      +<h2>A word of warning</h2>
      +<p>Note that this technique is also injecting code <em>directly</em> in to your web app - this tool should only be used for debugging. I can't take respibility for how you use this tool, basically: take care!</p>
      +
      +<h2>Current known support</h2>
      +<p>Remote debugging has been developed to work on all platforms, even if the technology isn't supported. However, jsconsole remote debugging has specifically tested and working on the follow mobile devices (feel free to add to this list):</p>
      +<ul>
      +  <li>iOS 4.2.x - iPad, iPhone 4</li>
      +  <li>Andriod 2.2.2 - Nexus One</li>
      +  <li>webOS - Palm Pre</li>
      +</ul>
      +
      +<h2 id="videos">Video exmaples</h2>
      +
      +<h3>Simple iOS simulator example</h3>
      +<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/Y219Ziuipvc?hd=1" frameborder="0" allowfullscreen></iframe>
      +
      +<h3>Full explanation and Android test</h3>
      +<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/DSH392Gxaho?hd=1" frameborder="0" allowfullscreen></iframe>
      +
      +
      +
      +</body>
      +</html>
      \ No newline at end of file
      diff --git a/console/remote.html b/console/remote.html
      new file mode 100644
      index 0000000..0432c9b
      --- /dev/null
      +++ b/console/remote.html
      @@ -0,0 +1,36 @@
      +<!DOCTYPE html>
      +<html lang="en">
      +<head>
      +<meta charset=utf-8 />
      +<title>remote</title>
      +</head>
      +<body>
      +<script src="/EventSource.js"></script>
      +<script>
      +var id = window.location.search.replace(/.*\?/, ''),
      +    origin = null;
      +window.addEventListener('message', function (event) {
      +  origin = event.origin;
      +
      +  if (event.data == '__init__') {
      +    return;
      +  }
      +
      +  var xhr = new XMLHttpRequest(),
      +      params = 'data=' + encodeURIComponent(event.data);
      +  
      +  xhr.open('POST', '/remote/' + id + '/log', true);
      +  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      +  xhr.send(params);    
      +
      +}, false);
      +
      +setTimeout(function () {
      +  var sse = new EventSource('/remote/' + id + '/run');
      +  sse.onmessage = function (event) {
      +    window.top.postMessage(event.data, origin);
      +  };
      +}, 13);
      +</script>
      +</body>
      +</html>
      diff --git a/console/remote.js b/console/remote.js
      new file mode 100644
      index 0000000..da13319
      --- /dev/null
      +++ b/console/remote.js
      @@ -0,0 +1,205 @@
      +;(function () {
      +
      +// 1. create iframe pointing to script on jsconsole.com domain
      +// 2. create console object with: log, dir, etc?
      +// 3. console.log runs postMessage with json.stringified content
      +// 4. jsconsole.com/remote/?id.onMessage = send to server, and wait for response. 
      +
      +function sortci(a, b) {
      +  return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
      +}
      +
      +// from console.js
      +function stringify(o, simple) {
      +  var json = '', i, type = ({}).toString.call(o), parts = [], names = [];
      +  
      +  if (type == '[object String]') {
      +    json = '"' + o.replace(/\n/g, '\\n').replace(/"/g, '\\"') + '"';
      +  } else if (type == '[object Array]') {
      +    json = '[';
      +    for (i = 0; i < o.length; i++) {
      +      parts.push(stringify(o[i], simple));
      +    }
      +    json += parts.join(', ') + ']';
      +    json;
      +  } else if (type == '[object Object]') {
      +    json = '{';
      +    for (i in o) {
      +      names.push(i);
      +    }
      +    names.sort(sortci);
      +    for (i = 0; i < names.length; i++) {
      +      parts.push(stringify(names[i]) + ': ' + stringify(o[names[i] ], simple));
      +    }
      +    json += parts.join(', ') + '}';
      +  } else if (type == '[object Number]') {
      +    json = o+'';
      +  } else if (type == '[object Boolean]') {
      +    json = o ? 'true' : 'false';
      +  } else if (type == '[object Function]') {
      +    json = o.toString();
      +  } else if (o === null) {
      +    json = 'null';
      +  } else if (o === undefined) {
      +    json = 'undefined';
      +  } else if (simple == undefined) {
      +    json = type + '{\n';
      +    for (i in o) {
      +      names.push(i);
      +    }
      +    names.sort(sortci);
      +    for (i = 0; i < names.length; i++) {
      +      parts.push(names[i] + ': ' + stringify(o[names[i]], true)); // safety from max stack
      +    }
      +    json += parts.join(',\n') + '\n}';
      +  } else {
      +    try {
      +      json = o+''; // should look like an object
      +    } catch (e) {}
      +  }
      +  return json;
      +}
      +
      +
      +// Plugins that inject are screwing this up :(
      +// function getLastChild(el) {
      +//   return (el.lastChild && el.lastChild.nodeName != '#text') ? getLastChild(el.lastChild) : el;
      +// }
      +
      +function getRemoteScript() {
      +  var scripts = document.getElementsByTagName('script'),
      +      remoteScript = scripts[scripts.length-1];
      +  for (var i = 0; i < scripts.length; i++) {
      +    if (/jsconsole\..*(:\d+)?\/remote.js/.test(scripts[i].src)) {
      +      remoteScript = scripts[i];
      +      break;
      +    }
      +  }
      +  
      +  return remoteScript;
      +}
      +
      +var last = getRemoteScript();
      +
      +// if (last.getAttribute('id') == '_firebugConsole') { // if Firebug is open, this all goes to crap
      +//   last = last.previousElementSibling;
      +// } 
      +
      +var lastSrc = last.getAttribute('src'),
      +    id = lastSrc.replace(/.*\?/, ''),
      +    origin = 'http://' + lastSrc.substr(7).replace(/\/.*$/, ''),
      +    remoteWindow = null,
      +    queue = [],
      +    msgType = '';
      +
      +var remoteFrame = document.createElement('iframe');
      +remoteFrame.style.display = 'none';
      +remoteFrame.src = origin + '/remote.html?' + id;
      +
      +// this is new - in an attempt to allow this code to be included in the head element
      +document.documentElement.appendChild(remoteFrame);
      +
      +
      +window.addEventListener('message', function (event) {
      +  if (event.origin != origin) return;
      +
      +  // eval the event.data command
      +  try {
      +    if (event.data.indexOf('console.log') == 0) {
      +      eval('remote.echo(' + event.data.match(/console.log\((.*)\);?/)[1] + ', "' + event.data + '", true)');
      +    } else {
      +      remote.echo(eval(event.data), event.data, undefined); // must be undefined to work
      +    }
      +  } catch (e) {
      +    remote.error(e, event.data);
      +  }
      +}, false);
      +
      +var remote = {
      +  log: function () {
      +    var argsObj = stringify(arguments.length == 1 ? arguments[0] : [].slice.call(arguments, 0));
      +    var response = [];
      +    [].forEach.call(arguments, function (args) {
      +      response.push(stringify(args, true));
      +    });
      +
      +	var msg = JSON.stringify({ response: response, cmd: 'remote console.log', type: msgType });
      +
      +    if (remoteWindow) {
      +      remoteWindow.postMessage(msg, origin);
      +    } else {
      +      queue.push(msg);
      +    }
      +    
      +    msgType = '';
      +  },
      +  info: function () {
      +    msgType = 'info';
      +    remote.log.apply(this, arguments);
      +  },
      +  echo: function () {
      +    var args = [].slice.call(arguments, 0),
      +        plain = args.pop(),
      +        cmd = args.pop(),
      +        response = args;
      +
      +    var argsObj = stringify(response, plain),
      +        msg = JSON.stringify({ response: argsObj, cmd: cmd });
      +    if (remoteWindow) {
      +      remoteWindow.postMessage(msg, origin);
      +    } else {
      +      queue.push(msg);
      +    }
      +  },
      +  error: function (error, cmd) {
      +    var msg = JSON.stringify({ response: error.message, cmd: cmd, type: 'error' });
      +    if (remoteWindow) {
      +      remoteWindow.postMessage(msg, origin);
      +    } else {
      +      queue.push(msg);
      +    }
      +  }
      +};
      +
      +// just for extra support
      +remote.debug = remote.dir = remote.log;
      +remote.warn = remote.info;
      +
      +remoteFrame.onload = function () {
      +  remoteWindow = remoteFrame.contentWindow;
      +  remoteWindow.postMessage('__init__', origin);
      +  
      +  remoteWindow.postMessage(stringify({ response: 'Connection established with ' + window.location.toString() + '\n' + navigator.userAgent, type: 'info' }), origin);
      +  
      +  for (var i = 0; i < queue.length; i++) {
      +    remoteWindow.postMessage(queue[i], origin);
      +  }
      +};
      +
      +window.remote = remote;
      +
      +window.addEventListener && window.addEventListener('error', function (event) {
      +  remote.error({ message: event.message }, event.filename + ':' + event.lineno);
      +}, false);
      +
      +try {
      +  window.console = remote;
      +} catch (e) {
      +  console.log('cannot overwrite existing console object');
      +}
      +
      +function warnUsage() {
      +  var useSS = false;
      +  try {
      +    sessionStorage.getItem('foo');
      +    useSS = true;
      +  } catch (e) {}
      +  if (!(useSS ? sessionStorage.jsconsole : window.name)) {
      +    if (useSS) sessionStorage.jsconsole = 1; else window.name = 1;
      +    alert('You will see this warning once per session.\n\nYou are using a remote control script on this site - if you accidently push it to production, anyone will have control of your visitor\'s browser. Remember to remove this script.');
      +  }
      +}
      +
      +warnUsage();
      +
      +})();
      diff --git a/console/server.js b/console/server.js
      new file mode 100644
      index 0000000..aa183de
      --- /dev/null
      +++ b/console/server.js
      @@ -0,0 +1,82 @@
      +// pending connect exposing static.mime (not available in npm yet)
      +var mime = require('connect/node_modules/mime');               
      +mime.define({ 'text/cache-manifest': ['appcache'] });                                                                             
      +
      +var connect = require('connect'),
      +    parse = require('url').parse,
      +    querystring = require('querystring').parse,
      +    sessions = { run: {}, log: {} },
      +    eventid = 0,
      +    uuid = require('node-uuid');
      +
      +function remoteServer(app) {
      +  app.get('/remote/:id?', function (req, res, next) {
      +    var url = parse(req.url),
      +        query = querystring(url.query);
      +
      +    // save a new session id - maybe give it a token back?
      +    // serve up some JavaScript
      +    var id = req.params.id || uuid();
      +    res.writeHead(200, {'Content-Type': 'text/javascript'});
      +    res.end((query.callback || 'callback') + '("' + id + '");');
      +  });
      +
      +  app.get('/remote/:id/log', function (req, res) {
      +    var id = req.params.id;
      +    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
      +    res.write('eventId:0\n\n');
      +
      +    sessions.log[id] = res;
      +    sessions.log[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
      +  });
      +
      +  app.post('/remote/:id/log', function (req, res) {
      +    // post made to send log to jsconsole
      +    var id = req.params.id;
      +    // passed over to Server Sent Events on jsconsole.com
      +    if (sessions.log[id]) {
      +      sessions.log[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');
      +
      +      if (sessions.log[id].xhr) {
      +        sessions.log[id].end(); // lets older browsers finish their xhr request
      +      }
      +    }
      +
      +    res.writeHead(200, { 'Content-Type' : 'text/plain' });
      +    res.end();
      +  });
      +
      +  app.get('/remote/:id/run', function (req, res) {
      +    var id = req.params.id;
      +    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
      +    res.write('eventId:0\n\n');
      +    sessions.run[id] = res;
      +    sessions.run[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
      +  });
      +
      +  app.post('/remote/:id/run', function (req, res) {
      +    var id = req.params.id;
      +
      +    if (sessions.run[id]) {
      +      sessions.run[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');
      +
      +      if (sessions.run[id].xhr) {
      +        sessions.run[id].end(); // lets older browsers finish their xhr request
      +      }
      +    }
      +    res.writeHead(200, { 'Content-Type' : 'text/plain' });
      +    res.end();
      +  });
      +}
      +
      +// connect.static.mime.define('text/cache-manifest', ['appcache']);
      +
      +var server = connect.createServer(
      +  connect.bodyParser(),
      +  connect.logger(),
      +  connect.static(__dirname),
      +  connect.router(remoteServer)
      +);
      +
      +console.log('Listening on ' + (process.argv[2] || 80));
      +server.listen(parseInt(process.argv[2]) || 80);