JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
preserve <script> tags and whitespace in plaintext elements
[peach-html5-editor.git] / editor.js
1 // Copyright 2015 Jason Woofenden
2 // This file implements an WYSIWYG editor in the browser (no contenteditable)
3 //
4 // This program is free software: you can redistribute it and/or modify it under
5 // the terms of the GNU Affero General Public License as published by the Free
6 // Software Foundation, either version 3 of the License, or (at your option) any
7 // later version.
8 //
9 // This program is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 // FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
12 // details.
13 //
14 // You should have received a copy of the GNU Affero General Public License
15 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 (function() {
18 var KEY_BACKSPACE, KEY_DELETE, KEY_DOWN, KEY_END, KEY_ENTER, KEY_ESCAPE, KEY_HOME, KEY_INSERT, KEY_LEFT, KEY_PAGE_DOWN, KEY_PAGE_UP, KEY_RIGHT, KEY_TAB, KEY_UP, breathing_room, control_key_codes, enc_attr_regex, enc_text_regex, event_return, find_prev_cursor_position, find_up_cursor_position, get_el_bounds, ignore_key_codes, js_attr_regex, multi_sp_regex, no_text_elements, overlay_padding, text_range_bounds, valid_attr_regex, void_elements, ws_props, xy_to_cursor, slice = [].slice
19
20 // SETTINGS
21 overlay_padding = 10
22 breathing_room = 30 // minimum pixels above/below cursor (scrolling)
23
24 function timeout (ms, cb) {
25         return setTimeout(cb, ms)
26 }
27
28 function next_frame (cb) {
29         if (window.requestAnimationFrame != null) {
30                 window.requestAnimationFrame(cb)
31         } else {
32                 timeout(16, cb)
33         }
34 }
35
36 function this_url_sans_path () {
37         var clip, ret
38         ret = "" + window.location.href
39         clip = ret.lastIndexOf('#')
40         if (clip > -1) {
41                 ret = ret.substr(0, clip)
42         }
43         clip = ret.lastIndexOf('?')
44         if (clip > -1) {
45                 ret = ret.substr(0, clip)
46         }
47         clip = ret.lastIndexOf('/')
48         if (clip > -1) {
49                 ret = ret.substr(0, clip + 1)
50         }
51         return ret
52 }
53
54 // table too look up the properties of various values for css's white-space
55 ws_props = {
56         normal: {
57                 space: false,           // spaces are not preserved/rendered
58                 newline: false,         // newlines are not preserved/rendered
59                 wrap: true,             // text is word-wrapped
60                 to_preserve: 'pre-wrap' // to preservespaces, change white-space to this
61         },
62         nowrap: {
63                 space: false,
64                 newline: false,
65                 wrap: false,
66                 to_preserve: 'pre'
67         },
68         'pre-line': {
69                 space: false,
70                 newline: true,
71                 wrap: true,
72                 to_preserve: 'pre-wrap'
73         },
74         pre: {
75                 space: true,
76                 newline: true,
77                 wrap: false,
78                 to_collapse: 'nowrap'
79         },
80         'pre-wrap': {
81                 space: true,
82                 newline: true,
83                 wrap: true,
84                 to_collapse: 'normal'
85         }
86 }
87
88 // xml 1.0 spec, chromium and firefox accept these, plus lots of unicode chars
89 valid_attr_regex = new RegExp('^[a-zA-Z_:][-a-zA-Z0-9_:.]*$')
90 // html5 spec is much more lax, but chromium won't let me make at attribute with the name "4"
91 js_attr_regex = new RegExp('^[oO][nN].')
92 // html5 spec says that only these characters are collapsable
93 multi_sp_regex = new RegExp('[\u0020\u0009\u000a\u000c\u000d][\u0020\u0009\u000a\u000c\u000d]')
94
95 function str_has_ws_run (str) {
96         return multi_sp_regex.test(str)
97 }
98
99 // text nodes don't have getBoundingClientRect(), so use selection api to find
100 // it.
101 get_el_bounds = window.bounds = function(el) {
102         var doc, range, rect, win, x_fix, y_fix
103         if (el.getBoundingClientRect != null) {
104                 rect = el.getBoundingClientRect()
105         } else {
106                 // text nodes don't have getBoundingClientRect(), so use range api
107                 range = el.ownerDocument.createRange()
108                 range.selectNodeContents(el)
109                 rect = range.getBoundingClientRect()
110         }
111         doc = el.ownerDocument.documentElement
112         win = el.ownerDocument.defaultView
113         y_fix = win.pageYOffset - doc.clientTop
114         x_fix = win.pageXOffset - doc.clientLeft
115         return {
116                 x: rect.left + x_fix,
117                 y: rect.top + y_fix,
118                 w: rect.width != null ? rect.width : rect.right - rect.left,
119                 h: rect.height != null ? rect.height : rect.top - rect.bottom
120         }
121 }
122
123 function is_display_block (el) {
124         if (el.nodeType === 1) {
125                 return window.getComputedStyle(el, null).getPropertyValue('display') === 'block'
126         }
127         return false
128 }
129
130 // Pass return value from dom event handlers to this.
131 // If they return false, this will addinionally stop propagation and default.
132 function event_return (e, bool) {
133         if (bool === false) {
134                 if (e.stopPropagation != null) {
135                         e.stopPropagation()
136                 }
137                 if (e.preventDefault != null) {
138                         e.preventDefault()
139                 }
140         }
141         return bool
142 }
143
144 // Warning: currently assumes you're asking about a single character
145 // Note: chromium returns multiple bounding rects for a space at a line-break
146 // Note: chromium's getBoundingClientRect() is broken (when zero-area client rects)
147 // Note: sometimes returns null (eg for whitespace that is not visible)
148 text_range_bounds = function(el, start, end) {
149         var doc, range, rect, rects, win, x_fix, y_fix
150         range = document.createRange()
151         range.setStart(el, start)
152         range.setEnd(el, end)
153         rects = range.getClientRects()
154         if (rects.length > 0) {
155                 if (rects.length > 1) {
156                         if (rects[1].width > rects[0].width) {
157                                 rect = rects[1]
158                         } else {
159                                 rect = rects[0]
160                         }
161                 } else {
162                         rect = rects[0]
163                 }
164         } else {
165                 return null
166         }
167         doc = el.ownerDocument.documentElement
168         win = el.ownerDocument.defaultView
169         y_fix = win.pageYOffset - doc.clientTop
170         x_fix = win.pageXOffset - doc.clientLeft
171         return {
172                 x: rect.left + x_fix,
173                 y: rect.top + y_fix,
174                 w: rect.width != null ? rect.width : rect.right - rect.left,
175                 h: rect.height != null ? rect.height : rect.top - rect.bottom,
176                 rects: rects,
177                 bounding: range.getBoundingClientRect()
178         }
179 }
180
181 function CursorPosition(args) {
182         this.n = args.n != null ? args.n : null
183         this.i = args.i != null ? args.i : null
184         if (args.x != null) {
185                 this.x = args.x
186                 this.y = args.y
187                 this.h = args.h
188         } else {
189                 this.set_xyh()
190         }
191 }
192
193 CursorPosition.prototype.set_xyh = function() {
194         var range, ret
195         range = document.createRange()
196         if (this.n.text.length === 0) {
197                 ret = text_range_bounds(this.n.el, 0, 0)
198         } else if (this.i === this.n.text.length) {
199                 ret = text_range_bounds(this.n.el, this.i - 1, this.i)
200                 if (ret != null) {
201                         ret.x += ret.w
202                 }
203         } else {
204                 ret = text_range_bounds(this.n.el, this.i, this.i + 1)
205         }
206         if (ret != null) {
207                 this.x = ret.x
208                 this.y = ret.y
209                 this.h = ret.h
210         } else {
211                 this.x = null
212                 this.y = null
213                 this.h = null
214         }
215         return ret
216 }
217
218 function new_cursor_position (args) {
219         var ret
220         ret = new CursorPosition(args)
221         if (ret.x != null) {
222                 return ret
223         }
224         return null
225 }
226
227 // html encoding for attributes
228 // encoding nbsp is not required, but hopefully it is useful
229 enc_attr_regex = new RegExp('(&)|(")|(\u00A0)', 'g')
230 function enc_attr (txt) {
231         return txt.replace(enc_attr_regex, function(match, amp, quote) {
232                 if (amp) {
233                         return '&amp;'
234                 }
235                 if (quote) {
236                         return '&quot;'
237                 }
238                 return '&nbsp;'
239         })
240 }
241 // html encoding for text (does nothing to stop whitespace collapse)
242 // encoding nbsp is not required, but hopefully it is useful
243 enc_text_regex = new RegExp('(&)|(<)|(\u00A0)', 'g')
244 function enc_text (txt) {
245         return txt.replace(enc_text_regex, function(match, amp, lt) {
246                 if (amp) {
247                         return '&amp;'
248                 }
249                 if (lt) {
250                         return '&lt;'
251                 }
252                 return '&nbsp;'
253         })
254 }
255
256 // no closing tag, cannot have children
257 void_elements = {
258         area: 1,
259         base: 1,
260         br: 1,
261         col: 1,
262         embed: 1,
263         hr: 1,
264         img: 1,
265         input: 1,
266         keygen: 1,
267         link: 1,
268         meta: 1,
269         param: 1,
270         source: 1,
271         track: 1,
272         wbr: 1
273 }
274
275 // contents are not html encoded
276 var plaintext_elements = {
277         style: 1,
278         script: 1,
279         xmp: 1,
280         iframe: 1,
281         noembed: 1,
282         noframes: 1,
283         plaintext: 1,
284         noscript: 1
285 }
286
287 // parser deletes a starting newline inside:
288 var newline_eating_elements = {
289         pre: 1,
290         textarea: 1,
291         listing: 1
292 }
293
294 // this does not pretty-print
295 function nodes_to_html (tree) {
296         var attr_keys, i, k, n, ret
297         ret = ''
298         for (i = 0; i < tree.length; ++i) {
299                 n = tree[i]
300                 switch (n.type) {
301                         case 'tag':
302                                 ret += '<' + n.name
303                                 attr_keys = []
304                                 for (k in n.attrs) {
305                                         ret += " " + k
306                                         if (n.attrs[k].length > 0) {
307                                                 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
308                                         }
309                                 }
310                                 ret += '>'
311                                 if (void_elements[n.name] == null) {
312                                         if (n.children.length) {
313                                                 ret += nodes_to_html(n.children)
314                                         }
315                                         ret += "</" + n.name + ">"
316                                 }
317                                 break
318                         case 'text':
319                                 if (n.parent != null ? plaintext_elements[n.parent.name] : false) {
320                                         ret += n.text
321                                 } else if (n.parent != null ? newline_eating_elements[n.parent.name] && n.text.charAt(0) === "\n" : false) {
322                                         ret += enc_text("\n" + n.text)
323                                 } else {
324                                         ret += enc_text(n.text)
325                                 }
326                                 break
327                         case 'comment':
328                                 ret += "<!--" + n.text + "-->" // TODO encode?
329                                 break
330                         case 'doctype':
331                                 ret += "<!DOCTYPE " + n.name
332                                 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
333                                         ret += " \"" + n.public_identifier + "\""
334                                 }
335                                 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
336                                         ret += " \"" + n.system_identifier + "\""
337                                 }
338                                 ret += ">"
339                 }
340         }
341         return ret
342 }
343
344 // TODO make these always pretty-print (on the inside) like blocks
345 // TODO careful though: whitespace might get pushed to parent, which might be rendered
346 no_text_elements = { // these elements never contain text
347         select: true,
348         table: true,
349         tr: true,
350         thead: true,
351         tbody: true,
352         ul: true,
353         ol: true
354 }
355
356 function domify (doc, hash) {
357         var attrs, el, i, k, tag, v
358         for (tag in hash) {
359                 attrs = hash[tag]
360                 if (tag === 'text') {
361                         return document.createTextNode(attrs)
362                 }
363                 el = document.createElement(tag)
364                 for (k in attrs) {
365                         v = attrs[k]
366                         if (k === 'children') {
367                                 for (i = 0; i < v.length; i++) {
368                                         el.appendChild(v[i])
369                                 }
370                         } else {
371                                 el.setAttribute(k, v)
372                         }
373                 }
374         }
375         return el
376 }
377
378 ignore_key_codes = {
379         '18': true,  // alt
380         '20': true,  // capslock
381         '17': true,  // ctrl
382         '144': true, // numlock
383         '16': true,  // shift
384         '91': true   // windows "start" key
385 }
386 // key codes: (valid on keydown, not keypress)
387 KEY_LEFT = 37
388 KEY_UP = 38
389 KEY_RIGHT = 39
390 KEY_DOWN = 40
391 KEY_BACKSPACE = 8 // <--
392 KEY_DELETE = 46 // -->
393 KEY_END = 35
394 KEY_ENTER = 13
395 KEY_ESCAPE = 27
396 KEY_HOME = 36
397 KEY_INSERT = 45
398 KEY_PAGE_UP = 33
399 KEY_PAGE_DOWN = 34
400 KEY_TAB = 9
401 control_key_codes = { // we react to these, but they aren't typing
402         '37': KEY_LEFT,
403         '38': KEY_UP,
404         '39': KEY_RIGHT,
405         '40': KEY_DOWN,
406         '35': KEY_END,
407          '8': KEY_BACKSPACE,
408         '46': KEY_DELETE,
409         '13': KEY_ENTER,
410         '27': KEY_ESCAPE,
411         '36': KEY_HOME,
412         '45': KEY_INSERT,
413         '33': KEY_PAGE_UP,
414         '34': KEY_PAGE_DOWN,
415          '9': KEY_TAB
416 }
417
418 function instantiate_tree (tree, parent) {
419         var c, i, k, remove, results, v
420         remove = []
421         for (i = 0; i < tree.length; ++i) {
422                 c = tree[i]
423                 switch (c.type) {
424                         case 'text':
425                                 c.el = parent.ownerDocument.createTextNode(c.text)
426                                 parent.appendChild(c.el)
427                         break
428                         case 'tag':
429                                 if (c.name === 'script' || c.name === 'object' || c.name === 'iframe' || c.name === 'link') {
430                                         // TODO make some placeholders visible
431                                         // problematic to have different type than c: c.el = parent.ownerDocument.createComment(c.name + ' tag here')
432                                         c.el = parent.ownerDocument.createElement(c.name)
433                                         // correct type, but empty and no attributes
434                                         continue
435                                 }
436                                 if (c.namespace === 'svg') {
437                                         c.el = parent.ownerDocument.createElementNS('http://www.w3.org/2000/svg', c.name)
438                                 } else if (c.namespace === 'mathml') {
439                                         c.el = parent.ownerDocument.createElementNS('http://www.w3.org/1998/Math/MathML', c.name)
440                                 } else {
441                                         c.el = parent.ownerDocument.createElement(c.name)
442                                 }
443                                 ref1 = c.attrs
444                                 for (k in ref1) {
445                                         v = ref1[k]
446                                         // FIXME if attr_whitelist[k]?
447                                         if (valid_attr_regex.test(k)) {
448                                                 if (!js_attr_regex.test(k)) {
449                                                         c.el.setAttribute(k, v)
450                                                 }
451                                         }
452                                 }
453                                 parent.appendChild(c.el)
454                                 if (c.children.length) {
455                                         instantiate_tree(c.children, c.el)
456                                 }
457                 }
458         }
459 }
460
461 function traverse_tree (tree, cb) {
462         var c, done, i
463         done = false
464         for (i = 0; i < tree.length; i++) {
465                 c = tree[i]
466                 done = cb(c)
467                 if (done) {
468                         return done
469                 }
470                 if (c.children.length) {
471                         done = traverse_tree(c.children, cb)
472                         if (done) {
473                                 return done
474                         }
475                 }
476         }
477         return done
478 }
479
480 function first_cursor_position (tree) {
481         var found
482         found = null
483         traverse_tree(tree, function(node, state) {
484                 var cursor
485                 if (node.type === 'text') {
486                         cursor = new_cursor_position({n: node, i: 0})
487                         if (cursor != null) {
488                                 found = cursor
489                                 return true // done traversing
490                         }
491                 }
492                 return false // not done traversing
493         })
494         return found // maybe null
495 }
496
497 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
498 function find_next_cursor_position (tree, cursor) {
499         var found, new_cursor, state_before
500         if (cursor.n.type === 'text' && cursor.n.text.length > cursor.i) {
501                 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i + 1})
502                 if (new_cursor != null) {
503                         return new_cursor
504                 }
505         }
506         state_before = true
507         found = null
508         traverse_tree(tree, function(node, state) {
509                 if (node.type === 'text' && state_before === false) {
510                         new_cursor = new_cursor_position({n: node, i: 0})
511                         if (new_cursor != null) {
512                                 found = new_cursor
513                                 return true // done traversing
514                         }
515                 }
516                 if (node === cursor.n) {
517                         state_before = false
518                 }
519                 return false // not done traversing
520         })
521         if (found != null) {
522                 return found
523         }
524         return null
525 }
526
527 function last_cursor_position (tree) {
528         var found
529         found = null
530         traverse_tree(tree, function(node) {
531                 var cursor
532                 if (node.type === 'text') {
533                         cursor = new_cursor_position({n: node, i: node.text.length})
534                         if (cursor != null) {
535                                 found = cursor
536                         }
537                 }
538                 return false // not done traversing
539         })
540         return found // maybe null
541 }
542
543 // this will fail when text has non-locatable cursor positions (eg collapsed whitespace)
544 function find_prev_cursor_position (tree, cursor) {
545         var found, found_prev, new_cursor
546         if (cursor.n.type === 'text' && cursor.i > 0) {
547                 new_cursor = new_cursor_position({n: cursor.n, i: cursor.i - 1})
548                 if (new_cursor != null) {
549                         return new_cursor
550                 }
551         }
552         found_prev = null
553         found = null
554         traverse_tree(tree, function(node) {
555                 if (node === cursor.n) {
556                         found = found_prev // maybe null
557                         return true // done traversing
558                 }
559                 if (node.type === 'text') {
560                         new_cursor = new_cursor_position({n: node, i: node.text.length})
561                         if (new_cursor != null) {
562                                 found_prev = new_cursor
563                         }
564                 }
565                 return false // not done traversing
566         })
567         return found // maybe null
568 }
569
570 function find_up_cursor_position (tree, cursor, ideal_x) {
571         var new_cursor, prev_cursor, target_y
572         new_cursor = cursor
573         // go prev until we're higher on y axis
574         while (new_cursor.y >= cursor.y) {
575                 new_cursor = find_prev_cursor_position(tree, new_cursor)
576                 if (new_cursor == null) {
577                         return null
578                 }
579         }
580         // done early if we're already left of old cursor position
581         if (new_cursor.x <= ideal_x) {
582                 return new_cursor
583         }
584         target_y = new_cursor.y
585         // search leftward, until we find the closest position
586         // new_cursor is the prev-most position we've checked
587         // prev_cursor is the older value, so it's not as prev as new_cursor
588         while (new_cursor.x > ideal_x && new_cursor.y === target_y) {
589                 prev_cursor = new_cursor
590                 new_cursor = find_prev_cursor_position(tree, new_cursor)
591                 if (new_cursor == null) {
592                         break
593                 }
594         }
595         // move cursor to prev_cursor or new_cursor
596         if (new_cursor != null) {
597                 if (new_cursor.y === target_y) {
598                         // both valid, and on the same line, use closest
599                         if ((ideal_x - new_cursor.x) < (prev_cursor.x - ideal_x)) {
600                                 return new_cursor
601                         } else {
602                                 return prev_cursor
603                         }
604                 } else {
605                         // new_cursor on wrong line, use prev_cursor
606                         return prev_cursor
607                 }
608         } else {
609                 // can't go any further prev, use prev_cursor
610                 return prev_cursor
611         }
612 }
613
614 function find_down_cursor_position (tree, cursor, ideal_x) {
615         var new_cursor, prev_cursor, target_y
616         new_cursor = cursor
617         // go next until we move on the y axis
618         while (new_cursor.y <= cursor.y) {
619                 new_cursor = find_next_cursor_position(tree, new_cursor)
620                 if (new_cursor == null) {
621                         return null
622                 }
623         }
624         // done early if we're already right of old cursor position
625         if (new_cursor.x >= ideal_x) {
626                 // this would be strange, but could happen due to runaround
627                 return new_cursor
628         }
629         target_y = new_cursor.y
630         // search rightward, until we find the closest position
631         // new_cursor is the next-most position we've checked
632         // prev_cursor is the older value, so it's not as next as new_cursor
633         while (new_cursor.x < ideal_x && new_cursor.y === target_y) {
634                 prev_cursor = new_cursor
635                 new_cursor = find_next_cursor_position(tree, new_cursor)
636                 if (new_cursor == null) {
637                         break
638                 }
639         }
640         if (new_cursor != null) {
641                 if (new_cursor.y === target_y) {
642                         // both valid, and on the same line, use closest
643                         if ((new_cursor.x - ideal_x) < (ideal_x - prev_cursor.x)) {
644                                 return new_cursor
645                         } else {
646                                 return prev_cursor
647                         }
648                 } else {
649                         // new_cursor on wrong line, use prev_cursor
650                         return prev_cursor
651                 }
652         } else {
653                 // can't go any further prev, use prev_cursor
654                 return prev_cursor
655         }
656 }
657
658 function xy_to_cursor (tree, xy) {
659         var after, before, bounds, cur, guess_i, i, n, ret
660         for (i = 0; i < tree.length; i++) {
661                 n = tree[i]
662                 if (n.type === 'tag' || n.type === 'text') {
663                         bounds = get_el_bounds(n.el)
664                         if (xy.x < bounds.x) {
665                                 continue
666                         }
667                         if (xy.x > bounds.x + bounds.w) {
668                                 continue
669                         }
670                         if (xy.y < bounds.y) {
671                                 continue
672                         }
673                         if (xy.y > bounds.y + bounds.h) {
674                                 continue
675                         }
676                         if (n.children.length) {
677                                 ret = xy_to_cursor(n.children, xy)
678                                 if (ret != null) {
679                                         return ret
680                                 }
681                         }
682                         if (n.type === 'text') {
683                                 // click is within bounding box that contains all text.
684                                 if (n.text.length === 0) {
685                                         ret = new_cursor_position({n: n, i: 0})
686                                         if (ret != null) {
687                                                 return ret
688                                         }
689                                         continue
690                                 }
691                                 before = new_cursor_position({n: n, i: 0})
692                                 if (before == null) {
693                                         continue
694                                 }
695                                 after = new_cursor_position({n: n, i: n.text.length})
696                                 if (after == null) {
697                                         continue
698                                 }
699                                 if (xy.y < before.y + before.h && xy.x < before.x) {
700                                         // console.log 'before first char on first line'
701                                         continue
702                                 }
703                                 if (xy.y > after.y && xy.x > after.x) {
704                                         // console.log 'after last char on last line'
705                                         continue
706                                 }
707                                 if (xy.y < before.y) {
708                                         console.log("Warning: click in text bounding box but above first line")
709                                         continue // above first line (runaround?)
710                                 }
711                                 if (xy.y > after.y + after.h) {
712                                         console.log("Warning: click in text bounding box but below last line", xy.y, after.y, after.h)
713                                         continue // below last line (shouldn't happen?)
714                                 }
715                                 while (after.i - before.i > 1) {
716                                         guess_i = Math.round((before.i + after.i) / 2)
717                                         cur = new_cursor_position({n: n, i: guess_i})
718                                         if (cur == null) {
719                                                 console.log("error: failed to find cursor pixel location for", n, guess_i)
720                                                 before = null
721                                                 break
722                                         }
723                                         if (xy.y < cur.y || (xy.y <= cur.y + cur.h && xy.x < cur.x)) {
724                                                 after = cur
725                                         } else {
726                                                 before = cur
727                                         }
728                                 }
729                                 if (before == null) { // signals failure to find a cursor position
730                                         continue
731                                 }
732                                 // which one is closest?
733                                 if (Math.abs(before.x - xy.x) < Math.abs(after.x - xy.x)) {
734                                         return before
735                                 } else {
736                                         return after
737                                 }
738                         }
739                 }
740         }
741         return null
742 }
743
744 // browsers collapse these (html5 spec calls these "space characters")
745 function is_space_code (char_code) {
746         switch (char_code) {
747                 case 9:
748                 case 10:
749                 case 12:
750                 case 13:
751                 case 32:
752                         return true
753         }
754         return false
755 }
756 function is_space (chr) {
757         return is_space_code(chr.charCodeAt(0))
758 }
759
760 function tree_remove_empty_text_nodes (tree) {
761         var c, empties, i, j, n
762         empties = []
763         traverse_tree(tree, function(n) {
764                 if (n.type === 'text') {
765                         if (n.text.length === 0) {
766                                 empties.unshift(n)
767                         }
768                 }
769                 return false // not done traversing
770         })
771         for (i = 0; i < empties.length; i++) {
772                 n = empties[i]
773                 // don't completely empty the tree
774                 if (tree.length === 1) {
775                         if (tree[0].type === 'text') {
776                                 console.log("oop, leaving a blank node because it's the only thing")
777                                 return
778                         }
779                 }
780                 n.el.parentNode.removeChild(n.el)
781                 ref = n.parent.children
782                 for (j = 0; j < ref.length; ++j) {
783                         c = ref[j]
784                         if (c === n) {
785                                 n.parent.children.splice(j, 1)
786                                 break
787                         }
788                 }
789         }
790 }
791
792 function PeachHTML5Editor (in_el, options) {
793         // Options: (all optional)
794         //   editor_id: "id" attribute for outer-most element created by/for editor
795         //   css_file: filename of a css file to style editable content
796         //   on_init: callback for when the editable content is in place
797         var css, opt_fragment, outer_bounds, outer_iframe_style, outer_wrap
798         this.options = options != null ? options : {}
799         this.pretty_print = options.pretty_print != null ? options.pretty_print : true
800         this.in_el = in_el
801         this.tree = null // array of Nodes, all editable content
802         this.tree_parent = null // this.tree is this.children. .el might === this.idoc.body
803         this.matting = []
804         this.init_1_called = false // when iframes have loaded
805         this.outer_iframe // iframe to hold editor
806         this.outer_idoc // "document" object for this.outer_iframe
807         this.input_el = null
808         this.wrap2 = null // scrollbar is on this
809         this.wrap2_offset = null
810         this.wrap2_height = null // including padding
811         this.iframe = null // iframe to hold editable content
812         this.idoc = null // "document" object for this.iframe
813         this.cursor = null
814         this.cursor_el = null
815         this.cursor_visible = false
816         this.cursor_ideal_x = null
817         opt_fragment = this.options.fragment != null ? this.options.fragment : true
818         this.parser_opts = {}
819         if (opt_fragment) {
820                 this.parser_opts.fragment = 'body'
821         }
822         this.outer_iframe = domify(document, {iframe: {}})
823         outer_iframe_style = 'border: none !important; margin: 0 !important; padding: 0 !important; height: 100% !important; width: 100% !important;'
824         if (this.options.editor_id != null) {
825                 this.outer_iframe.setAttribute('id', this.options.editor_id)
826         }
827         this.outer_iframe.onload = (function(_this) { return function() {
828                 var icss
829                 _this.outer_idoc = _this.outer_iframe.contentDocument
830                 icss = domify(_this.outer_idoc, { style: { children: [
831                         domify(_this.outer_idoc, {text: css})
832                 ]}})
833                 _this.outer_idoc.head.appendChild(icss)
834                 _this.input_el = domify(_this.outer_idoc, {textarea: {style: "position: relative; left: 100px"}}) // {style: "display: block; position: absolute; top: -1000px; left: 0; height: 500px; width 50em"}})
835                 _this.input_el.onblur = _this.onblur.bind(_this)
836                 _this.outer_idoc.body.appendChild(_this.input_el)
837                 _this.iframe = domify(_this.outer_idoc, {iframe: {sandbox: 'allow-same-origin allow-scripts'}})
838                 _this.iframe.onload = function() {
839                         return _this.init_1()
840                 }
841                 timeout(200, function() { // firefox never fires this onload
842                         if (!_this.init_1_called) {
843                                 return _this.init_1()
844                         }
845                 })
846                 _this.outer_idoc.body.appendChild(
847                         domify(_this.outer_idoc, {div: {id: 'wrap1', children: [
848                                 domify(_this.outer_idoc, {div: {
849                                         style: "position: absolute; top: 0; left: 1px; font-size: 10px",
850                                         children: [domify(_this.outer_idoc, {text: "Peach HTML5 Editor"})]
851                                 }}),
852                                 _this.wrap2 = domify(_this.outer_idoc, {div: {id: 'wrap2', children: [
853                                         domify(_this.outer_idoc, {div: {id: 'wrap3', children: [
854                                                 _this.iframe,
855                                                 _this.overlay = domify(_this.outer_idoc, { div: { id: 'overlay' }})
856                                         ]}})
857                                 ]}})
858                         ]}})
859                 )
860         }})(this)
861         outer_wrap = domify(document, {div: {"class": 'peach_html5_editor' }})
862         this.in_el.parentNode.appendChild(outer_wrap)
863         outer_bounds = get_el_bounds(outer_wrap)
864         if (outer_bounds.w < 300) {
865                 outer_bounds.w = 300
866         }
867         if (outer_bounds.h < 300) {
868                 outer_bounds.h = 300
869         }
870         outer_iframe_style += "width: " + outer_bounds.w + "px; height: " + outer_bounds.h + "px;"
871         this.outer_iframe.setAttribute('style', outer_iframe_style)
872         css = this.generate_outer_css({w: outer_bounds.w, h: outer_bounds.h})
873         outer_wrap.appendChild(this.outer_iframe)
874 }
875 PeachHTML5Editor.prototype.init_1 = function() { // this.iframe has loaded (but not it's css)
876         var istyle
877         this.idoc = this.iframe.contentDocument
878         this.init_1_called = true
879         // chromium doesn't resolve relative urls as though they were at the same domain
880         // so add a <base> tag
881         this.idoc.head.appendChild(domify(this.idoc, {base: {href: this_url_sans_path()}}))
882         // don't let @iframe have scrollbars
883         this.idoc.head.appendChild(domify(this.idoc, {style: {children: [
884                 domify(this.idoc, {text: "body { overflow: hidden; }"})
885         ]}}))
886         if (this.options.css_file) {
887                 istyle = domify(this.idoc, {link: {rel: 'stylesheet', href: this.options.css_file}})
888                 istyle.onload = (function(_this) {
889                         return function() {
890                                 return _this.init_2()
891                         }
892                 })(this)
893                 this.idoc.head.appendChild(istyle)
894         } else {
895                 this.init_2()
896         }
897 }
898 PeachHTML5Editor.prototype.init_2 = function() { // this.iframe and it's css file(s) are ready
899         var _this = this
900         var this_event_bind = function (cb) {
901                 return function (e) {
902                         _this.have_focus()
903                         event_return(e, _this[cb](e))
904                 }
905         }
906         this.overlay.onmousedown = this_event_bind('onclick')
907         this.overlay.ondoubleclick = this_event_bind('ondoubleclick')
908         this.outer_idoc.body.onkeyup = this_event_bind('onkeyup')
909         this.outer_idoc.body.onkeydown = this_event_bind('onkeydown')
910         this.outer_idoc.body.onkeypress = this_event_bind('onkeypress')
911         this.load_html(this.in_el.value)
912         if (this.options.on_init != null) {
913                 return this.options.on_init()
914         }
915 }
916 PeachHTML5Editor.prototype.generate_outer_css = function(args) {
917         var frame_width, h, inner_padding, occupy, ret, w
918         w = args.w != null ? args.w : 300
919         h = args.h != null ? args.h : 300
920         inner_padding = args.inner_padding != null ? args.inner_padding : overlay_padding
921         frame_width = args.frame_width != null ? args.frame_width : inner_padding
922         occupy = function(left, top, right, bottom) {
923                 if (top == null) {
924                         top = left
925                 }
926                 if (right == null) {
927                         right = left
928                 }
929                 if (bottom == null) {
930                         bottom = top
931                 }
932                 w -= left + right
933                 h -= top + bottom
934                 return Math.max(left, top, right, bottom)
935         }
936         ret = ''
937         ret += 'body {'
938         ret +=     'margin: 0;'
939         ret +=     'padding: 0;'
940         ret +=     'color: black;'
941         ret +=     'background: white;'
942         ret +=     'font-family: sans;'
943         ret += '}'
944         ret += '#wrap1 {'
945         ret +=     "border: " + (occupy(1)) + "px solid black;"
946         ret +=     "padding: " + (occupy(frame_width)) + "px;"
947         ret += '}'
948         ret += '#wrap2 {'
949         ret +=     "border: " + (occupy(1)) + "px solid black;"
950         this.wrap2_height = h // including padding because padding scrolls
951         ret +=     "padding: " + (occupy(inner_padding)) + "px;"
952         ret +=     "padding-right: " + (inner_padding + occupy(0, 0, 15, 0)) + "px;"
953         ret +=     "width: " + w + "px;"
954         ret +=     "height: " + h + "px;"
955         ret += 'overflow-x: hidden;'
956         ret += 'overflow-y: scroll;'
957         ret += '}'
958         ret += '#wrap3 {'
959         ret += 'position: relative;'
960         ret +=     "width: " + w + "px;"
961         ret +=     "min-height: " + h + "px;"
962         ret += '}'
963         ret += 'iframe {'
964         ret += 'box-sizing: border-box;'
965         ret += 'margin: 0;'
966         ret += 'border: none;'
967         ret += 'padding: 0;'
968         ret +=     "width: " + w + "px;"
969         //ret +=     "height: " + h + "px;" // height auto-set when content set/changed
970         ret +=     '-ms-user-select: none;'
971         ret +=     '-webkit-user-select: none;'
972         ret +=     '-moz-user-select: none;'
973         ret +=     'user-select: none;'
974         ret += '}'
975         ret += '#overlay {'
976         ret +=     'position: absolute;'
977         ret +=     "left: -" + inner_padding + "px;"
978         ret +=     "top: -" + inner_padding + "px;"
979         ret +=     "right: -" + inner_padding + "px;"
980         ret +=     "bottom: -" + inner_padding + "px;"
981         ret +=     'overflow: hidden;'
982         ret += '}'
983         ret += '.lightbox {'
984         ret +=     'position: absolute;'
985         ret +=     'background: rgba(100,100,100,0.2);'
986         ret += '}'
987         ret += '#cursor {'
988         ret +=     'position: absolute;'
989         ret +=     'width: 2px;'
990         ret +=     'background: linear-gradient(0deg, rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1), rgba(255,255,255,1), rgba(0,0,0,1));'
991         ret +=     'background-size: 200% 200%;'
992         ret +=     '-webkit-animation: blink 1s linear normal infinite;'
993         ret +=     'animation: blink 1s linear normal infinite;'
994         ret += '}'
995         ret += '@-webkit-keyframes blink {'
996         ret +=     '0%{background-position:0% 0%}'
997         ret +=     '100%{background-position:0% -100%}'
998         ret += '}'
999         ret += '@keyframes blink { '
1000         ret +=     '0%{background-position:0% 0%}'
1001         ret +=     '100%{background-position:0% -100%}'
1002         ret += '}'
1003         ret += '.ann_box {'
1004         ret +=     'z-index: 5;'
1005         ret +=     'position: absolute;'
1006         ret +=     'border: 1px solid rgba(0,0,0,0.1);'
1007         ret +=     'outline: 1px solid rgba(255,255,255,0.1);' // in case there's a black background
1008         ret += '}'
1009         ret += '.ann_tag {'
1010         ret +=     'z-index: 10;'
1011         ret +=     'position: absolute;'
1012         ret +=     'font-size: 8px;'
1013         ret +=     'white-space: pre;'
1014         ret +=     'background: rgba(255,255,255,0.4);'
1015         ret +=     '-ms-user-select: none;'
1016         ret +=     '-webkit-user-select: none;'
1017         ret +=     '-moz-user-select: none;'
1018         ret +=     'user-select: none;'
1019         ret += '}'
1020         return ret
1021 }
1022 PeachHTML5Editor.prototype.overlay_event_to_inner_xy = function(e) {
1023         var x, y
1024         if (this.wrap2_offset == null) {
1025                 this.wrap2_offset = get_el_bounds(this.wrap2)
1026         }
1027         x = e.pageX - overlay_padding
1028         y = e.pageY - overlay_padding + this.wrap2.scrollTop
1029         return {
1030                 x: x - this.wrap2_offset.x,
1031                 y: y - this.wrap2_offset.y
1032         }
1033 }
1034 PeachHTML5Editor.prototype.onclick = function(e) {
1035         var new_cursor, xy
1036         xy = this.overlay_event_to_inner_xy(e)
1037         new_cursor = xy_to_cursor(this.tree, xy)
1038         if (new_cursor != null) {
1039                 this.move_cursor(new_cursor)
1040         } else {
1041                 this.kill_cursor()
1042         }
1043         return false
1044 }
1045 PeachHTML5Editor.prototype.ondoubleclick = function(e) {
1046         return false
1047 }
1048 PeachHTML5Editor.prototype.onkeyup = function(e) {
1049         if (e.ctrlKey) {
1050                 return
1051         }
1052         if (ignore_key_codes[e.keyCode] != null) {
1053                 return false
1054         }
1055         //return false if control_key_codes[e.keyCode] != null
1056 }
1057 PeachHTML5Editor.prototype.onkeydown = function(e) {
1058         var new_cursor, saved_ideal_x
1059         if (e.ctrlKey) {
1060                 return
1061         }
1062         if (ignore_key_codes[e.keyCode] != null) {
1063                 return false
1064         }
1065         //return false if control_key_codes[e.keyCode] != null
1066         switch (e.keyCode) {
1067                 case KEY_LEFT:
1068                         if (this.cursor != null) {
1069                                 new_cursor = find_prev_cursor_position(this.tree, this.cursor)
1070                         } else {
1071                                 new_cursor = first_cursor_position(this.tree)
1072                         }
1073                         if (new_cursor != null) {
1074                                 this.move_cursor(new_cursor)
1075                         }
1076                         return false
1077                 case KEY_RIGHT:
1078                         if (this.cursor != null) {
1079                                 new_cursor = find_next_cursor_position(this.tree, this.cursor)
1080                         } else {
1081                                 new_cursor = last_cursor_position(this.tree)
1082                         }
1083                         if (new_cursor != null) {
1084                                 this.move_cursor(new_cursor)
1085                         }
1086                         return false
1087                 case KEY_UP:
1088                         if (this.cursor != null) {
1089                                 new_cursor = find_up_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1090                                 if (new_cursor != null) {
1091                                         saved_ideal_x = this.cursor_ideal_x
1092                                         this.move_cursor(new_cursor)
1093                                         this.cursor_ideal_x = saved_ideal_x
1094                                 }
1095                         } else {
1096                                 // move cursor to first position in document
1097                                 new_cursor = first_cursor_position(this.tree)
1098                                 if (new_cursor != null) {
1099                                         this.move_cursor(new_cursor)
1100                                 }
1101                         }
1102                         return false
1103                 case KEY_DOWN:
1104                         if (this.cursor != null) {
1105                                 new_cursor = find_down_cursor_position(this.tree, this.cursor, this.cursor_ideal_x)
1106                                 if (new_cursor != null) {
1107                                         saved_ideal_x = this.cursor_ideal_x
1108                                         this.move_cursor(new_cursor)
1109                                         this.cursor_ideal_x = saved_ideal_x
1110                                 }
1111                         } else {
1112                                 // move cursor to first position in document
1113                                 new_cursor = last_cursor_position(this.tree)
1114                                 if (new_cursor != null) {
1115                                         this.move_cursor(new_cursor)
1116                                 }
1117                         }
1118                         return false
1119                 case KEY_END:
1120                         new_cursor = last_cursor_position(this.tree)
1121                         if (new_cursor != null) {
1122                                 this.move_cursor(new_cursor)
1123                         }
1124                         return false
1125                 case KEY_BACKSPACE:
1126                         this.on_key_backspace(e)
1127                         return false
1128                 case KEY_DELETE:
1129                         if (this.cursor == null) {
1130                                 return false
1131                         }
1132                         new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: this.cursor.i})
1133                         // try moving cursor right and then running backspace code
1134                         // TODO replace this hack with a real implementation
1135                         if (new_cursor != null) {
1136                                 // try to detect common case where cursor goes inside an block,
1137                                 // but doesn't pass a character (and advance one more in that case)
1138                                 if (new_cursor.n !== this.cursor.n && new_cursor.i === 0) {
1139                                         if (new_cursor.n.type === 'text' && new_cursor.n.text.length > 0) {
1140                                                 if (new_cursor.n.parent != null) {
1141                                                         if (!this.is_display_block(new_cursor.n.parent)) {
1142                                                                 // FIXME should test run sibling
1143                                                                 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i + 1})
1144                                                         }
1145                                                 }
1146                                         }
1147                                 }
1148                         }
1149                         if (new_cursor != null) {
1150                                 if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1151                                         this.move_cursor(new_cursor)
1152                                         this.on_key_backspace(e)
1153                                 }
1154                         }
1155                         return false
1156                 case KEY_ENTER:
1157                         this.on_key_enter(e)
1158                         return false
1159                 case KEY_ESCAPE:
1160                         this.kill_cursor()
1161                         return false
1162                 case KEY_HOME:
1163                         new_cursor = first_cursor_position(this.tree)
1164                         if (new_cursor != null) {
1165                                 this.move_cursor(new_cursor)
1166                         }
1167                         return false
1168                 case KEY_INSERT:
1169                         return false
1170                 case KEY_PAGE_UP:
1171                         this.on_page_up_key(e)
1172                         return false
1173                 case KEY_PAGE_DOWN:
1174                         this.on_page_down_key(e)
1175                         return false
1176                 case KEY_TAB:
1177                         return false
1178         }
1179 }
1180 PeachHTML5Editor.prototype.onkeypress = function(e) {
1181         var char, new_cursor
1182         if (e.ctrlKey) {
1183                 return
1184         }
1185         if (ignore_key_codes[e.keyCode] != null) {
1186                 return false
1187         }
1188         char = e.charCode != null ? e.charCode : e.keyCode
1189         if (char && (this.cursor != null)) {
1190                 char = String.fromCharCode(char)
1191                 this.insert_character(this.cursor.n, this.cursor.i, char)
1192                 this.text_cleanup(this.cursor.n)
1193                 this.changed()
1194                 new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i + 1})
1195                 if (new_cursor) {
1196                         this.move_cursor(new_cursor)
1197                 } else {
1198                         console.log("ERROR: couldn't find cursor position after insert")
1199                         this.kill_cursor()
1200                 }
1201         }
1202         return false
1203 }
1204 PeachHTML5Editor.prototype.on_key_enter = function(e) { // enter key pressed
1205         var before, cur_block, i, n, new_cursor, new_node, new_text, parent_el, pc
1206         if (!this.cursor_visible) {
1207                 return
1208         }
1209         cur_block = this.cursor.n
1210         while (true) {
1211                 if (cur_block.type === 'tag') {
1212                         if (is_display_block(cur_block.el)) {
1213                                 break
1214                         }
1215                 }
1216                 if (cur_block.parent == null) {
1217                         return
1218                 }
1219                 cur_block = cur_block.parent
1220         }
1221         // find array to insert new element into
1222         if (cur_block.parent === this.tree_parent) {
1223                 parent_el = this.idoc.body
1224                 pc = this.tree
1225         } else {
1226                 parent_el = cur_block.parent.el
1227                 pc = cur_block.parent.children
1228         }
1229         for (i = 0; i < pc.length; ++i) {
1230                 n = pc[i]
1231                 if (n === cur_block) {
1232                         break
1233                 }
1234         }
1235         i += 1 // we want to be after it
1236         if (i < pc.length) {
1237                 before = pc[i].el
1238         } else {
1239                 before = null
1240         }
1241         // TODO if content after cursor
1242         // TODO new block is empty
1243         new_text = new peach_parser.Node('text', {text: ' '})
1244         new_node = new peach_parser.Node('tag', {
1245                 name: 'p',
1246                 parent: cur_block.parent,
1247                 attrs: {style: 'white-space: pre-wrap'},
1248                 children: [new_text]
1249         })
1250         new_text.parent = new_node
1251         new_text.el = domify(this.idoc, {text: ' '})
1252         new_node.el = domify(this.idoc, {p: {style: 'white-space: pre-wrap', children: [new_text.el]}})
1253         pc.splice(i, 0, new_node)
1254         parent_el.insertBefore(new_node.el, before)
1255         this.changed()
1256         new_cursor = new_cursor_position({
1257                 n: new_text,
1258                 i: 0
1259         })
1260         if (new_cursor == null) {
1261                 throw 'bork bork'
1262         }
1263         this.move_cursor(new_cursor)
1264         // TODO move content past cursor into this new block
1265         return false
1266 }
1267 // unlike the global function, this takes a Node, not an element
1268 PeachHTML5Editor.prototype.is_display_block = function(n) {
1269         // TODO stop calling global function, merge it into here, use iframe's window object
1270         if (n.type !== 'tag') {
1271                 return false
1272         }
1273         return is_display_block(n.el)
1274 }
1275 PeachHTML5Editor.prototype.find_block_parent = function(n) {
1276         while (true) {
1277                 n = n.parent
1278                 if (n == null) {
1279                         return null
1280                 }
1281                 if (this.is_display_block(n)) {
1282                         return n
1283                 }
1284                 if (n === this.tree_parent) {
1285                         return n
1286                 }
1287         }
1288         return null
1289 }
1290 // return a flat array of nodes (text, <br>, and later also inline-block)
1291 // that are flowing/wrapping together. n can be the containing block, or any
1292 // element inside it.
1293 PeachHTML5Editor.prototype.get_text_run = function(n) {
1294         var block, ret
1295         ret = []
1296         if (this.is_display_block(n)) {
1297                 block = n
1298         } else {
1299                 block = this.find_block_parent(n)
1300                 if (block == null) {
1301                         return ret
1302                 }
1303         }
1304         traverse_tree(block.children, (function(_this) { return function(n) {
1305                 var disp
1306                 if (n.type === 'text') {
1307                         ret.push(n)
1308                 } else if (n.type === 'tag') {
1309                         if (n.name === 'br') {
1310                                 ret.push(n)
1311                         } else {
1312                                 disp = _this.computed_style(n)
1313                                 if (disp === 'inline-block') {
1314                                         ret.push(n)
1315                                 }
1316                         }
1317                 }
1318                 return false // not done traversing
1319         }})(this))
1320         return ret
1321 }
1322 PeachHTML5Editor.prototype.node_is_decendant = function(young, old) {
1323         while (young != null && young !== this.tree_parent) {
1324                 if (young === old) {
1325                         return true
1326                 }
1327                 young = young.parent
1328         }
1329         return false
1330 }
1331 // helper for on_key_backspace
1332 PeachHTML5Editor.prototype._merge_left = function(state) {
1333         var pi, prev
1334         // the node prev to n was not prev to it a moment ago, merge with it if reasonable
1335         pi = state.n.parent.children.indexOf(state.n)
1336         if (pi > 0) {
1337                 prev = state.n.parent.children[pi - 1]
1338                 if (prev.type === 'text') {
1339                         state.i = prev.text.length
1340                         prev.text = prev.el.textContent = prev.text + state.n.text
1341                         this.remove_node(state.n)
1342                         state.n = prev
1343                         state.changed = true
1344                         state.moved_cursor = true
1345                 }
1346         }
1347         // else // TODO merge possible consecutive matching inline tags at @cursor
1348         return state
1349 }
1350 // helper for on_key_backspace
1351 // remove n from the dom, also remove its inline parents that are emptied by removing n
1352 PeachHTML5Editor.prototype._backspace_node_helper = function(n, run, run_i) {
1353         var block
1354         if (run == null) {
1355                 run = this.get_text_run(n)
1356         }
1357         if (run_i == null) {
1358                 run_i = run.indexOf(n)
1359         }
1360         block = this.find_block_parent(n)
1361         this.remove_node(n)
1362         n = n.parent
1363         while (n != null && n !== block) {
1364                 // bail if the previous node in this run is also inside the same parent
1365                 if (run_i > 0) {
1366                         if (this.node_is_decendant(run[run_i - 1], n)) {
1367                                 break
1368                         }
1369                 }
1370                 // bail if the next node in this run is also inside the same parent
1371                 if (run_i + 1 < run.length) {
1372                         if (this.node_is_decendant(run[run_i + 1], n)) {
1373                                 break
1374                         }
1375                 }
1376                 // move any sibling nodes to parent. These nodes are not in the text run
1377                 while (n.children.length > 0) {
1378                         this.move_node(n.children[0], n.parent, n)
1379                 }
1380                 // remove (now completely empty) inline parent
1381                 this.remove_node(n)
1382                 // proceed to outer parent
1383                 n = n.parent
1384         }
1385 }
1386 PeachHTML5Editor.prototype.on_key_backspace = function(e) {
1387         var block, changed, merge_state, n, ncb, need_text_cleanup, new_cursor, pcb, post, pre, prev, prev_cursor, run, run_i
1388         if (this.cursor == null) {
1389                 return
1390         }
1391         new_cursor = null
1392         run = null
1393         changed = true
1394         if (this.cursor.i === 0) { // cursor is at start of text node
1395                 if (run == null) {
1396                         run = this.get_text_run(this.cursor.n)
1397                 }
1398                 run_i = run.indexOf(this.cursor.n)
1399                 if (run_i === 0) { // if at start of text run
1400                         block = this.find_block_parent(this.cursor.n)
1401                         prev_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1402                         if (prev_cursor === null) { // if in first text run of document
1403                                 // do nothing (there's nothing text-like to the left of the cursor)
1404                                 return
1405                         }
1406                         // else merge with prev/outer text run
1407                         pcb = this.find_block_parent(prev_cursor.n)
1408                         while (block.children.length > 0) {
1409                                 this.move_node(block.children[0], pcb)
1410                         }
1411                         this.remove_node(block)
1412                         // merge possible consecutive text nodes at @cursor
1413                         merge_state = {n: this.cursor.n}
1414                         this._merge_left(merge_state)
1415                         this.text_cleanup(merge_state.n)
1416                         new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1417                 } else { // at start of text node, but not start of text run
1418                         prev = run[run_i - 1]
1419                         if (prev.type === 'text') { // if previous in text run is text
1420                                 if (prev.text.length === 1) { // if emptying prev (in text run)
1421                                         this._backspace_node_helper(prev, run, run_i)
1422                                         merge_state = {n: this.cursor.n, i: this.cursor.i}
1423                                         this._merge_left(merge_state)
1424                                         this.text_cleanup(merge_state.n)
1425                                         new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1426                                 } else { // prev in run is text with muliple chars
1427                                         // delete last character in prev
1428                                         prev.text = prev.text.substr(0, prev.text.length - 1)
1429                                         prev.el.textContent = prev.text
1430                                         this.text_cleanup(this.cursor.n)
1431                                         new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i})
1432                                 }
1433                         } else if (prev.name === 'br' || prev.name === 'hr') {
1434                                 this._backspace_node_helper(prev, run, run_i)
1435                                 merge_state = {n: this.cursor.n, i: this.cursor.i}
1436                                 this._merge_left(merge_state)
1437                                 this.text_cleanup(merge_state.n)
1438                                 new_cursor = new_cursor_position({n: merge_state.n, i: merge_state.i})
1439                         }
1440                         // FIXME implement this:
1441                         // else // if prev (in run) is inline-block
1442                                 // if that inline-block has text in it
1443                                         // delete last char in prev inlineblock
1444                                         // if that empties it
1445                                                 // delete it
1446                                                 // merge left
1447                                         // else
1448                                                 // move cursor inside
1449                                 // else
1450                                         // delete prev (inline) block
1451                                         // merge left
1452                                 // auto-delete this @cursor.parent(s) if this empties them
1453                 }
1454         } else { // cursor is not at start of text node
1455                 if (run == null) {
1456                         run = this.get_text_run(this.cursor.n)
1457                 }
1458                 if (this.cursor.n.text.length === 1) { // if emptying text node
1459                         if (run.length === 1) { // if emptying text run (of text/br/hr/inline-block)
1460                                 // remove inline-parents of @cursor.n
1461                                 block = this.find_block_parent(this.cursor.n)
1462                                 changed = false
1463                                 n = this.cursor.n.parent
1464                                 // note: this doesn't use _backspace_node_helper because:
1465                                 // 1. we don't want to delete the target node (we're replacing it's contents)
1466                                 // 2. we want to track whether anything was removed
1467                                 // 3. we know already know there's no other text from this run anywhere
1468                                 while (n && n !== block) {
1469                                         changed = true
1470                                         while (n.children.length > 0) {
1471                                                 this.move_node(n.children[0], n.parent, n)
1472                                         }
1473                                         this.remove_node(n)
1474                                         n = n.parent
1475                                 }
1476                                 // replace @cursor.n with a single (preserved) space
1477                                 if (this.cursor.n.text !== ' ') {
1478                                         changed = true
1479                                         this.cursor.n.text = this.cursor.n.el.textContent = ' '
1480                                 }
1481                                 if (changed) {
1482                                         this.text_cleanup(this.cursor.n)
1483                                 }
1484                                 // place the cursor to the left of that space
1485                                 new_cursor = new_cursor_position({n: this.cursor.n, i: 0})
1486                         } else { // emptying a text node (but not a whole text run)
1487                                 // figure out where cursor should land
1488                                 block = this.find_block_parent(this.cursor.n)
1489                                 new_cursor = find_prev_cursor_position(this.tree, {n: this.cursor.n, i: 0})
1490                                 ncb = this.find_block_parent(new_cursor.n)
1491                                 if (ncb !== block) {
1492                                         new_cursor = find_next_cursor_position(this.tree, {n: this.cursor.n, i: 1})
1493                                 }
1494                                 // delete text node and cleanup emptied parents
1495                                 run_i = run.indexOf(this.cursor.n)
1496                                 this._backspace_node_helper(this.cursor.n, run, run_i)
1497                                 // see if new adjacent siblings should merge
1498                                 // TODO make smarter
1499                                 if (run_i > 0 && run_i + 1 < run.length) {
1500                                         if (run[run_i - 1].type === 'text' && run[run_i + 1].type === 'text') {
1501                                                 merge_state = {n: run[run_i + 1]}
1502                                                 this._merge_left(merge_state)
1503                                                 if (merge_state.moved_cursor) {
1504                                                         new_cursor = merge_state
1505                                                 }
1506                                         }
1507                                 }
1508                                 // update whitespace preservation
1509                                 this.text_cleanup(block)
1510                                 // update cursor x/y in case things moved around
1511                                 if (new_cursor != null) {
1512                                         if (new_cursor.n.el.parentNode) { // still in dom after cleanup
1513                                                 new_cursor = new_cursor_position({n: new_cursor.n, i: new_cursor.i})
1514                                         } else {
1515                                                 new_cursor = null
1516                                         }
1517                                 }
1518                         }
1519                 } else { // there's a char left of cursor that we can delete without emptying anything
1520                         // delete character
1521                         need_text_cleanup = true
1522                         if (this.cursor.i > 1 && this.cursor.i < this.cursor.n.text.length) {
1523                                 pre = this.cursor.n.text.substr(this.cursor.i - 2, 3)
1524                                 post = pre.charAt(0) + pre.charAt(2)
1525                                 if (str_has_ws_run(pre) === str_has_ws_run(post)) {
1526                                         need_text_cleanup = false
1527                                 }
1528                         }
1529                         this.remove_character(this.cursor.n, this.cursor.i - 1)
1530                         // call text_cleanup if whe created/removed a whitespace run
1531                         if (need_text_cleanup) {
1532                                 this.text_cleanup(this.cursor.n)
1533                         }
1534                         new_cursor = new_cursor_position({n: this.cursor.n, i: this.cursor.i - 1})
1535                 }
1536         }
1537         // mark document changed and move the cursor
1538         if (changed != null) {
1539                 this.changed()
1540         }
1541         if (new_cursor != null) {
1542                 this.move_cursor(new_cursor)
1543         } else {
1544                 this.kill_cursor()
1545         }
1546 }
1547 PeachHTML5Editor.prototype.on_page_up_key = function(e) {
1548         var new_cursor, screen_y, scroll_amount
1549         if (this.wrap2.scrollTop === 0) {
1550                 if (this.cursor == null) {
1551                         return
1552                 }
1553                 new_cursor = first_cursor_position(this.tree)
1554                 if (new_cursor != null) {
1555                         if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1556                                 this.move_cursor(new_cursor)
1557                         }
1558                 }
1559                 return
1560         }
1561         if (this.cursor != null) {
1562                 screen_y = this.cursor.y - this.wrap2.scrollTop
1563         }
1564         scroll_amount = this.wrap2_height - breathing_room
1565         this.wrap2.scrollTop = Math.max(0, this.wrap2.scrollTop - scroll_amount)
1566         if (this.cursor != null) {
1567                 return this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1568         }
1569 }
1570 PeachHTML5Editor.prototype.on_page_down_key = function(e) {
1571         var lowest_scrollpos, new_cursor, screen_y, scroll_amount
1572         lowest_scrollpos = this.wrap2.scrollHeight - this.wrap2_height
1573         if (this.wrap2.scrollTop === lowest_scrollpos) {
1574                 if (this.cursor == null) {
1575                         return
1576                 }
1577                 new_cursor = last_cursor_position(this.tree)
1578                 if (new_cursor != null) {
1579                         if (new_cursor.n !== this.cursor.n || new_cursor.i !== this.cursor.i) {
1580                                 this.move_cursor(new_cursor)
1581                         }
1582                 }
1583                 return
1584         }
1585         if (this.cursor != null) {
1586                 screen_y = this.cursor.y - this.wrap2.scrollTop
1587         }
1588         scroll_amount = this.wrap2_height - breathing_room
1589         this.wrap2.scrollTop = Math.min(lowest_scrollpos, this.wrap2.scrollTop + scroll_amount)
1590         if (this.cursor != null) {
1591                 this.move_cursor_into_view(screen_y + this.wrap2.scrollTop)
1592         }
1593 }
1594 PeachHTML5Editor.prototype.move_cursor_into_view = function(y_target) {
1595         var cur, far_enough, finder, new_cursor, saved_ideal_x, was, y_max, y_min
1596         if (y_target === this.cursor.y) {
1597                 return
1598         }
1599         was = this.cursor
1600         y_min = this.wrap2.scrollTop
1601         if (this.wrap2.scrollTop !== 0) {
1602                 y_min += breathing_room
1603         }
1604         y_max = this.wrap2.scrollTop + this.wrap2_height
1605         if (this.wrap2.scrollTop !== this.wrap2.scrollHeight - this.wrap2_height) { // downmost
1606                 y_max -= breathing_room
1607         }
1608         y_target = Math.min(y_target, y_max)
1609         y_target = Math.max(y_target, y_min)
1610         if (y_target < this.cursor.y) {
1611                 finder = find_up_cursor_position
1612                 far_enough = function(cur, target_y) {
1613                         return cur.y + cur.h <= target_y
1614                 }
1615         } else {
1616                 finder = find_down_cursor_position
1617                 far_enough = function(cur, y_target) {
1618                         return cur.y >= y_target
1619                 }
1620         }
1621         while (true) {
1622                 cur = finder(this.tree, was, this.cursor_ideal_x)
1623                 if (cur == null) {
1624                         break
1625                 }
1626                 if (far_enough(cur, y_target)) {
1627                         break
1628                 }
1629                 was = cur
1630         }
1631         if (was === this.cursor) {
1632                 was = null
1633         }
1634         if (was != null) {
1635                 if (was.y + was.h > y_max) {
1636                         was = null
1637                 } else if (was.y < y_min) {
1638                         was = null
1639                 }
1640         }
1641         if (cur != null) {
1642                 if (cur.y + cur.h > y_max) {
1643                         cur = null
1644                 } else if (cur.y < y_min) {
1645                         cur = null
1646                 }
1647         }
1648         if ((cur != null) && (was != null)) {
1649                 // both valid, pick best
1650                 if (cur.y < y_min) {
1651                         new_cursor = was
1652                 } else if (was.y + was.h > y_max) {
1653                         new_cursor = cur
1654                 } else if (cur.y - y_target < y_target - was.y) {
1655                         new_cursor = cur
1656                 } else {
1657                         new_cursor = was
1658                 }
1659         } else {
1660                 new_cursor = was != null ? was : cur
1661         }
1662         if (new_cursor != null) {
1663                 saved_ideal_x = this.cursor_ideal_x
1664                 this.move_cursor(new_cursor)
1665                 this.cursor_ideal_x = saved_ideal_x
1666         }
1667 }
1668 // remove all the editable content (and cursor, overlays, etc)
1669 PeachHTML5Editor.prototype.clear_dom = function() {
1670         while (this.idoc.body.childNodes.length) {
1671                 this.idoc.body.removeChild(this.idoc.body.childNodes[0])
1672         }
1673         this.kill_cursor()
1674 }
1675 PeachHTML5Editor.prototype.load_html = function(html) {
1676         this.tree = peach_parser.parse(html, this.parser_opts)
1677         if (this.tree[0] == null ? true : this.tree[0].parent == null) {
1678                 this.tree = peach_parser.parse('<p style="white-space: pre-wrap"> </p>', this.parser_opts)
1679         }
1680         this.tree_parent = this.tree[0].parent
1681         this.tree_parent.el = this.idoc.body
1682         this.clear_dom()
1683         instantiate_tree(this.tree, this.tree_parent.el)
1684         this.collapse_whitespace(this.tree)
1685         return this.changed()
1686 }
1687 PeachHTML5Editor.prototype.changed = function() {
1688         this.in_el.onchange = null
1689         if (this.pretty_print) {
1690                 this.in_el.value = this.pretty_html(this.tree)
1691         } else {
1692                 this.in_el.value = nodes_to_html(this.tree)
1693         }
1694         this.in_el.onchange = (function(_this) { return function() {
1695                 return _this.load_html(_this.in_el.value)
1696         }})(this)
1697         return this.adjust_iframe_height()
1698 }
1699 PeachHTML5Editor.prototype.adjust_iframe_height = function() {
1700         var h, s
1701         s = this.wrap2.scrollTop
1702         // when the content gets shorter, the idoc's body tag will continue to
1703         // report the old (too big) height in Chrome. The workaround is to
1704         // shrink the iframe before the content height:
1705         this.iframe.style.height = "10px"
1706         h = parseInt(this.idoc.body.scrollHeight, 10)
1707         this.iframe.style.height = h + "px"
1708         return this.wrap2.scrollTop = s
1709 }
1710 // true if n is text node with only one caracter, and the only child of a tag
1711 PeachHTML5Editor.prototype.is_only_char_in_tag = function(n, i) {
1712         if (n.type !== 'text') {
1713                 return false
1714         }
1715         if (n.text.length !== 1) {
1716                 return false
1717         }
1718         if (n.parent === this.tree_parent) {
1719                 return false
1720         }
1721         if (n.parent.children.length !== 1) {
1722                 return false
1723         }
1724         return true
1725 }
1726 // true if n is text node with just a space in it, and the only child of a tag
1727 PeachHTML5Editor.prototype.is_lone_space = function(n, i) {
1728         if (n.type !== 'text') {
1729                 return false
1730         }
1731         if (n.text !== ' ') {
1732                 return false
1733         }
1734         if (n.parent === this.tree_parent) {
1735                 return false
1736         }
1737         if (n.parent.children.length !== 1) {
1738                 return false
1739         }
1740         return true
1741 }
1742 // detect special case: typing before a space that's the only thing in a block/doc
1743 // reason: enter key creates blocks with just a space in them
1744 PeachHTML5Editor.prototype.insert_should_replace = function(n, i) {
1745         if (i !== 0) {
1746                 return false
1747         }
1748         if (n.text !== ' ') {
1749                 return false
1750         }
1751         if (n.parent === this.tree_parent) {
1752                 return true
1753         }
1754         if (n.parent.children.length === 1) {
1755                 if (n.parent.children[0] === n) {
1756                         // n is only child
1757                         return true
1758                 }
1759         }
1760         return false
1761 }
1762 // WARNING:  after calling this, you MUST call changed() and text_cleanup()
1763 PeachHTML5Editor.prototype.insert_character = function(n, i, char) {
1764         if (n.parent === this.tree_parent) {
1765                 // FIXME implement text nodes at top level
1766                 return
1767         }
1768         // insert the character
1769         if (this.insert_should_replace(n, i)) {
1770                 n.text = char
1771         } else if (i === 0) {
1772                 n.text = char + n.text
1773         } else if (i === n.text.length) {
1774                 n.text += char
1775         } else {
1776                 n.text = n.text.substr(0, i) + char + n.text.substr(i)
1777         }
1778         return n.el.nodeValue = n.text
1779 }
1780 // WARNING: after calling this, you MUST call changed() and text_cleanup()
1781 PeachHTML5Editor.prototype.remove_character = function(n, i) {
1782         n.text = n.text.substr(0, i) + n.text.substr(i + 1)
1783         return n.el.nodeValue = n.text
1784 }
1785 PeachHTML5Editor.prototype.computed_style = function(n, prop) {
1786         var style
1787         if (n.type === 'text') {
1788                 n = n.parent
1789         }
1790         style = this.iframe.contentWindow.getComputedStyle(n.el, null)
1791         return style.getPropertyValue(prop)
1792 }
1793 // returns the new white-space value that will preserve spaces for node n
1794 PeachHTML5Editor.prototype.preserve_space = function(n, ideal_target) {
1795         var target, ws, ref
1796         if (n.type === 'text') {
1797                 target = n.parent
1798         } else {
1799                 target = n
1800         }
1801         while (target !== ideal_target && !target.el.style.whiteSpace) {
1802                 if (target == null) {
1803                         console.log("bug #967123")
1804                         return
1805                 }
1806                 target = target.parent
1807         }
1808         ws = (ref = ws_props[target.el.style.whiteSpace]) != null ? ref.to_preserve : null
1809         if (ws == null) {
1810                 ws = 'pre-wrap'
1811         }
1812         target.el.style.whiteSpace = ws
1813         this.update_style_from_el(target)
1814         return ws
1815 }
1816 PeachHTML5Editor.prototype.update_style_from_el = function(n) {
1817         var style
1818         style = n.el.getAttribute('style')
1819         if (style != null && style != '') {
1820                 return n.attrs.style = style
1821         } else {
1822                 if (n.attrs.style != null) {
1823                         return delete n.attrs.style
1824                 }
1825         }
1826 }
1827 // remove whitespace that would be trimmed
1828 // replace whitespace that would collapse with a single space
1829 // FIXME remove whitespace from after <br> (but not before)
1830 // FIXME rewrite to
1831 //     check computed white-space prop on txt parents
1832 //     batch replace txt node contents (ie don't loop for each char)
1833 PeachHTML5Editor.prototype.collapse_whitespace = function(tree) {
1834         var cur, cur_i, cur_px, first, iterate, next, next_i, next_pos, next_px, operate, pos, prev, prev_i, prev_pos, prev_px, queue, remove, removed_char, replace_with_space
1835         if (tree == null) {
1836                 tree = this.tree
1837         }
1838         prev = cur = next = null
1839         prev_i = cur_i = next_i = 0
1840         prev_pos = pos = next_pos = null
1841         prev_px = cur_px = next_px = null
1842         first = true
1843         removed_char = null
1844
1845         tree_remove_empty_text_nodes(tree)
1846
1847         iterate = function(tree, cb) {
1848                 var advance, block, i, j, n
1849                 for (j = 0; j < tree.length; j++) {
1850                         n = tree[j]
1851                         if (n.type === 'text') {
1852                                 i = 0
1853                                 while (i < n.text.length) { // don't foreach, cb might remove chars
1854                                         advance = cb(n, i)
1855                                         if (advance) {
1856                                                 i += 1
1857                                         }
1858                                 }
1859                         }
1860                         if (n.type === 'tag') {
1861                                 block = is_display_block(n.el)
1862                                 if (block) {
1863                                         cb(null)
1864                                 }
1865                                 if (n.children.length > 0 && plaintext_elements[n.name] == null) {
1866                                         iterate(n.children, cb)
1867                                 }
1868                                 if (block) {
1869                                         cb(null)
1870                                 }
1871                         }
1872                 }
1873         }
1874         // remove cur char
1875         remove = function(undo) {
1876                 if (undo) {
1877                         cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i))
1878                         if (next === cur) { // in same text node
1879                                 next_i += 1
1880                         }
1881                         return -1
1882                 } else {
1883                         removed_char = cur.text.charAt(cur_i)
1884                         cur.el.textContent = cur.text = (cur.text.substr(0, cur_i)) + (cur.text.substr(cur_i + 1))
1885                         if (next === cur) { // in same text node
1886                                 if (next_i === 0) {
1887                                         throw "how is this possible?"
1888                                 }
1889                                 next_i -= 1
1890                         }
1891                         return 1
1892                 }
1893         }
1894         replace_with_space = function(undo) {
1895                 if (undo) {
1896                         cur.text = (cur.text.substr(0, cur_i)) + removed_char + (cur.text.substr(cur_i + 1))
1897                         cur.el.textContent = cur.text
1898                 } else {
1899                         removed_char = cur.text.charAt(cur_i)
1900                         if (removed_char !== ' ') {
1901                                 cur.text = (cur.text.substr(0, cur_i)) + ' ' + (cur.text.substr(cur_i + 1))
1902                                 cur.el.textContent = cur.text
1903                         }
1904                 }
1905                 return 0
1906         }
1907         // return true if cur was removed from the dom (ie re-use same prev)
1908         operate = function() {
1909                 // cur definitately set
1910                 // prev and/or next might be null, indicating the start/end of a display:block
1911                 var bounds, dbg, fixer, fixers, i, need_undo, new_next_px, new_prev_px, removed, undo_arg
1912                 if (!is_space_code(cur.text.charCodeAt(cur_i))) {
1913                         return false
1914                 }
1915                 fixers = [remove, replace_with_space]
1916                 // check for common case: single whitespace surrounded by non-whitespace chars
1917                 if ((prev != null) && (next != null)) {
1918                         if (!((is_space_code(prev.text.charCodeAt(prev_i))) || (is_space_code(next.text.charCodeAt(next_i))))) {
1919                                 dbg = cur.text.charCodeAt(cur_i)
1920                                 if (cur.text.charAt(cur_i) === ' ') {
1921                                         return false
1922                                 } else {
1923                                         fixers = [replace_with_space]
1924                                 }
1925                         }
1926                 }
1927                 bounds = text_range_bounds(cur.el, cur_i, cur_i + 1)
1928                 // consistent cases:
1929                 // 1. zero rects returned by getClientRects() means collapsed space
1930                 if (bounds === null) {
1931                         return remove()
1932                 }
1933                 // 2. width greater than zero means visible space
1934                 if (bounds.w > 0) {
1935                         // has bounds, don't try removing
1936                         fixers = [replace_with_space]
1937                 }
1938                 // now the weird edge cases...
1939                 //
1940                 // firefox and chromium both report zero width for characters at the end
1941                 // of a line where the text wraps (automatically, due to word-wrap) to
1942                 // the next line. These do not appear to be distinguishable from
1943                 // collapsed spaces via the range/bounds api, so...
1944                 //
1945                 // remove it from the dom, and if prev or next moves, put it back.
1946                 //
1947                 // this block (try changing it, put it back if something moves) is also
1948                 // used on collapsable whitespace characters besides space. In this case
1949                 // the character is replaced with a normal space character instead of
1950                 // removed
1951                 if ((prev != null) && (prev_px == null)) {
1952                         prev_px = new_cursor_position({n: prev, i: prev_i})
1953                 }
1954                 if ((next != null) && (next_px == null)) {
1955                         next_px = new_cursor_position({n: next, i: next_i})
1956                 }
1957                 //if prev is null and next is null
1958                 //      parent_px = cur.parent.el.getBoundingClientRect()
1959                 undo_arg = true // just for readabality
1960                 removed = 0
1961                 for (i = 0; i < fixers.length; i++) {
1962                         fixer = fixers[i]
1963                         if (removed > 0) {
1964                                 break
1965                         }
1966                         removed += fixer()
1967                         need_undo = false
1968                         if (prev != null) {
1969                                 if (prev_px != null) {
1970                                         new_prev_px = new_cursor_position({n: prev, i: prev_i})
1971                                         if (new_prev_px != null) {
1972                                                 if (new_prev_px.x !== prev_px.x || new_prev_px.y !== prev_px.y) {
1973                                                         need_undo = true
1974                                                 }
1975                                         } else {
1976                                                 need_undo = true
1977                                         }
1978                                 } else {
1979                                         console.log("this shouldn't happen, we remove spaces that don't locate")
1980                                 }
1981                         }
1982                         if ((next != null) && !need_undo) {
1983                                 if (next_px != null) {
1984                                         new_next_px = new_cursor_position({n: next, i: next_i})
1985                                         if (new_next_px != null) {
1986                                                 if (new_next_px.x !== next_px.x || new_next_px.y !== next_px.y) {
1987                                                         need_undo = true
1988                                                 }
1989                                         } else {
1990                                                 need_undo = true
1991                                         }
1992                                 }
1993                                 //else
1994                                 //      console.log "removing space becase space after it is collapsed"
1995                         }
1996                         if (need_undo) {
1997                                 removed += fixer(undo_arg)
1998                         }
1999                 }
2000                 if (removed > 0) {
2001                         return true
2002                 } else {
2003                         return false
2004                 }
2005         }
2006         // pass null at start/end of display:block
2007         queue = function(n, i) {
2008                 var advance, removed
2009                 next = n
2010                 next_i = i
2011                 next_px = null
2012                 advance = true
2013                 if (cur != null) {
2014                         removed = operate()
2015                         // don't advance (to the next character next time) if we removed a
2016                         // character from the same text node as ``next``, because doing so
2017                         // renumbers the indexes in that string
2018                         if (removed && cur === next) {
2019                                 advance = false
2020                         }
2021                 } else {
2022                         removed = false
2023                 }
2024                 if (!removed) {
2025                         prev = cur
2026                         prev_i = cur_i
2027                         prev_px = cur_px
2028                 }
2029                 cur = next
2030                 cur_i = next_i
2031                 cur_px = next_px
2032                 return advance
2033         }
2034         queue(null)
2035         iterate(tree, queue)
2036         queue(null)
2037
2038         tree_remove_empty_text_nodes(tree)
2039 }
2040 // call this after you insert or remove inline nodes. It will:
2041 //    merge consecutive text nodes
2042 //    remove empty text nodes
2043 //    adjust white-space property
2044 // note: this assumes that all whitespace in text nodes should be displayed
2045 // (ie not collapse or be trimmed) and will change the white-space property
2046 // as needed to achieve this.
2047 PeachHTML5Editor.prototype.text_cleanup = function(n) {
2048         var block, eats_start_sp, i, last, n_i, need_preserve, prev, prev_i, run, ws
2049         if (this.is_display_block(n)) {
2050                 block = n
2051         } else {
2052                 block = this.find_block_parent(n)
2053                 if (block == null) {
2054                         return
2055                 }
2056         }
2057         run = this.get_text_run(block)
2058         if (run == null) {
2059                 return
2060         }
2061         // merge consecutive text elements
2062         if (run.length > 1) {
2063                 i = 1
2064                 prev = run[0]
2065                 while (i < run.length) {
2066                         n = run[i]
2067                         if (prev.type === 'text' && n.type === 'text') {
2068                                 if (prev.parent === n.parent) {
2069                                         prev_i = n.parent.children.indexOf(prev)
2070                                         n_i = n.parent.children.indexOf(n)
2071                                         if (n_i === prev_i + 1) {
2072                                                 prev.text = prev.text + n.text
2073                                                 prev.el.textContent = prev.text
2074                                                 this.remove_node(n)
2075                                                 run.splice(i, 1)
2076                                                 continue // don't increment i or change prev
2077                                         }
2078                                 }
2079                         }
2080                         i += 1
2081                         prev = n
2082                 }
2083         }
2084         // remove empty text nodes
2085         i = 0
2086         while (i < run.length) {
2087                 n = run[i]
2088                 if (n.type === 'text') {
2089                         if (n.text === '') {
2090                                 this.remove_node(n)
2091                                 // FIXME maybe remove parents recursively if this makes them empty
2092                                 run.splice(i, 1)
2093                                 continue // don't increment i
2094                         }
2095                 }
2096                 i += 1
2097         }
2098         // note: inline tags can have white-space:pre-line/etc
2099         // note: inline-blocks have their whitespace collapsed independantly of outer run
2100         // note: inline-blocks are treated like non-whitespace char even if empty
2101         if (block.el.style.whiteSpace != null) {
2102                 ws = block.el.style.whiteSpace
2103                 if (ws_props[ws]) {
2104                         if (ws_props[ws].space) {
2105                                 if (ws_props[ws].to_collapse === 'normal') {
2106                                         block.el.style.whiteSpace = null
2107                                 } else {
2108                                         block.el.style.whiteSpace = ws_props[ws].to_collapse
2109                                 }
2110                                 this.update_style_from_el(block)
2111                         }
2112                 }
2113         }
2114         // note: space after <br> colapses, but not space before
2115         // check for spaces that would collapse without help
2116         eats_start_sp = true // if the next node starts with space it collapses (unless pre)
2117         prev = null
2118         for (i = 0; i < run.length; ++i) {
2119                 n = run[i]
2120                 if (n.type === 'tag') {
2121                         if (n.name === 'br') {
2122                                 eats_start_sp = true
2123                         } else {
2124                                 eats_start_sp = false
2125                         }
2126                 } else {
2127                         need_preserve = false
2128                         if (n.type !== 'text') {
2129                                 console.log("bug #232308")
2130                                 return
2131                         }
2132                         if (eats_start_sp) {
2133                                 if (is_space_code(n.text.charCodeAt(0))) {
2134                                         need_preserve = true
2135                                 }
2136                         }
2137                         if (!need_preserve) {
2138                                 need_preserve = multi_sp_regex.test(n.text)
2139                         }
2140                         if (need_preserve) {
2141                                 // do we have it already?
2142                                 ws = this.computed_style(n, 'white-space')
2143                                 if (ws_props[ws] != null ? !ws_props[ws].space : true) {
2144                                         // 2nd arg is ideal target for css rule
2145                                         ws = this.preserve_space(n, block)
2146                                 }
2147                                 eats_start_sp = false
2148                         } else {
2149                                 if (is_space_code(n.text.charCodeAt(n.text.length - 1))) {
2150                                         ws = this.computed_style(n, 'white-space')
2151                                         if ((ref1 = ws_props[ws]) != null ? ref1.space : void 0) {
2152                                                 eats_start_sp = false
2153                                         } else {
2154                                                 eats_start_sp = true
2155                                         }
2156                                 } else {
2157                                         eats_start_sp = false
2158                                 }
2159                         }
2160                 }
2161         }
2162         // check if text ends with a collapsable space
2163         if (run.length > 0) {
2164                 last = run[run.length - 1]
2165                 if (last.type === 'text') {
2166                         if (eats_start_sp) {
2167                                 this.preserve_space(last, block)
2168                         }
2169                 }
2170         }
2171 }
2172 PeachHTML5Editor.prototype.css_clear = function(n, prop) {
2173         var css_delimiter_regex, i, styles
2174         if (n.attrs.style == null) {
2175                 return
2176         }
2177         if (n.attrs.style === '') {
2178                 return
2179         }
2180         css_delimiter_regex = new RegExp('\s*;\s*', 'g') // FIXME make this global
2181         styles = n.attrs.style.trim().split(css_delimiter)
2182         if (!(styles.length > 0)) {
2183                 return
2184         }
2185         if (styles[styles.length - 1] === '') {
2186                 styles.pop()
2187                 if (!(styles.length > 0)) {
2188                         return
2189                 }
2190         }
2191         i = 0
2192         while (i < styles.length) {
2193                 if (styles[i].substr(0, 12) === 'white-space:') {
2194                         styles.splice(i, 1)
2195                 } else {
2196                         i += 1
2197                 }
2198         }
2199 }
2200 // WARNING: after calling this one or more times, you MUST:
2201 //    if it's inline: call @text_cleanup
2202 //    call @changed()
2203 PeachHTML5Editor.prototype.remove_node = function(n) {
2204         var i
2205         i = n.parent.children.indexOf(n)
2206         if (i === -1) {
2207                 throw "BUG #9187112313"
2208         }
2209         n.el.parentNode.removeChild(n.el)
2210         n.parent.children.splice(i, 1)
2211 }
2212 // remove a node from the tree/dom, insert into new_parent before insert_before?end
2213 // WARNING: after calling this one or more times, you MUST:
2214 //    if it's inline: call @text_cleanup
2215 //    call @changed()
2216 PeachHTML5Editor.prototype.move_node = function(n, new_parent, insert_before) {
2217         var before_i, i
2218         if (insert_before == null) {
2219                 insert_before = null
2220         }
2221         i = n.parent.children.indexOf(n)
2222         if (i === -1) {
2223                 throw "Error: tried to remove node, but it's not in it's parents list of children"
2224                 return
2225         }
2226         if (insert_before != null) {
2227                 before_i = new_parent.children.indexOf(insert_before)
2228                 if (i === -1) {
2229                         throw "Error: tried to move a node to be before a non-existent node"
2230                 }
2231                 insert_before = insert_before.el
2232         }
2233         this.remove_node(n)
2234         if (insert_before != null) {
2235                 new_parent.el.insertBefore(n.el, insert_before)
2236                 new_parent.children.splice(before_i, 0, n)
2237         } else {
2238                 new_parent.el.appendChild(n.el, insert_before)
2239                 new_parent.children.push(n)
2240         }
2241         n.parent = new_parent
2242 }
2243 // remove it, forget where it was
2244 PeachHTML5Editor.prototype.kill_cursor = function() {
2245         if (this.cursor_visible) {
2246                 this.cursor_el.parentNode.removeChild(this.cursor_el)
2247                 this.cursor_visible = false
2248         }
2249         this.cursor = null
2250         this.annotate(null)
2251 }
2252 PeachHTML5Editor.prototype.move_cursor = function(cursor) {
2253         var height
2254         this.cursor_ideal_x = cursor.x
2255         this.cursor = cursor
2256         if (!this.cursor_visible) {
2257                 this.cursor_el = domify(this.outer_idoc, {div: { id: 'cursor'}})
2258                 this.overlay.appendChild(this.cursor_el)
2259                 this.cursor_visible = true
2260         }
2261         this.cursor_el.style.left = (cursor.x + overlay_padding - 1) + "px"
2262         if (cursor.h < 5) {
2263                 height = 12
2264         } else {
2265                 height = cursor.h
2266         }
2267         this.cursor_el.style.top = (cursor.y + overlay_padding + Math.round(height * .07)) + "px"
2268         this.cursor_el.style.height = (Math.round(height * 0.82)) + "px"
2269         this.annotate(cursor.n)
2270         this.scroll_into_view(cursor.y, height)
2271 }
2272 PeachHTML5Editor.prototype.scroll_into_view = function(y, h) {
2273         var downmost, upmost
2274         if (h == null) {
2275                 h = 0
2276         }
2277         y += overlay_padding // convert units from @idoc to @wrap2
2278         // very top of document
2279         if (y <= breathing_room) {
2280                 this.wrap2.scrollTop = 0
2281                 return
2282         }
2283         // very bottom of document
2284         if (y + h >= this.wrap2.scrollHeight - breathing_room) {
2285                 this.wrap2.scrollTop = this.wrap2.scrollHeight - this.wrap2_height
2286                 return
2287         }
2288         // The most scrolled up (lowest value for scrollTop) that would be OK
2289         upmost = y + h + breathing_room - this.wrap2_height
2290         upmost = Math.max(upmost, 0)
2291         // the most scrolled down (highest value for scrollTop) that would be OK
2292         downmost = y - breathing_room
2293         downmost = Math.min(downmost, this.wrap2.scrollHeight - this.wrap2_height)
2294         if (upmost > downmost) { // means h is too big to fit
2295                 // scroll so top is visible
2296                 this.wrap2.scrollTop = downmost
2297                 return
2298         }
2299         if (this.wrap2.scrollTop < upmost) {
2300                 this.wrap2.scrollTop = upmost
2301                 return
2302         }
2303         if (this.wrap2.scrollTop > downmost) {
2304                 this.wrap2.scrollTop = downmost
2305                 return
2306         }
2307 }
2308 PeachHTML5Editor.prototype.annotate = function(n) {
2309         var alpha, ann_box, ann_tag, bounds, prev_bounds
2310         while (this.matting.length > 0) {
2311                 this.overlay.removeChild(this.matting[0])
2312                 this.matting.shift()
2313         }
2314         if (n == null) {
2315                 return
2316         }
2317         prev_bounds = {x: 0, y: 0, w: 0, h: 0}
2318         alpha = 0.1
2319         while (((n != null ? n.el : void 0) != null) && n !== this.tree_parent) {
2320                 if (n.type === 'text') {
2321                         n = n.parent
2322                         continue
2323                 }
2324                 bounds = get_el_bounds(n.el)
2325                 if (bounds == null) {
2326                         return
2327                 }
2328                 if (bounds.x === prev_bounds.x && bounds.y === prev_bounds.y && bounds.w === prev_bounds.w && bounds.h === prev_bounds.h) {
2329                         n = n.parent
2330                         continue
2331                 }
2332                 ann_box = domify(this.outer_idoc, {div: {"class": 'ann_box', style: "left: " + (bounds.x - 1 + overlay_padding) + "px; top: " + (bounds.y - 2 + overlay_padding) + "px; width: " + bounds.w + "px; height: " + bounds.h + "px"}}) // outline: 1000px solid rgba(0,153,255,#{alpha});
2333                 this.overlay.appendChild(ann_box)
2334                 this.matting.push(ann_box)
2335                 ann_tag = domify(this.outer_idoc, {div: {"class": 'ann_tag', style: "left: " + (bounds.x + 1 + overlay_padding) + "px; top: " + (bounds.y - 7 + overlay_padding) + "px",children: [domify(this.outer_idoc, {text: " " + n.name + " "})]}})
2336                 this.overlay.appendChild(ann_tag)
2337                 this.matting.push(ann_tag)
2338                 n = n.parent
2339                 alpha *= 1.5
2340         }
2341 }
2342 PeachHTML5Editor.prototype.pretty_html = function(tree, indent, parent_flags) {
2343         var attr_keys, cs, display, float, i, j, in_flow, in_flow_block, inner_flags, is_block, is_br, is_text, k, n, next_indent, position, prev_in_flow_is_block, prev_in_flow_is_text, ret, visibility, want_nl, whitespace
2344         if (indent == null) {
2345                 indent = ''
2346         }
2347         if (parent_flags == null) {
2348                 parent_flags = {
2349                         pre_ish: false,
2350                         block: true,
2351                         want_nl: false
2352                 }
2353         }
2354         ret = ''
2355         want_nl = parent_flags.want_nl
2356         prev_in_flow_is_text = false
2357         prev_in_flow_is_block = false
2358         for (i = 0; i < tree.length; ++i) {
2359                 n = tree[i]
2360                 inner_flags = {
2361                         want_nl: true
2362                 }
2363                 is_br = false
2364                 switch (n.type) {
2365                         case 'tag':
2366                                 if (n.name === 'br') {
2367                                         is_br = true
2368                                 }
2369                                 is_text = false
2370                                 cs = this.iframe.contentWindow.getComputedStyle(n.el, null)
2371                                 whitespace = cs.getPropertyValue('white-space')
2372                                 display = cs.getPropertyValue('display')
2373                                 position = cs.getPropertyValue('position')
2374                                 float = cs.getPropertyValue('float')
2375                                 visibility = cs.getPropertyValue('visibility')
2376                                 if (n.name === 'textarea') {
2377                                         inner_flags.pre_ish = true
2378                                 } else {
2379                                         inner_flags.pre_ish = whitespace.substr(0, 3) === 'pre'
2380                                 }
2381                                 switch (float) {
2382                                         case 'left':
2383                                         case 'right':
2384                                                 in_flow = false
2385                                         break
2386                                         default:
2387                                                 switch (position) {
2388                                                         case 'absolute':
2389                                                         case 'fixed':
2390                                                                 in_flow = false
2391                                                         break
2392                                                         default:
2393                                                                 if ('display' === 'none') {
2394                                                                         in_flow = false
2395                                                                 } else {
2396                                                                         switch (visibility) {
2397                                                                                 case 'hidden':
2398                                                                                 case 'collapse':
2399                                                                                         in_flow = false
2400                                                                                 break
2401                                                                                 default:
2402                                                                                         in_flow = true
2403                                                                         }
2404                                                                 }
2405                                                 }
2406                                 }
2407                                 switch (display) {
2408                                         case 'inline':
2409                                         case 'none':
2410                                                 inner_flags.block = false
2411                                                 is_block = in_flow_block = false
2412                                         break
2413                                         case 'inline-black':
2414                                                 inner_flags.block = true
2415                                                 is_block = in_flow_block = false
2416                                         break
2417                                         default:
2418                                                 inner_flags.block = true
2419                                                 is_block = true
2420                                                 in_flow_block = in_flow
2421                                 }
2422                         break
2423                         case 'text':
2424                                 is_text = true
2425                                 is_block = false
2426                                 in_flow = true
2427                                 in_flow_block = false
2428                                 break
2429                         default: // 'comment', 'doctype'
2430                                 is_text = false
2431                                 is_block = false
2432                                 in_flow = false
2433                                 in_flow_block = false
2434                 }
2435                 // print whitespace if we can
2436                 if (!parent_flags.pre_ish) {
2437                         if (!(prev_in_flow_is_text && is_br)) {
2438                                 if ((i === 0 && parent_flags.block) || in_flow_block || prev_in_flow_is_block) {
2439                                         if (want_nl) {
2440                                                 ret += "\n"
2441                                         }
2442                                         ret += indent
2443                                 }
2444                         }
2445                 }
2446                 switch (n.type) {
2447                         case 'tag':
2448                                 ret += '<' + n.name
2449                                 attr_keys = []
2450                                 for (k in n.attrs) {
2451                                         attr_keys.unshift(k)
2452                                 }
2453                                 //attr_keys.sort()
2454                                 for (j = 0; j < attr_keys.length; ++j) {
2455                                         k = attr_keys[j]
2456                                         ret += " " + k
2457                                         if (n.attrs[k].length > 0) {
2458                                                 ret += "=\"" + (enc_attr(n.attrs[k])) + "\""
2459                                         }
2460                                 }
2461                                 ret += '>'
2462                                 if (void_elements[n.name] == null) {
2463                                         if (inner_flags.block) {
2464                                                 next_indent = indent + '    '
2465                                         } else {
2466                                                 next_indent = indent
2467                                         }
2468                                         if (n.children.length) {
2469                                                 ret += this.pretty_html(n.children, next_indent, inner_flags)
2470                                         }
2471                                         ret += "</" + n.name + ">"
2472                                 }
2473                                 break
2474                         case 'text':
2475                                 if (n.parent != null ? plaintext_elements[n.parent.name] : false) {
2476                                         ret += n.text
2477                                 } else if (n.parent != null ? newline_eating_elements[n.parent.name] && n.text.charAt(0) === "\n" : false) {
2478                                         ret += enc_text("\n" + n.text)
2479                                 } else {
2480                                         ret += enc_text(n.text)
2481                                 }
2482                                 break
2483                         case 'comment':
2484                                 ret += "<!--" + n.text + "-->" // TODO encode?
2485                                 break
2486                         case 'doctype':
2487                                 ret += "<!DOCTYPE " + n.name
2488                                 if ((n.public_identifier != null) && n.public_identifier.length > 0) {
2489                                         ret += " \"" + n.public_identifier + "\""
2490                                 }
2491                                 if ((n.system_identifier != null) && n.system_identifier.length > 0) {
2492                                         ret += " \"" + n.system_identifier + "\""
2493                                 }
2494                                 ret += ">"
2495                 }
2496                 want_nl = true
2497                 if (in_flow) {
2498                         prev_in_flow_is_text = is_text
2499                         prev_in_flow_is_block = is_block || (in_flow && is_br)
2500                 }
2501         }
2502         if (tree.length) {
2503                 // output final newline if allowed
2504                 if (!parent_flags.pre_ish) {
2505                         if (prev_in_flow_is_block || parent_flags.block) {
2506                                 ret += "\n" + (indent.substr(4))
2507                         }
2508                 }
2509         }
2510         return ret
2511 }
2512 PeachHTML5Editor.prototype.onblur = function() {
2513         this.editor_is_focused = false
2514         this.kill_cursor()
2515 }
2516 PeachHTML5Editor.prototype.have_focus = function() {
2517         if (!this.editor_is_focused) {
2518                 this.input_el.focus()
2519                 this.editor_is_focused = true
2520         }
2521 }
2522
2523 window.peach_html5_editor = function() {
2524         // coffeescript: return new PeachHTML5Editor args...
2525         // compiles to below... there must be a better way
2526         var args
2527         args = 1 <= arguments.length ? slice.call(arguments, 0) : []
2528         return (function(func, args, ctor) {
2529                 ctor.prototype = func.prototype
2530                 var child = new ctor, result = func.apply(child, args)
2531                 return Object(result) === result ? result : child
2532         })(PeachHTML5Editor, args, function(){})
2533 }
2534
2535 }).call(this)
2536
2537 // test in browser: peach_html5_editor(document.getElementsByTagName('textarea')[0])