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