]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
Merge pull request #236 from Tyriar/235_fix_scroll_to_top_on_app_mode
[mirror_xterm.js.git] / src / xterm.js
1 /**
2 * xterm.js: xterm, in the browser
3 * Copyright (c) 2014, sourceLair Limited (www.sourcelair.com (MIT License)
4 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
5 * https://github.com/chjj/term.js
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 *
25 * Originally forked from (with the author's permission):
26 * Fabrice Bellard's javascript vt100 for jslinux:
27 * http://bellard.org/jslinux/
28 * Copyright (c) 2011 Fabrice Bellard
29 * The original design remains. The terminal itself
30 * has been extended to include xterm CSI codes, among
31 * other features.
32 */
33
34 (function (xterm) {
35 if (typeof exports === 'object' && typeof module === 'object') {
36 /*
37 * CommonJS environment
38 */
39 module.exports = xterm.call(this);
40 } else if (typeof define == 'function') {
41 /*
42 * Require.js is available
43 */
44 define([], xterm.bind(window));
45 } else {
46 /*
47 * Plain browser environment
48 */
49 this.Xterm = xterm.call(this);
50 this.Terminal = this.Xterm; /* Backwards compatibility with term.js */
51 }
52 })(function() {
53 /**
54 * Terminal Emulation References:
55 * http://vt100.net/
56 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
57 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
58 * http://invisible-island.net/vttest/
59 * http://www.inwap.com/pdp10/ansicode.txt
60 * http://linux.die.net/man/4/console_codes
61 * http://linux.die.net/man/7/urxvt
62 */
63
64 'use strict';
65
66 /**
67 * Shared
68 */
69
70 var window = this, document = this.document;
71
72 /**
73 * EventEmitter
74 */
75
76 function EventEmitter() {
77 this._events = this._events || {};
78 }
79
80 EventEmitter.prototype.addListener = function(type, listener) {
81 this._events[type] = this._events[type] || [];
82 this._events[type].push(listener);
83 };
84
85 EventEmitter.prototype.on = EventEmitter.prototype.addListener;
86
87 EventEmitter.prototype.removeListener = function(type, listener) {
88 if (!this._events[type]) return;
89
90 var obj = this._events[type]
91 , i = obj.length;
92
93 while (i--) {
94 if (obj[i] === listener || obj[i].listener === listener) {
95 obj.splice(i, 1);
96 return;
97 }
98 }
99 };
100
101 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
102
103 EventEmitter.prototype.removeAllListeners = function(type) {
104 if (this._events[type]) delete this._events[type];
105 };
106
107 EventEmitter.prototype.once = function(type, listener) {
108 var self = this;
109 function on() {
110 var args = Array.prototype.slice.call(arguments);
111 this.removeListener(type, on);
112 return listener.apply(this, args);
113 }
114 on.listener = listener;
115 return this.on(type, on);
116 };
117
118 EventEmitter.prototype.emit = function(type) {
119 if (!this._events[type]) return;
120
121 var args = Array.prototype.slice.call(arguments, 1)
122 , obj = this._events[type]
123 , l = obj.length
124 , i = 0;
125
126 for (; i < l; i++) {
127 obj[i].apply(this, args);
128 }
129 };
130
131 EventEmitter.prototype.listeners = function(type) {
132 return this._events[type] = this._events[type] || [];
133 };
134
135
136 /**
137 * Encapsulates the logic for handling compositionstart, compositionupdate and compositionend
138 * events, displaying the in-progress composition to the UI and forwarding the final composition
139 * to the handler.
140 * @param {HTMLTextAreaElement} textarea The textarea that xterm uses for input.
141 * @param {HTMLElement} compositionView The element to display the in-progress composition in.
142 * @param {Terminal} terminal The Terminal to forward the finished composition to.
143 */
144 function CompositionHelper(textarea, compositionView, terminal) {
145 this.textarea = textarea;
146 this.compositionView = compositionView;
147 this.terminal = terminal;
148
149 // Whether input composition is currently happening, eg. via a mobile keyboard, speech input
150 // or IME. This variable determines whether the compositionText should be displayed on the UI.
151 this.isComposing = false;
152
153 // The input currently being composed, eg. via a mobile keyboard, speech input or IME.
154 this.compositionText = null;
155
156 // The position within the input textarea's value of the current composition.
157 this.compositionPosition = { start: null, end: null };
158
159 // Whether a composition is in the process of being sent, setting this to false will cancel
160 // any in-progress composition.
161 this.isSendingComposition = false;
162 }
163
164 /**
165 * Handles the compositionstart event, activating the composition view.
166 */
167 CompositionHelper.prototype.compositionstart = function() {
168 this.isComposing = true;
169 this.compositionPosition.start = this.textarea.value.length;
170 this.compositionView.textContent = '';
171 this.compositionView.classList.add('active');
172 };
173
174 /**
175 * Handles the compositionupdate event, updating the composition view.
176 * @param {CompositionEvent} ev The event.
177 */
178 CompositionHelper.prototype.compositionupdate = function(ev) {
179 this.compositionView.textContent = ev.data;
180 this.updateCompositionElements();
181 var self = this;
182 setTimeout(function() {
183 self.compositionPosition.end = self.textarea.value.length;
184 }, 0);
185 };
186
187 /**
188 * Handles the compositionend event, hiding the composition view and sending the composition to
189 * the handler.
190 */
191 CompositionHelper.prototype.compositionend = function() {
192 this.finalizeComposition(true);
193 };
194
195 /**
196 * Handles the keydown event, routing any necessary events to the CompositionHelper functions.
197 * @return Whether the Terminal should continue processing the keydown event.
198 */
199 CompositionHelper.prototype.keydown = function(ev) {
200 if (this.isComposing || this.isSendingComposition) {
201 if (ev.keyCode === 229) {
202 // Continue composing if the keyCode is the "composition character"
203 return false;
204 } else if (ev.keyCode === 16 || ev.keyCode === 17 || ev.keyCode === 18) {
205 // Continue composing if the keyCode is a modifier key
206 return false;
207 } else {
208 // Finish composition immediately. This is mainly here for the case where enter is
209 // pressed and the handler needs to be triggered before the command is executed.
210 this.finalizeComposition(false);
211 }
212 }
213
214 if (ev.keyCode === 229) {
215 // If the "composition character" is used but gets to this point it means a non-composition
216 // character (eg. numbers and punctuation) was pressed when the IME was active.
217 this.handleAnyTextareaChanges();
218 return false;
219 }
220
221 return true;
222 };
223
224 /**
225 * Finalizes the composition, resuming regular input actions. This is called when a composition
226 * is ending.
227 * @param {boolean} waitForPropogation Whether to wait for events to propogate before sending
228 * the input. This should be false if a non-composition keystroke is entered before the
229 * compositionend event is triggered, such as enter, so that the composition is send before
230 * the command is executed.
231 */
232 CompositionHelper.prototype.finalizeComposition = function(waitForPropogation) {
233 this.compositionView.classList.remove('active');
234 this.isComposing = false;
235 this.clearTextareaPosition();
236
237 if (!waitForPropogation) {
238 // Cancel any delayed composition send requests and send the input immediately.
239 this.isSendingComposition = false;
240 var input = this.textarea.value.substring(this.compositionPosition.start, this.compositionPosition.end);
241 this.terminal.handler(input);
242 } else {
243 // Make a deep copy of the composition position here as a new compositionstart event may
244 // fire before the setTimeout executes.
245 var currentCompositionPosition = {
246 start: this.compositionPosition.start,
247 end: this.compositionPosition.end,
248 }
249
250 // Since composition* events happen before the changes take place in the textarea on most
251 // browsers, use a setTimeout with 0ms time to allow the native compositionend event to
252 // complete. This ensures the correct character is retrieved, this solution was used
253 // because:
254 // - The compositionend event's data property is unreliable, at least on Chromium
255 // - The last compositionupdate event's data property does not always accurately describe
256 // the character, a counter example being Korean where an ending consonsant can move to
257 // the following character if the following input is a vowel.
258 var self = this;
259 this.isSendingComposition = true;
260 setTimeout(function () {
261 // Ensure that the input has not already been sent
262 if (self.isSendingComposition) {
263 self.isSendingComposition = false;
264 var input;
265 if (self.isComposing) {
266 // Use the end position to get the string if a new composition has started.
267 input = self.textarea.value.substring(currentCompositionPosition.start, currentCompositionPosition.end);
268 } else {
269 // Don't use the end position here in order to pick up any characters after the
270 // composition has finished, for example when typing a non-composition character
271 // (eg. 2) after a composition character.
272 input = self.textarea.value.substring(currentCompositionPosition.start);
273 }
274 self.terminal.handler(input);
275 }
276 }, 0);
277 }
278 };
279
280 /**
281 * Apply any changes made to the textarea after the current event chain is allowed to complete.
282 * This should be called when not currently composing but a keydown event with the "composition
283 * character" (229) is triggered, in order to allow non-composition text to be entered when an
284 * IME is active.
285 */
286 CompositionHelper.prototype.handleAnyTextareaChanges = function() {
287 var oldValue = this.textarea.value;
288 var self = this;
289 setTimeout(function() {
290 // Ignore if a composition has started since the timeout
291 if (!self.isComposing) {
292 var newValue = self.textarea.value;
293 var diff = newValue.replace(oldValue, '');
294 if (diff.length > 0) {
295 self.terminal.handler(diff);
296 }
297 }
298 }, 0);
299 };
300
301 /**
302 * Positions the composition view on top of the cursor and the textarea just below it (so the
303 * IME helper dialog is positioned correctly).
304 */
305 CompositionHelper.prototype.updateCompositionElements = function(dontRecurse) {
306 if (!this.isComposing) {
307 return;
308 }
309 var cursor = this.terminal.element.querySelector('.terminal-cursor');
310 if (cursor) {
311 this.compositionView.style.left = cursor.offsetLeft + 'px';
312 this.compositionView.style.top = cursor.offsetTop + 'px';
313 var compositionViewBounds = this.compositionView.getBoundingClientRect();
314 this.textarea.style.left = cursor.offsetLeft + compositionViewBounds.width + 'px';
315 this.textarea.style.top = (cursor.offsetTop + cursor.offsetHeight) + 'px';
316 }
317 if (!dontRecurse) {
318 setTimeout(this.updateCompositionElements.bind(this, true), 0);
319 }
320 };
321
322 /**
323 * Clears the textarea's position so that the cursor does not blink on IE.
324 * @private
325 */
326 CompositionHelper.prototype.clearTextareaPosition = function() {
327 this.textarea.style.left = '';
328 this.textarea.style.top = '';
329 };
330
331 /**
332 * Represents the viewport of a terminal, the visible area within the larger buffer of output.
333 * Logic for the virtual scroll bar is included in this object.
334 * @param {Terminal} terminal The Terminal object.
335 * @param {HTMLElement} viewportElement The DOM element acting as the viewport
336 * @param {HTMLElement} charMeasureElement A DOM element used to measure the character size of
337 * the terminal.
338 */
339 function Viewport(terminal, viewportElement, scrollArea, charMeasureElement) {
340 this.terminal = terminal;
341 this.viewportElement = viewportElement;
342 this.scrollArea = scrollArea;
343 this.charMeasureElement = charMeasureElement;
344 this.currentRowHeight = 0;
345 this.lastRecordedBufferLength = 0;
346 this.lastRecordedViewportHeight = 0;
347
348 this.terminal.on('scroll', this.syncScrollArea.bind(this));
349 this.terminal.on('resize', this.syncScrollArea.bind(this));
350 this.viewportElement.addEventListener('scroll', this.onScroll.bind(this));
351
352 this.syncScrollArea();
353 }
354
355 /**
356 * Refreshes row height, setting line-height, viewport height and scroll area height if
357 * necessary.
358 * @param {number|undefined} charSize A character size measurement bounding rect object, if it
359 * doesn't exist it will be created.
360 */
361 Viewport.prototype.refresh = function(charSize) {
362 var size = charSize || this.charMeasureElement.getBoundingClientRect();
363 if (size.height > 0) {
364 var rowHeightChanged = size.height !== this.currentRowHeight;
365 if (rowHeightChanged) {
366 this.currentRowHeight = size.height;
367 this.viewportElement.style.lineHeight = size.height + 'px';
368 this.terminal.rowContainer.style.lineHeight = size.height + 'px';
369 }
370 var viewportHeightChanged = this.lastRecordedViewportHeight !== this.terminal.rows;
371 if (rowHeightChanged || viewportHeightChanged) {
372 this.lastRecordedViewportHeight = this.terminal.rows;
373 this.viewportElement.style.height = size.height * this.terminal.rows + 'px';
374 }
375 this.scrollArea.style.height = (size.height * this.lastRecordedBufferLength) + 'px';
376 }
377 };
378
379 /**
380 * Updates dimensions and synchronizes the scroll area if necessary.
381 */
382 Viewport.prototype.syncScrollArea = function() {
383 if (this.isApplicationMode) {
384 // Fix scroll bar in application mode
385 this.lastRecordedBufferLength = this.terminal.rows;
386 this.refresh();
387 return;
388 }
389
390 if (this.lastRecordedBufferLength !== this.terminal.lines.length) {
391 // If buffer height changed
392 this.lastRecordedBufferLength = this.terminal.lines.length;
393 this.refresh();
394 } else if (this.lastRecordedViewportHeight !== this.terminal.rows) {
395 // If viewport height changed
396 this.refresh();
397 } else {
398 // If size has changed, refresh viewport
399 var size = this.charMeasureElement.getBoundingClientRect();
400 if (size.height !== this.currentRowHeight) {
401 this.refresh(size);
402 }
403 }
404
405 // Sync scrollTop
406 var scrollTop = this.terminal.ydisp * this.currentRowHeight;
407 if (this.viewportElement.scrollTop !== scrollTop) {
408 this.viewportElement.scrollTop = scrollTop;
409 }
410 };
411
412 /**
413 * Sets the application mode of the viewport.
414 * @param {boolean} isApplicationMode Sets whether the terminal is in application mode. true
415 * for application mode (DECKPAM) and false for normal mode (DECKPNM).
416 */
417 Viewport.prototype.setApplicationMode = function(isApplicationMode) {
418 this.isApplicationMode = isApplicationMode;
419 this.syncScrollArea();
420 };
421
422 /**
423 * Handles scroll events on the viewport, calculating the new viewport and requesting the
424 * terminal to scroll to it.
425 * @param {Event} ev The scroll event.
426 */
427 Viewport.prototype.onScroll = function(ev) {
428 if (this.isApplicationMode) {
429 // Scrolling via the scroll bar is disabled during application mode
430 return;
431 }
432 var newRow = Math.round(this.viewportElement.scrollTop / this.currentRowHeight);
433 var diff = newRow - this.terminal.ydisp;
434 this.terminal.scrollDisp(diff, true);
435 };
436
437 /**
438 * Handles mouse wheel events by adjusting the viewport's scrollTop and delegating the actual
439 * scrolling to `onScroll`, this event needs to be attached manually by the consumer of
440 * `Viewport`.
441 * @param {WheelEvent} ev The mouse wheel event.
442 */
443 Viewport.prototype.onWheel = function(ev) {
444 if (ev.deltaY === 0) {
445 // Do nothing if it's not a vertical scroll event
446 return;
447 }
448 // Fallback to WheelEvent.DOM_DELTA_PIXEL
449 var multiplier = 1;
450 if (ev.deltaMode === WheelEvent.DOM_DELTA_LINE) {
451 multiplier = this.currentRowHeight;
452 } else if (ev.deltaMode === WheelEvent.DOM_DELTA_PAGE) {
453 multiplier = this.currentRowHeight * this.terminal.rows;
454 }
455 this.viewportElement.scrollTop += ev.deltaY * multiplier;
456 // Prevent the page from scrolling when the terminal scrolls
457 ev.preventDefault();
458 };
459
460 /**
461 * States
462 */
463 var normal = 0, escaped = 1, csi = 2, osc = 3, charset = 4, dcs = 5, ignore = 6;
464
465 /**
466 * Terminal
467 */
468
469 /**
470 * Creates a new `Terminal` object.
471 *
472 * @param {object} options An object containing a set of options, the available options are:
473 * - cursorBlink (boolean): Whether the terminal cursor blinks
474 *
475 * @public
476 * @class Xterm Xterm
477 * @alias module:xterm/src/xterm
478 */
479 function Terminal(options) {
480 var self = this;
481
482 if (!(this instanceof Terminal)) {
483 return new Terminal(arguments[0], arguments[1], arguments[2]);
484 }
485
486 self.cancel = Terminal.cancel;
487
488 EventEmitter.call(this);
489
490 if (typeof options === 'number') {
491 options = {
492 cols: arguments[0],
493 rows: arguments[1],
494 handler: arguments[2]
495 };
496 }
497
498 options = options || {};
499
500
501 Object.keys(Terminal.defaults).forEach(function(key) {
502 if (options[key] == null) {
503 options[key] = Terminal.options[key];
504
505 if (Terminal[key] !== Terminal.defaults[key]) {
506 options[key] = Terminal[key];
507 }
508 }
509 self[key] = options[key];
510 });
511
512 if (options.colors.length === 8) {
513 options.colors = options.colors.concat(Terminal._colors.slice(8));
514 } else if (options.colors.length === 16) {
515 options.colors = options.colors.concat(Terminal._colors.slice(16));
516 } else if (options.colors.length === 10) {
517 options.colors = options.colors.slice(0, -2).concat(
518 Terminal._colors.slice(8, -2), options.colors.slice(-2));
519 } else if (options.colors.length === 18) {
520 options.colors = options.colors.concat(
521 Terminal._colors.slice(16, -2), options.colors.slice(-2));
522 }
523 this.colors = options.colors;
524
525 this.options = options;
526
527 // this.context = options.context || window;
528 // this.document = options.document || document;
529 this.parent = options.body || options.parent
530 || (document ? document.getElementsByTagName('body')[0] : null);
531
532 this.cols = options.cols || options.geometry[0];
533 this.rows = options.rows || options.geometry[1];
534
535 if (options.handler) {
536 this.on('data', options.handler);
537 }
538
539 /**
540 * The scroll position of the y cursor, ie. ybase + y = the y position within the entire
541 * buffer
542 */
543 this.ybase = 0;
544
545 /**
546 * The scroll position of the viewport
547 */
548 this.ydisp = 0;
549
550 /**
551 * The cursor's x position after ybase
552 */
553 this.x = 0;
554
555 /**
556 * The cursor's y position after ybase
557 */
558 this.y = 0;
559
560 /**
561 * Used to debounce the refresh function
562 */
563 this.isRefreshing = false;
564
565 /**
566 * Whether there is a full terminal refresh queued
567 */
568
569 this.cursorState = 0;
570 this.cursorHidden = false;
571 this.convertEol;
572 this.state = 0;
573 this.queue = '';
574 this.scrollTop = 0;
575 this.scrollBottom = this.rows - 1;
576 this.customKeydownHandler = null;
577
578 // modes
579 this.applicationKeypad = false;
580 this.applicationCursor = false;
581 this.originMode = false;
582 this.insertMode = false;
583 this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
584 this.normal = null;
585
586 // charset
587 this.charset = null;
588 this.gcharset = null;
589 this.glevel = 0;
590 this.charsets = [null];
591
592 // mouse properties
593 this.decLocator;
594 this.x10Mouse;
595 this.vt200Mouse;
596 this.vt300Mouse;
597 this.normalMouse;
598 this.mouseEvents;
599 this.sendFocus;
600 this.utfMouse;
601 this.sgrMouse;
602 this.urxvtMouse;
603
604 // misc
605 this.element;
606 this.children;
607 this.refreshStart;
608 this.refreshEnd;
609 this.savedX;
610 this.savedY;
611 this.savedCols;
612
613 // stream
614 this.readable = true;
615 this.writable = true;
616
617 this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
618 this.curAttr = this.defAttr;
619
620 this.params = [];
621 this.currentParam = 0;
622 this.prefix = '';
623 this.postfix = '';
624
625 // leftover surrogate high from previous write invocation
626 this.surrogate_high = '';
627
628 /**
629 * An array of all lines in the entire buffer, including the prompt. The lines are array of
630 * characters which are 2-length arrays where [0] is an attribute and [1] is the character.
631 */
632 this.lines = [];
633 var i = this.rows;
634 while (i--) {
635 this.lines.push(this.blankLine());
636 }
637
638 this.tabs;
639 this.setupStops();
640 }
641
642 inherits(Terminal, EventEmitter);
643
644 /**
645 * back_color_erase feature for xterm.
646 */
647 Terminal.prototype.eraseAttr = function() {
648 // if (this.is('screen')) return this.defAttr;
649 return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
650 };
651
652 /**
653 * Colors
654 */
655
656 // Colors 0-15
657 Terminal.tangoColors = [
658 // dark:
659 '#2e3436',
660 '#cc0000',
661 '#4e9a06',
662 '#c4a000',
663 '#3465a4',
664 '#75507b',
665 '#06989a',
666 '#d3d7cf',
667 // bright:
668 '#555753',
669 '#ef2929',
670 '#8ae234',
671 '#fce94f',
672 '#729fcf',
673 '#ad7fa8',
674 '#34e2e2',
675 '#eeeeec'
676 ];
677
678 // Colors 0-15 + 16-255
679 // Much thanks to TooTallNate for writing this.
680 Terminal.colors = (function() {
681 var colors = Terminal.tangoColors.slice()
682 , r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
683 , i;
684
685 // 16-231
686 i = 0;
687 for (; i < 216; i++) {
688 out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
689 }
690
691 // 232-255 (grey)
692 i = 0;
693 for (; i < 24; i++) {
694 r = 8 + i * 10;
695 out(r, r, r);
696 }
697
698 function out(r, g, b) {
699 colors.push('#' + hex(r) + hex(g) + hex(b));
700 }
701
702 function hex(c) {
703 c = c.toString(16);
704 return c.length < 2 ? '0' + c : c;
705 }
706
707 return colors;
708 })();
709
710 Terminal._colors = Terminal.colors.slice();
711
712 Terminal.vcolors = (function() {
713 var out = []
714 , colors = Terminal.colors
715 , i = 0
716 , color;
717
718 for (; i < 256; i++) {
719 color = parseInt(colors[i].substring(1), 16);
720 out.push([
721 (color >> 16) & 0xff,
722 (color >> 8) & 0xff,
723 color & 0xff
724 ]);
725 }
726
727 return out;
728 })();
729
730 /**
731 * Options
732 */
733
734 Terminal.defaults = {
735 colors: Terminal.colors,
736 theme: 'default',
737 convertEol: false,
738 termName: 'xterm',
739 geometry: [80, 24],
740 cursorBlink: false,
741 visualBell: false,
742 popOnBell: false,
743 scrollback: 1000,
744 screenKeys: false,
745 debug: false,
746 cancelEvents: false
747 // programFeatures: false,
748 // focusKeys: false,
749 };
750
751 Terminal.options = {};
752
753 Terminal.focus = null;
754
755 each(keys(Terminal.defaults), function(key) {
756 Terminal[key] = Terminal.defaults[key];
757 Terminal.options[key] = Terminal.defaults[key];
758 });
759
760 /**
761 * Focus the terminal. Delegates focus handling to the terminal's DOM element.
762 */
763 Terminal.prototype.focus = function() {
764 return this.textarea.focus();
765 };
766
767 /**
768 * Binds the desired focus behavior on a given terminal object.
769 *
770 * @static
771 */
772 Terminal.bindFocus = function (term) {
773 on(term.textarea, 'focus', function (ev) {
774 if (term.sendFocus) {
775 term.send('\x1b[I');
776 }
777 term.element.classList.add('focus');
778 term.showCursor();
779 Terminal.focus = term;
780 term.emit('focus', {terminal: term});
781 });
782 };
783
784 /**
785 * Blur the terminal. Delegates blur handling to the terminal's DOM element.
786 */
787 Terminal.prototype.blur = function() {
788 return this.textarea.blur();
789 };
790
791 /**
792 * Binds the desired blur behavior on a given terminal object.
793 *
794 * @static
795 */
796 Terminal.bindBlur = function (term) {
797 on(term.textarea, 'blur', function (ev) {
798 term.refresh(term.y, term.y);
799 if (term.sendFocus) {
800 term.send('\x1b[O');
801 }
802 term.element.classList.remove('focus');
803 Terminal.focus = null;
804 term.emit('blur', {terminal: term});
805 });
806 };
807
808 /**
809 * Initialize default behavior
810 */
811 Terminal.prototype.initGlobal = function() {
812 Terminal.bindPaste(this);
813 Terminal.bindKeys(this);
814 Terminal.bindCopy(this);
815 Terminal.bindFocus(this);
816 Terminal.bindBlur(this);
817 };
818
819 /**
820 * Bind to paste event and allow both keyboard and right-click pasting, without having the
821 * contentEditable value set to true.
822 */
823 Terminal.bindPaste = function(term) {
824 on([term.textarea, term.element], 'paste', function(ev) {
825 ev.stopPropagation();
826 if (ev.clipboardData) {
827 var text = ev.clipboardData.getData('text/plain');
828 term.handler(text);
829 term.textarea.value = '';
830 return term.cancel(ev);
831 }
832 });
833 };
834
835 /**
836 * Prepares text copied from terminal selection, to be saved in the clipboard by:
837 * 1. stripping all trailing white spaces
838 * 2. converting all non-breaking spaces to regular spaces
839 * @param {string} text The copied text that needs processing for storing in clipboard
840 * @returns {string}
841 * @static
842 */
843 Terminal.prepareCopiedTextForClipboard = function (text) {
844 var space = String.fromCharCode(32),
845 nonBreakingSpace = String.fromCharCode(160),
846 allNonBreakingSpaces = new RegExp(nonBreakingSpace, 'g'),
847 processedText = text.split('\n').map(function (line) {
848 /**
849 * Strip all trailing white spaces and convert all non-breaking spaces to regular
850 * spaces.
851 */
852 var processedLine = line.replace(/\s+$/g, '').replace(allNonBreakingSpaces, space);
853
854 return processedLine;
855 }).join('\n');
856
857 return processedText;
858 };
859
860 /**
861 * Apply key handling to the terminal
862 */
863 Terminal.bindKeys = function(term) {
864 on(term.element, 'keydown', function(ev) {
865 if (document.activeElement != this) {
866 return;
867 }
868 term.keyDown(ev);
869 }, true);
870
871 on(term.element, 'keypress', function(ev) {
872 if (document.activeElement != this) {
873 return;
874 }
875 term.keyPress(ev);
876 }, true);
877
878 on(term.element, 'keyup', term.focus.bind(term));
879
880 on(term.textarea, 'keydown', function(ev) {
881 term.keyDown(ev);
882 }, true);
883
884 on(term.textarea, 'keypress', function(ev) {
885 term.keyPress(ev);
886 // Truncate the textarea's value, since it is not needed
887 this.value = '';
888 }, true);
889
890 on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
891 on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
892 on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
893 term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
894 };
895
896 /**
897 * Binds copy functionality to the given terminal.
898 * @static
899 */
900 Terminal.bindCopy = function(term) {
901 on(term.element, 'copy', function(ev) {
902 return; // temporary
903 });
904 };
905
906
907 /**
908 * Insert the given row to the terminal or produce a new one
909 * if no row argument is passed. Return the inserted row.
910 * @param {HTMLElement} row (optional) The row to append to the terminal.
911 */
912 Terminal.prototype.insertRow = function (row) {
913 if (typeof row != 'object') {
914 row = document.createElement('div');
915 }
916
917 this.rowContainer.appendChild(row);
918 this.children.push(row);
919
920 return row;
921 };
922
923 /**
924 * Opens the terminal within an element.
925 *
926 * @param {HTMLElement} parent The element to create the terminal within.
927 */
928 Terminal.prototype.open = function(parent) {
929 var self=this, i=0, div;
930
931 this.parent = parent || this.parent;
932
933 if (!this.parent) {
934 throw new Error('Terminal requires a parent element.');
935 }
936
937 /*
938 * Grab global elements
939 */
940 this.context = this.parent.ownerDocument.defaultView;
941 this.document = this.parent.ownerDocument;
942 this.body = this.document.getElementsByTagName('body')[0];
943
944 /*
945 * Parse User-Agent
946 */
947 if (this.context.navigator && this.context.navigator.userAgent) {
948 this.isMSIE = !!~this.context.navigator.userAgent.indexOf('MSIE');
949 }
950
951 /*
952 * Find the users platform. We use this to interpret the meta key
953 * and ISO third level shifts.
954 * http://stackoverflow.com/questions/19877924/what-is-the-list-of-possible-values-for-navigator-platform-as-of-today
955 */
956 if (this.context.navigator && this.context.navigator.platform) {
957 this.isMac = contains(
958 this.context.navigator.platform,
959 ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K']
960 );
961 this.isIpad = this.context.navigator.platform === 'iPad';
962 this.isIphone = this.context.navigator.platform === 'iPhone';
963 this.isMSWindows = contains(
964 this.context.navigator.platform,
965 ['Windows', 'Win16', 'Win32', 'WinCE']
966 );
967 }
968
969 /*
970 * Create main element container
971 */
972 this.element = this.document.createElement('div');
973 this.element.classList.add('terminal');
974 this.element.classList.add('xterm');
975 this.element.classList.add('xterm-theme-' + this.theme);
976
977 this.element.style.height
978 this.element.setAttribute('tabindex', 0);
979
980 this.viewportElement = document.createElement('div');
981 this.viewportElement.classList.add('xterm-viewport');
982 this.element.appendChild(this.viewportElement);
983 this.viewportScrollArea = document.createElement('div');
984 this.viewportScrollArea.classList.add('xterm-scroll-area');
985 this.viewportElement.appendChild(this.viewportScrollArea);
986
987 /*
988 * Create the container that will hold the lines of the terminal and then
989 * produce the lines the lines.
990 */
991 this.rowContainer = document.createElement('div');
992 this.rowContainer.classList.add('xterm-rows');
993 this.element.appendChild(this.rowContainer);
994 this.children = [];
995
996 /*
997 * Create the container that will hold helpers like the textarea for
998 * capturing DOM Events. Then produce the helpers.
999 */
1000 this.helperContainer = document.createElement('div');
1001 this.helperContainer.classList.add('xterm-helpers');
1002 // TODO: This should probably be inserted once it's filled to prevent an additional layout
1003 this.element.appendChild(this.helperContainer);
1004 this.textarea = document.createElement('textarea');
1005 this.textarea.classList.add('xterm-helper-textarea');
1006 this.textarea.setAttribute('autocorrect', 'off');
1007 this.textarea.setAttribute('autocapitalize', 'off');
1008 this.textarea.setAttribute('spellcheck', 'false');
1009 this.textarea.tabIndex = 0;
1010 this.textarea.addEventListener('focus', function() {
1011 self.emit('focus', {terminal: self});
1012 });
1013 this.textarea.addEventListener('blur', function() {
1014 self.emit('blur', {terminal: self});
1015 });
1016 this.helperContainer.appendChild(this.textarea);
1017
1018 this.compositionView = document.createElement('div');
1019 this.compositionView.classList.add('composition-view');
1020 this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
1021 this.helperContainer.appendChild(this.compositionView);
1022
1023 this.charMeasureElement = document.createElement('div');
1024 this.charMeasureElement.classList.add('xterm-char-measure-element');
1025 this.charMeasureElement.innerHTML = 'W';
1026 this.helperContainer.appendChild(this.charMeasureElement);
1027
1028 for (; i < this.rows; i++) {
1029 this.insertRow();
1030 }
1031 this.parent.appendChild(this.element);
1032
1033 this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasureElement);
1034
1035 // Draw the screen.
1036 this.refresh(0, this.rows - 1);
1037
1038 // Initialize global actions that
1039 // need to be taken on the document.
1040 this.initGlobal();
1041
1042 // Ensure there is a Terminal.focus.
1043 this.focus();
1044
1045 on(this.element, 'mouseup', function() {
1046 var selection = document.getSelection(),
1047 collapsed = selection.isCollapsed,
1048 isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
1049 if (!isRange) {
1050 self.focus();
1051 }
1052 });
1053
1054 // Listen for mouse events and translate
1055 // them into terminal mouse protocols.
1056 this.bindMouse();
1057
1058 // Figure out whether boldness affects
1059 // the character width of monospace fonts.
1060 if (Terminal.brokenBold == null) {
1061 Terminal.brokenBold = isBoldBroken(this.document);
1062 }
1063
1064 this.emit('open');
1065 };
1066
1067
1068 /**
1069 * Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
1070 * @param {string} addon The name of the addon to load
1071 * @static
1072 */
1073 Terminal.loadAddon = function(addon, callback) {
1074 if (typeof exports === 'object' && typeof module === 'object') {
1075 // CommonJS
1076 return require(__dirname + '/../addons/' + addon);
1077 } else if (typeof define == 'function') {
1078 // RequireJS
1079 return require(['../addons/' + addon + '/' + addon], callback);
1080 } else {
1081 console.error('Cannot load a module without a CommonJS or RequireJS environment.');
1082 return false;
1083 }
1084 };
1085
1086
1087 /**
1088 * XTerm mouse events
1089 * http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
1090 * To better understand these
1091 * the xterm code is very helpful:
1092 * Relevant files:
1093 * button.c, charproc.c, misc.c
1094 * Relevant functions in xterm/button.c:
1095 * BtnCode, EmitButtonCode, EditorButton, SendMousePosition
1096 */
1097 Terminal.prototype.bindMouse = function() {
1098 var el = this.element, self = this, pressed = 32;
1099
1100 // mouseup, mousedown, wheel
1101 // left click: ^[[M 3<^[[M#3<
1102 // wheel up: ^[[M`3>
1103 function sendButton(ev) {
1104 var button
1105 , pos;
1106
1107 // get the xterm-style button
1108 button = getButton(ev);
1109
1110 // get mouse coordinates
1111 pos = getCoords(ev);
1112 if (!pos) return;
1113
1114 sendEvent(button, pos);
1115
1116 switch (ev.overrideType || ev.type) {
1117 case 'mousedown':
1118 pressed = button;
1119 break;
1120 case 'mouseup':
1121 // keep it at the left
1122 // button, just in case.
1123 pressed = 32;
1124 break;
1125 case 'wheel':
1126 // nothing. don't
1127 // interfere with
1128 // `pressed`.
1129 break;
1130 }
1131 }
1132
1133 // motion example of a left click:
1134 // ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
1135 function sendMove(ev) {
1136 var button = pressed
1137 , pos;
1138
1139 pos = getCoords(ev);
1140 if (!pos) return;
1141
1142 // buttons marked as motions
1143 // are incremented by 32
1144 button += 32;
1145
1146 sendEvent(button, pos);
1147 }
1148
1149 // encode button and
1150 // position to characters
1151 function encode(data, ch) {
1152 if (!self.utfMouse) {
1153 if (ch === 255) return data.push(0);
1154 if (ch > 127) ch = 127;
1155 data.push(ch);
1156 } else {
1157 if (ch === 2047) return data.push(0);
1158 if (ch < 127) {
1159 data.push(ch);
1160 } else {
1161 if (ch > 2047) ch = 2047;
1162 data.push(0xC0 | (ch >> 6));
1163 data.push(0x80 | (ch & 0x3F));
1164 }
1165 }
1166 }
1167
1168 // send a mouse event:
1169 // regular/utf8: ^[[M Cb Cx Cy
1170 // urxvt: ^[[ Cb ; Cx ; Cy M
1171 // sgr: ^[[ Cb ; Cx ; Cy M/m
1172 // vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
1173 // locator: CSI P e ; P b ; P r ; P c ; P p & w
1174 function sendEvent(button, pos) {
1175 // self.emit('mouse', {
1176 // x: pos.x - 32,
1177 // y: pos.x - 32,
1178 // button: button
1179 // });
1180
1181 if (self.vt300Mouse) {
1182 // NOTE: Unstable.
1183 // http://www.vt100.net/docs/vt3xx-gp/chapter15.html
1184 button &= 3;
1185 pos.x -= 32;
1186 pos.y -= 32;
1187 var data = '\x1b[24';
1188 if (button === 0) data += '1';
1189 else if (button === 1) data += '3';
1190 else if (button === 2) data += '5';
1191 else if (button === 3) return;
1192 else data += '0';
1193 data += '~[' + pos.x + ',' + pos.y + ']\r';
1194 self.send(data);
1195 return;
1196 }
1197
1198 if (self.decLocator) {
1199 // NOTE: Unstable.
1200 button &= 3;
1201 pos.x -= 32;
1202 pos.y -= 32;
1203 if (button === 0) button = 2;
1204 else if (button === 1) button = 4;
1205 else if (button === 2) button = 6;
1206 else if (button === 3) button = 3;
1207 self.send('\x1b['
1208 + button
1209 + ';'
1210 + (button === 3 ? 4 : 0)
1211 + ';'
1212 + pos.y
1213 + ';'
1214 + pos.x
1215 + ';'
1216 + (pos.page || 0)
1217 + '&w');
1218 return;
1219 }
1220
1221 if (self.urxvtMouse) {
1222 pos.x -= 32;
1223 pos.y -= 32;
1224 pos.x++;
1225 pos.y++;
1226 self.send('\x1b[' + button + ';' + pos.x + ';' + pos.y + 'M');
1227 return;
1228 }
1229
1230 if (self.sgrMouse) {
1231 pos.x -= 32;
1232 pos.y -= 32;
1233 self.send('\x1b[<'
1234 + ((button & 3) === 3 ? button & ~3 : button)
1235 + ';'
1236 + pos.x
1237 + ';'
1238 + pos.y
1239 + ((button & 3) === 3 ? 'm' : 'M'));
1240 return;
1241 }
1242
1243 var data = [];
1244
1245 encode(data, button);
1246 encode(data, pos.x);
1247 encode(data, pos.y);
1248
1249 self.send('\x1b[M' + String.fromCharCode.apply(String, data));
1250 }
1251
1252 function getButton(ev) {
1253 var button
1254 , shift
1255 , meta
1256 , ctrl
1257 , mod;
1258
1259 // two low bits:
1260 // 0 = left
1261 // 1 = middle
1262 // 2 = right
1263 // 3 = release
1264 // wheel up/down:
1265 // 1, and 2 - with 64 added
1266 switch (ev.overrideType || ev.type) {
1267 case 'mousedown':
1268 button = ev.button != null
1269 ? +ev.button
1270 : ev.which != null
1271 ? ev.which - 1
1272 : null;
1273
1274 if (self.isMSIE) {
1275 button = button === 1 ? 0 : button === 4 ? 1 : button;
1276 }
1277 break;
1278 case 'mouseup':
1279 button = 3;
1280 break;
1281 case 'DOMMouseScroll':
1282 button = ev.detail < 0
1283 ? 64
1284 : 65;
1285 break;
1286 case 'wheel':
1287 button = ev.wheelDeltaY > 0
1288 ? 64
1289 : 65;
1290 break;
1291 }
1292
1293 // next three bits are the modifiers:
1294 // 4 = shift, 8 = meta, 16 = control
1295 shift = ev.shiftKey ? 4 : 0;
1296 meta = ev.metaKey ? 8 : 0;
1297 ctrl = ev.ctrlKey ? 16 : 0;
1298 mod = shift | meta | ctrl;
1299
1300 // no mods
1301 if (self.vt200Mouse) {
1302 // ctrl only
1303 mod &= ctrl;
1304 } else if (!self.normalMouse) {
1305 mod = 0;
1306 }
1307
1308 // increment to SP
1309 button = (32 + (mod << 2)) + button;
1310
1311 return button;
1312 }
1313
1314 // mouse coordinates measured in cols/rows
1315 function getCoords(ev) {
1316 var x, y, w, h, el;
1317
1318 // ignore browsers without pageX for now
1319 if (ev.pageX == null) return;
1320
1321 x = ev.pageX;
1322 y = ev.pageY;
1323 el = self.element;
1324
1325 // should probably check offsetParent
1326 // but this is more portable
1327 while (el && el !== self.document.documentElement) {
1328 x -= el.offsetLeft;
1329 y -= el.offsetTop;
1330 el = 'offsetParent' in el
1331 ? el.offsetParent
1332 : el.parentNode;
1333 }
1334
1335 // convert to cols/rows
1336 w = self.element.clientWidth;
1337 h = self.element.clientHeight;
1338 x = Math.ceil((x / w) * self.cols);
1339 y = Math.ceil((y / h) * self.rows);
1340
1341 // be sure to avoid sending
1342 // bad positions to the program
1343 if (x < 0) x = 0;
1344 if (x > self.cols) x = self.cols;
1345 if (y < 0) y = 0;
1346 if (y > self.rows) y = self.rows;
1347
1348 // xterm sends raw bytes and
1349 // starts at 32 (SP) for each.
1350 x += 32;
1351 y += 32;
1352
1353 return {
1354 x: x,
1355 y: y,
1356 type: 'wheel'
1357 };
1358 }
1359
1360 on(el, 'mousedown', function(ev) {
1361 if (!self.mouseEvents) return;
1362
1363 // send the button
1364 sendButton(ev);
1365
1366 // ensure focus
1367 self.focus();
1368
1369 // fix for odd bug
1370 //if (self.vt200Mouse && !self.normalMouse) {
1371 if (self.vt200Mouse) {
1372 ev.overrideType = 'mouseup';
1373 sendButton(ev);
1374 return self.cancel(ev);
1375 }
1376
1377 // bind events
1378 if (self.normalMouse) on(self.document, 'mousemove', sendMove);
1379
1380 // x10 compatibility mode can't send button releases
1381 if (!self.x10Mouse) {
1382 on(self.document, 'mouseup', function up(ev) {
1383 sendButton(ev);
1384 if (self.normalMouse) off(self.document, 'mousemove', sendMove);
1385 off(self.document, 'mouseup', up);
1386 return self.cancel(ev);
1387 });
1388 }
1389
1390 return self.cancel(ev);
1391 });
1392
1393 //if (self.normalMouse) {
1394 // on(self.document, 'mousemove', sendMove);
1395 //}
1396
1397 on(el, 'wheel', function(ev) {
1398 if (!self.mouseEvents) return;
1399 if (self.x10Mouse
1400 || self.vt300Mouse
1401 || self.decLocator) return;
1402 sendButton(ev);
1403 return self.cancel(ev);
1404 });
1405
1406 // allow wheel scrolling in
1407 // the shell for example
1408 on(el, 'wheel', function(ev) {
1409 if (self.mouseEvents) return;
1410 if (self.applicationKeypad) return;
1411 self.viewport.onWheel(ev);
1412 return self.cancel(ev);
1413 });
1414 };
1415
1416 /**
1417 * Destroys the terminal.
1418 */
1419 Terminal.prototype.destroy = function() {
1420 this.readable = false;
1421 this.writable = false;
1422 this._events = {};
1423 this.handler = function() {};
1424 this.write = function() {};
1425 if (this.element.parentNode) {
1426 this.element.parentNode.removeChild(this.element);
1427 }
1428 //this.emit('close');
1429 };
1430
1431
1432 /**
1433 * Flags used to render terminal text properly
1434 */
1435 Terminal.flags = {
1436 BOLD: 1,
1437 UNDERLINE: 2,
1438 BLINK: 4,
1439 INVERSE: 8,
1440 INVISIBLE: 16
1441 }
1442
1443 /**
1444 * Refreshes (re-renders) terminal content within two rows (inclusive)
1445 *
1446 * Rendering Engine:
1447 *
1448 * In the screen buffer, each character is stored as a an array with a character
1449 * and a 32-bit integer:
1450 * - First value: a utf-16 character.
1451 * - Second value:
1452 * - Next 9 bits: background color (0-511).
1453 * - Next 9 bits: foreground color (0-511).
1454 * - Next 14 bits: a mask for misc. flags:
1455 * - 1=bold
1456 * - 2=underline
1457 * - 4=blink
1458 * - 8=inverse
1459 * - 16=invisible
1460 *
1461 * @param {number} start The row to start from (between 0 and terminal's height terminal - 1)
1462 * @param {number} end The row to end at (between fromRow and terminal's height terminal - 1)
1463 * @param {boolean} queue Whether the refresh should ran right now or be queued
1464 */
1465 Terminal.prototype.refresh = function(start, end, queue) {
1466 var self = this;
1467
1468 // queue defaults to true
1469 queue = (typeof queue == 'undefined') ? true : queue;
1470
1471 /**
1472 * The refresh queue allows refresh to execute only approximately 30 times a second. For
1473 * commands that pass a significant amount of output to the write function, this prevents the
1474 * terminal from maxing out the CPU and making the UI unresponsive. While commands can still
1475 * run beyond what they do on the terminal, it is far better with a debounce in place as
1476 * every single terminal manipulation does not need to be constructed in the DOM.
1477 *
1478 * A side-effect of this is that it makes ^C to interrupt a process seem more responsive.
1479 */
1480 if (queue) {
1481 // If refresh should be queued, order the refresh and return.
1482 if (this._refreshIsQueued) {
1483 // If a refresh has already been queued, just order a full refresh next
1484 this._fullRefreshNext = true;
1485 } else {
1486 setTimeout(function () {
1487 self.refresh(start, end, false);
1488 }, 34)
1489 this._refreshIsQueued = true;
1490 }
1491 return;
1492 }
1493
1494 // If refresh should be run right now (not be queued), release the lock
1495 this._refreshIsQueued = false;
1496
1497 // If multiple refreshes were requested, make a full refresh.
1498 if (this._fullRefreshNext) {
1499 start = 0;
1500 end = this.rows - 1;
1501 this._fullRefreshNext = false // reset lock
1502 }
1503
1504 var x, y, i, line, out, ch, ch_width, width, data, attr, bg, fg, flags, row, parent, focused = document.activeElement;
1505
1506 // If this is a big refresh, remove the terminal rows from the DOM for faster calculations
1507 if (end - start >= this.rows / 2) {
1508 parent = this.element.parentNode;
1509 if (parent) {
1510 this.element.removeChild(this.rowContainer);
1511 }
1512 }
1513
1514 width = this.cols;
1515 y = start;
1516
1517 if (end >= this.rows.length) {
1518 this.log('`end` is too large. Most likely a bad CSR.');
1519 end = this.rows.length - 1;
1520 }
1521
1522 for (; y <= end; y++) {
1523 row = y + this.ydisp;
1524
1525 line = this.lines[row];
1526 out = '';
1527
1528 if (this.y === y - (this.ybase - this.ydisp)
1529 && this.cursorState
1530 && !this.cursorHidden) {
1531 x = this.x;
1532 } else {
1533 x = -1;
1534 }
1535
1536 attr = this.defAttr;
1537 i = 0;
1538
1539 for (; i < width; i++) {
1540 data = line[i][0];
1541 ch = line[i][1];
1542 ch_width = line[i][2];
1543 if (!ch_width)
1544 continue;
1545
1546 if (i === x) data = -1;
1547
1548 if (data !== attr) {
1549 if (attr !== this.defAttr) {
1550 out += '</span>';
1551 }
1552 if (data !== this.defAttr) {
1553 if (data === -1) {
1554 out += '<span class="reverse-video terminal-cursor';
1555 if (this.cursorBlink) {
1556 out += ' blinking';
1557 }
1558 out += '">';
1559 } else {
1560 var classNames = [];
1561
1562 bg = data & 0x1ff;
1563 fg = (data >> 9) & 0x1ff;
1564 flags = data >> 18;
1565
1566 if (flags & Terminal.flags.BOLD) {
1567 if (!Terminal.brokenBold) {
1568 classNames.push('xterm-bold');
1569 }
1570 // See: XTerm*boldColors
1571 if (fg < 8) fg += 8;
1572 }
1573
1574 if (flags & Terminal.flags.UNDERLINE) {
1575 classNames.push('xterm-underline');
1576 }
1577
1578 if (flags & Terminal.flags.BLINK) {
1579 classNames.push('xterm-blink');
1580 }
1581
1582 /**
1583 * If inverse flag is on, then swap the foreground and background variables.
1584 */
1585 if (flags & Terminal.flags.INVERSE) {
1586 /* One-line variable swap in JavaScript: http://stackoverflow.com/a/16201730 */
1587 bg = [fg, fg = bg][0];
1588 // Should inverse just be before the
1589 // above boldColors effect instead?
1590 if ((flags & 1) && fg < 8) fg += 8;
1591 }
1592
1593 if (flags & Terminal.flags.INVISIBLE) {
1594 classNames.push('xterm-hidden');
1595 }
1596
1597 /**
1598 * Weird situation: Invert flag used black foreground and white background results
1599 * in invalid background color, positioned at the 256 index of the 256 terminal
1600 * color map. Pin the colors manually in such a case.
1601 *
1602 * Source: https://github.com/sourcelair/xterm.js/issues/57
1603 */
1604 if (flags & Terminal.flags.INVERSE) {
1605 if (bg == 257) {
1606 bg = 15;
1607 }
1608 if (fg == 256) {
1609 fg = 0;
1610 }
1611 }
1612
1613 if (bg < 256) {
1614 classNames.push('xterm-bg-color-' + bg);
1615 }
1616
1617 if (fg < 256) {
1618 classNames.push('xterm-color-' + fg);
1619 }
1620
1621 out += '<span';
1622 if (classNames.length) {
1623 out += ' class="' + classNames.join(' ') + '"';
1624 }
1625 out += '>';
1626 }
1627 }
1628 }
1629
1630 switch (ch) {
1631 case '&':
1632 out += '&amp;';
1633 break;
1634 case '<':
1635 out += '&lt;';
1636 break;
1637 case '>':
1638 out += '&gt;';
1639 break;
1640 default:
1641 if (ch <= ' ') {
1642 out += '&nbsp;';
1643 } else {
1644 out += ch;
1645 }
1646 break;
1647 }
1648
1649 attr = data;
1650 }
1651
1652 if (attr !== this.defAttr) {
1653 out += '</span>';
1654 }
1655
1656 this.children[y].innerHTML = out;
1657 }
1658
1659 if (parent) {
1660 this.element.appendChild(this.rowContainer);
1661 }
1662
1663 this.emit('refresh', {element: this.element, start: start, end: end});
1664 };
1665
1666 /**
1667 * Display the cursor element
1668 */
1669 Terminal.prototype.showCursor = function() {
1670 if (!this.cursorState) {
1671 this.cursorState = 1;
1672 this.refresh(this.y, this.y);
1673 }
1674 };
1675
1676 /**
1677 * Scroll the terminal
1678 */
1679 Terminal.prototype.scroll = function() {
1680 var row;
1681
1682 if (++this.ybase === this.scrollback) {
1683 this.ybase = this.ybase / 2 | 0;
1684 this.lines = this.lines.slice(-(this.ybase + this.rows) + 1);
1685 }
1686
1687 this.ydisp = this.ybase;
1688
1689 // last line
1690 row = this.ybase + this.rows - 1;
1691
1692 // subtract the bottom scroll region
1693 row -= this.rows - 1 - this.scrollBottom;
1694
1695 if (row === this.lines.length) {
1696 // potential optimization:
1697 // pushing is faster than splicing
1698 // when they amount to the same
1699 // behavior.
1700 this.lines.push(this.blankLine());
1701 } else {
1702 // add our new line
1703 this.lines.splice(row, 0, this.blankLine());
1704 }
1705
1706 if (this.scrollTop !== 0) {
1707 if (this.ybase !== 0) {
1708 this.ybase--;
1709 this.ydisp = this.ybase;
1710 }
1711 this.lines.splice(this.ybase + this.scrollTop, 1);
1712 }
1713
1714 // this.maxRange();
1715 this.updateRange(this.scrollTop);
1716 this.updateRange(this.scrollBottom);
1717
1718 this.emit('scroll', this.ydisp);
1719 };
1720
1721 /**
1722 * Scroll the display of the terminal
1723 * @param {number} disp The number of lines to scroll down (negatives scroll up).
1724 * @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
1725 * to avoid unwanted events being handled by the veiwport when the event was triggered from the
1726 * viewport originally.
1727 */
1728 Terminal.prototype.scrollDisp = function(disp, suppressScrollEvent) {
1729 this.ydisp += disp;
1730
1731 if (this.ydisp > this.ybase) {
1732 this.ydisp = this.ybase;
1733 } else if (this.ydisp < 0) {
1734 this.ydisp = 0;
1735 }
1736
1737 if (!suppressScrollEvent) {
1738 this.emit('scroll', this.ydisp);
1739 }
1740
1741 this.refresh(0, this.rows - 1);
1742 };
1743
1744 /**
1745 * Writes text to the terminal.
1746 * @param {string} text The text to write to the terminal.
1747 */
1748 Terminal.prototype.write = function(data) {
1749 var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
1750
1751 this.refreshStart = this.y;
1752 this.refreshEnd = this.y;
1753
1754 if (this.ybase !== this.ydisp) {
1755 this.ydisp = this.ybase;
1756 this.emit('scroll', this.ydisp);
1757 this.maxRange();
1758 }
1759
1760 // apply leftover surrogate high from last write
1761 if (this.surrogate_high) {
1762 data = this.surrogate_high + data;
1763 this.surrogate_high = '';
1764 }
1765
1766 for (; i < l; i++) {
1767 ch = data[i];
1768
1769 // FIXME: higher chars than 0xa0 are not allowed in escape sequences
1770 // --> maybe move to default
1771 code = data.charCodeAt(i);
1772 if (0xD800 <= code && code <= 0xDBFF) {
1773 // we got a surrogate high
1774 // get surrogate low (next 2 bytes)
1775 low = data.charCodeAt(i+1);
1776 if (isNaN(low)) {
1777 // end of data stream, save surrogate high
1778 this.surrogate_high = ch;
1779 continue;
1780 }
1781 code = ((code - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
1782 ch += data.charAt(i+1);
1783 }
1784 // surrogate low - already handled above
1785 if (0xDC00 <= code && code <= 0xDFFF)
1786 continue;
1787
1788 switch (this.state) {
1789 case normal:
1790 switch (ch) {
1791 case '\x07':
1792 this.bell();
1793 break;
1794
1795 // '\n', '\v', '\f'
1796 case '\n':
1797 case '\x0b':
1798 case '\x0c':
1799 if (this.convertEol) {
1800 this.x = 0;
1801 }
1802 this.y++;
1803 if (this.y > this.scrollBottom) {
1804 this.y--;
1805 this.scroll();
1806 }
1807 break;
1808
1809 // '\r'
1810 case '\r':
1811 this.x = 0;
1812 break;
1813
1814 // '\b'
1815 case '\x08':
1816 if (this.x > 0) {
1817 this.x--;
1818 }
1819 break;
1820
1821 // '\t'
1822 case '\t':
1823 this.x = this.nextStop();
1824 break;
1825
1826 // shift out
1827 case '\x0e':
1828 this.setgLevel(1);
1829 break;
1830
1831 // shift in
1832 case '\x0f':
1833 this.setgLevel(0);
1834 break;
1835
1836 // '\e'
1837 case '\x1b':
1838 this.state = escaped;
1839 break;
1840
1841 default:
1842 // ' '
1843 // calculate print space
1844 // expensive call, therefore we save width in line buffer
1845 ch_width = wcwidth(code);
1846
1847 if (ch >= ' ') {
1848 if (this.charset && this.charset[ch]) {
1849 ch = this.charset[ch];
1850 }
1851
1852 row = this.y + this.ybase;
1853
1854 // insert combining char in last cell
1855 // FIXME: needs handling after cursor jumps
1856 if (!ch_width && this.x) {
1857
1858 // dont overflow left
1859 if (this.lines[row][this.x-1]) {
1860 if (!this.lines[row][this.x-1][2]) {
1861
1862 // found empty cell after fullwidth, need to go 2 cells back
1863 if (this.lines[row][this.x-2])
1864 this.lines[row][this.x-2][1] += ch;
1865
1866 } else {
1867 this.lines[row][this.x-1][1] += ch;
1868 }
1869 this.updateRange(this.y);
1870 }
1871 break;
1872 }
1873
1874 // goto next line if ch would overflow
1875 // TODO: needs a global min terminal width of 2
1876 if (this.x+ch_width-1 >= this.cols) {
1877 // autowrap - DECAWM
1878 if (this.wraparoundMode) {
1879 this.x = 0;
1880 this.y++;
1881 if (this.y > this.scrollBottom) {
1882 this.y--;
1883 this.scroll();
1884 }
1885 } else {
1886 this.x = this.cols-1;
1887 if(ch_width===2) // FIXME: check for xterm behavior
1888 continue;
1889 }
1890 }
1891 row = this.y + this.ybase;
1892
1893 // insert mode: move characters to right
1894 if (this.insertMode) {
1895 // do this twice for a fullwidth char
1896 for (var moves=0; moves<ch_width; ++moves) {
1897 // remove last cell, if it's width is 0
1898 // we have to adjust the second last cell as well
1899 var removed = this.lines[this.y + this.ybase].pop();
1900 if (removed[2]===0
1901 && this.lines[row][this.cols-2]
1902 && this.lines[row][this.cols-2][2]===2)
1903 this.lines[row][this.cols-2] = [this.curAttr, ' ', 1];
1904
1905 // insert empty cell at cursor
1906 this.lines[row].splice(this.x, 0, [this.curAttr, ' ', 1]);
1907 }
1908 }
1909
1910 this.lines[row][this.x] = [this.curAttr, ch, ch_width];
1911 this.x++;
1912 this.updateRange(this.y);
1913
1914 // fullwidth char - set next cell width to zero and advance cursor
1915 if (ch_width===2) {
1916 this.lines[row][this.x] = [this.curAttr, '', 0];
1917 this.x++;
1918 }
1919 }
1920 break;
1921 }
1922 break;
1923 case escaped:
1924 switch (ch) {
1925 // ESC [ Control Sequence Introducer ( CSI is 0x9b).
1926 case '[':
1927 this.params = [];
1928 this.currentParam = 0;
1929 this.state = csi;
1930 break;
1931
1932 // ESC ] Operating System Command ( OSC is 0x9d).
1933 case ']':
1934 this.params = [];
1935 this.currentParam = 0;
1936 this.state = osc;
1937 break;
1938
1939 // ESC P Device Control String ( DCS is 0x90).
1940 case 'P':
1941 this.params = [];
1942 this.currentParam = 0;
1943 this.state = dcs;
1944 break;
1945
1946 // ESC _ Application Program Command ( APC is 0x9f).
1947 case '_':
1948 this.state = ignore;
1949 break;
1950
1951 // ESC ^ Privacy Message ( PM is 0x9e).
1952 case '^':
1953 this.state = ignore;
1954 break;
1955
1956 // ESC c Full Reset (RIS).
1957 case 'c':
1958 this.reset();
1959 break;
1960
1961 // ESC E Next Line ( NEL is 0x85).
1962 // ESC D Index ( IND is 0x84).
1963 case 'E':
1964 this.x = 0;
1965 ;
1966 case 'D':
1967 this.index();
1968 break;
1969
1970 // ESC M Reverse Index ( RI is 0x8d).
1971 case 'M':
1972 this.reverseIndex();
1973 break;
1974
1975 // ESC % Select default/utf-8 character set.
1976 // @ = default, G = utf-8
1977 case '%':
1978 //this.charset = null;
1979 this.setgLevel(0);
1980 this.setgCharset(0, Terminal.charsets.US);
1981 this.state = normal;
1982 i++;
1983 break;
1984
1985 // ESC (,),*,+,-,. Designate G0-G2 Character Set.
1986 case '(': // <-- this seems to get all the attention
1987 case ')':
1988 case '*':
1989 case '+':
1990 case '-':
1991 case '.':
1992 switch (ch) {
1993 case '(':
1994 this.gcharset = 0;
1995 break;
1996 case ')':
1997 this.gcharset = 1;
1998 break;
1999 case '*':
2000 this.gcharset = 2;
2001 break;
2002 case '+':
2003 this.gcharset = 3;
2004 break;
2005 case '-':
2006 this.gcharset = 1;
2007 break;
2008 case '.':
2009 this.gcharset = 2;
2010 break;
2011 }
2012 this.state = charset;
2013 break;
2014
2015 // Designate G3 Character Set (VT300).
2016 // A = ISO Latin-1 Supplemental.
2017 // Not implemented.
2018 case '/':
2019 this.gcharset = 3;
2020 this.state = charset;
2021 i--;
2022 break;
2023
2024 // ESC N
2025 // Single Shift Select of G2 Character Set
2026 // ( SS2 is 0x8e). This affects next character only.
2027 case 'N':
2028 break;
2029 // ESC O
2030 // Single Shift Select of G3 Character Set
2031 // ( SS3 is 0x8f). This affects next character only.
2032 case 'O':
2033 break;
2034 // ESC n
2035 // Invoke the G2 Character Set as GL (LS2).
2036 case 'n':
2037 this.setgLevel(2);
2038 break;
2039 // ESC o
2040 // Invoke the G3 Character Set as GL (LS3).
2041 case 'o':
2042 this.setgLevel(3);
2043 break;
2044 // ESC |
2045 // Invoke the G3 Character Set as GR (LS3R).
2046 case '|':
2047 this.setgLevel(3);
2048 break;
2049 // ESC }
2050 // Invoke the G2 Character Set as GR (LS2R).
2051 case '}':
2052 this.setgLevel(2);
2053 break;
2054 // ESC ~
2055 // Invoke the G1 Character Set as GR (LS1R).
2056 case '~':
2057 this.setgLevel(1);
2058 break;
2059
2060 // ESC 7 Save Cursor (DECSC).
2061 case '7':
2062 this.saveCursor();
2063 this.state = normal;
2064 break;
2065
2066 // ESC 8 Restore Cursor (DECRC).
2067 case '8':
2068 this.restoreCursor();
2069 this.state = normal;
2070 break;
2071
2072 // ESC # 3 DEC line height/width
2073 case '#':
2074 this.state = normal;
2075 i++;
2076 break;
2077
2078 // ESC H Tab Set (HTS is 0x88).
2079 case 'H':
2080 this.tabSet();
2081 break;
2082
2083 // ESC = Application Keypad (DECKPAM).
2084 case '=':
2085 this.log('Serial port requested application keypad.');
2086 this.applicationKeypad = true;
2087 this.viewport.setApplicationMode(true);
2088 this.state = normal;
2089 break;
2090
2091 // ESC > Normal Keypad (DECKPNM).
2092 case '>':
2093 this.log('Switching back to normal keypad.');
2094 this.applicationKeypad = false;
2095 this.viewport.setApplicationMode(false);
2096 this.state = normal;
2097 break;
2098
2099 default:
2100 this.state = normal;
2101 this.error('Unknown ESC control: %s.', ch);
2102 break;
2103 }
2104 break;
2105
2106 case charset:
2107 switch (ch) {
2108 case '0': // DEC Special Character and Line Drawing Set.
2109 cs = Terminal.charsets.SCLD;
2110 break;
2111 case 'A': // UK
2112 cs = Terminal.charsets.UK;
2113 break;
2114 case 'B': // United States (USASCII).
2115 cs = Terminal.charsets.US;
2116 break;
2117 case '4': // Dutch
2118 cs = Terminal.charsets.Dutch;
2119 break;
2120 case 'C': // Finnish
2121 case '5':
2122 cs = Terminal.charsets.Finnish;
2123 break;
2124 case 'R': // French
2125 cs = Terminal.charsets.French;
2126 break;
2127 case 'Q': // FrenchCanadian
2128 cs = Terminal.charsets.FrenchCanadian;
2129 break;
2130 case 'K': // German
2131 cs = Terminal.charsets.German;
2132 break;
2133 case 'Y': // Italian
2134 cs = Terminal.charsets.Italian;
2135 break;
2136 case 'E': // NorwegianDanish
2137 case '6':
2138 cs = Terminal.charsets.NorwegianDanish;
2139 break;
2140 case 'Z': // Spanish
2141 cs = Terminal.charsets.Spanish;
2142 break;
2143 case 'H': // Swedish
2144 case '7':
2145 cs = Terminal.charsets.Swedish;
2146 break;
2147 case '=': // Swiss
2148 cs = Terminal.charsets.Swiss;
2149 break;
2150 case '/': // ISOLatin (actually /A)
2151 cs = Terminal.charsets.ISOLatin;
2152 i++;
2153 break;
2154 default: // Default
2155 cs = Terminal.charsets.US;
2156 break;
2157 }
2158 this.setgCharset(this.gcharset, cs);
2159 this.gcharset = null;
2160 this.state = normal;
2161 break;
2162
2163 case osc:
2164 // OSC Ps ; Pt ST
2165 // OSC Ps ; Pt BEL
2166 // Set Text Parameters.
2167 if (ch === '\x1b' || ch === '\x07') {
2168 if (ch === '\x1b') i++;
2169
2170 this.params.push(this.currentParam);
2171
2172 switch (this.params[0]) {
2173 case 0:
2174 case 1:
2175 case 2:
2176 if (this.params[1]) {
2177 this.title = this.params[1];
2178 this.handleTitle(this.title);
2179 }
2180 break;
2181 case 3:
2182 // set X property
2183 break;
2184 case 4:
2185 case 5:
2186 // change dynamic colors
2187 break;
2188 case 10:
2189 case 11:
2190 case 12:
2191 case 13:
2192 case 14:
2193 case 15:
2194 case 16:
2195 case 17:
2196 case 18:
2197 case 19:
2198 // change dynamic ui colors
2199 break;
2200 case 46:
2201 // change log file
2202 break;
2203 case 50:
2204 // dynamic font
2205 break;
2206 case 51:
2207 // emacs shell
2208 break;
2209 case 52:
2210 // manipulate selection data
2211 break;
2212 case 104:
2213 case 105:
2214 case 110:
2215 case 111:
2216 case 112:
2217 case 113:
2218 case 114:
2219 case 115:
2220 case 116:
2221 case 117:
2222 case 118:
2223 // reset colors
2224 break;
2225 }
2226
2227 this.params = [];
2228 this.currentParam = 0;
2229 this.state = normal;
2230 } else {
2231 if (!this.params.length) {
2232 if (ch >= '0' && ch <= '9') {
2233 this.currentParam =
2234 this.currentParam * 10 + ch.charCodeAt(0) - 48;
2235 } else if (ch === ';') {
2236 this.params.push(this.currentParam);
2237 this.currentParam = '';
2238 }
2239 } else {
2240 this.currentParam += ch;
2241 }
2242 }
2243 break;
2244
2245 case csi:
2246 // '?', '>', '!'
2247 if (ch === '?' || ch === '>' || ch === '!') {
2248 this.prefix = ch;
2249 break;
2250 }
2251
2252 // 0 - 9
2253 if (ch >= '0' && ch <= '9') {
2254 this.currentParam = this.currentParam * 10 + ch.charCodeAt(0) - 48;
2255 break;
2256 }
2257
2258 // '$', '"', ' ', '\''
2259 if (ch === '$' || ch === '"' || ch === ' ' || ch === '\'') {
2260 this.postfix = ch;
2261 break;
2262 }
2263
2264 this.params.push(this.currentParam);
2265 this.currentParam = 0;
2266
2267 // ';'
2268 if (ch === ';') break;
2269
2270 this.state = normal;
2271
2272 switch (ch) {
2273 // CSI Ps A
2274 // Cursor Up Ps Times (default = 1) (CUU).
2275 case 'A':
2276 this.cursorUp(this.params);
2277 break;
2278
2279 // CSI Ps B
2280 // Cursor Down Ps Times (default = 1) (CUD).
2281 case 'B':
2282 this.cursorDown(this.params);
2283 break;
2284
2285 // CSI Ps C
2286 // Cursor Forward Ps Times (default = 1) (CUF).
2287 case 'C':
2288 this.cursorForward(this.params);
2289 break;
2290
2291 // CSI Ps D
2292 // Cursor Backward Ps Times (default = 1) (CUB).
2293 case 'D':
2294 this.cursorBackward(this.params);
2295 break;
2296
2297 // CSI Ps ; Ps H
2298 // Cursor Position [row;column] (default = [1,1]) (CUP).
2299 case 'H':
2300 this.cursorPos(this.params);
2301 break;
2302
2303 // CSI Ps J Erase in Display (ED).
2304 case 'J':
2305 this.eraseInDisplay(this.params);
2306 break;
2307
2308 // CSI Ps K Erase in Line (EL).
2309 case 'K':
2310 this.eraseInLine(this.params);
2311 break;
2312
2313 // CSI Pm m Character Attributes (SGR).
2314 case 'm':
2315 if (!this.prefix) {
2316 this.charAttributes(this.params);
2317 }
2318 break;
2319
2320 // CSI Ps n Device Status Report (DSR).
2321 case 'n':
2322 if (!this.prefix) {
2323 this.deviceStatus(this.params);
2324 }
2325 break;
2326
2327 /**
2328 * Additions
2329 */
2330
2331 // CSI Ps @
2332 // Insert Ps (Blank) Character(s) (default = 1) (ICH).
2333 case '@':
2334 this.insertChars(this.params);
2335 break;
2336
2337 // CSI Ps E
2338 // Cursor Next Line Ps Times (default = 1) (CNL).
2339 case 'E':
2340 this.cursorNextLine(this.params);
2341 break;
2342
2343 // CSI Ps F
2344 // Cursor Preceding Line Ps Times (default = 1) (CNL).
2345 case 'F':
2346 this.cursorPrecedingLine(this.params);
2347 break;
2348
2349 // CSI Ps G
2350 // Cursor Character Absolute [column] (default = [row,1]) (CHA).
2351 case 'G':
2352 this.cursorCharAbsolute(this.params);
2353 break;
2354
2355 // CSI Ps L
2356 // Insert Ps Line(s) (default = 1) (IL).
2357 case 'L':
2358 this.insertLines(this.params);
2359 break;
2360
2361 // CSI Ps M
2362 // Delete Ps Line(s) (default = 1) (DL).
2363 case 'M':
2364 this.deleteLines(this.params);
2365 break;
2366
2367 // CSI Ps P
2368 // Delete Ps Character(s) (default = 1) (DCH).
2369 case 'P':
2370 this.deleteChars(this.params);
2371 break;
2372
2373 // CSI Ps X
2374 // Erase Ps Character(s) (default = 1) (ECH).
2375 case 'X':
2376 this.eraseChars(this.params);
2377 break;
2378
2379 // CSI Pm ` Character Position Absolute
2380 // [column] (default = [row,1]) (HPA).
2381 case '`':
2382 this.charPosAbsolute(this.params);
2383 break;
2384
2385 // 141 61 a * HPR -
2386 // Horizontal Position Relative
2387 case 'a':
2388 this.HPositionRelative(this.params);
2389 break;
2390
2391 // CSI P s c
2392 // Send Device Attributes (Primary DA).
2393 // CSI > P s c
2394 // Send Device Attributes (Secondary DA)
2395 case 'c':
2396 this.sendDeviceAttributes(this.params);
2397 break;
2398
2399 // CSI Pm d
2400 // Line Position Absolute [row] (default = [1,column]) (VPA).
2401 case 'd':
2402 this.linePosAbsolute(this.params);
2403 break;
2404
2405 // 145 65 e * VPR - Vertical Position Relative
2406 case 'e':
2407 this.VPositionRelative(this.params);
2408 break;
2409
2410 // CSI Ps ; Ps f
2411 // Horizontal and Vertical Position [row;column] (default =
2412 // [1,1]) (HVP).
2413 case 'f':
2414 this.HVPosition(this.params);
2415 break;
2416
2417 // CSI Pm h Set Mode (SM).
2418 // CSI ? Pm h - mouse escape codes, cursor escape codes
2419 case 'h':
2420 this.setMode(this.params);
2421 break;
2422
2423 // CSI Pm l Reset Mode (RM).
2424 // CSI ? Pm l
2425 case 'l':
2426 this.resetMode(this.params);
2427 break;
2428
2429 // CSI Ps ; Ps r
2430 // Set Scrolling Region [top;bottom] (default = full size of win-
2431 // dow) (DECSTBM).
2432 // CSI ? Pm r
2433 case 'r':
2434 this.setScrollRegion(this.params);
2435 break;
2436
2437 // CSI s
2438 // Save cursor (ANSI.SYS).
2439 case 's':
2440 this.saveCursor(this.params);
2441 break;
2442
2443 // CSI u
2444 // Restore cursor (ANSI.SYS).
2445 case 'u':
2446 this.restoreCursor(this.params);
2447 break;
2448
2449 /**
2450 * Lesser Used
2451 */
2452
2453 // CSI Ps I
2454 // Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
2455 case 'I':
2456 this.cursorForwardTab(this.params);
2457 break;
2458
2459 // CSI Ps S Scroll up Ps lines (default = 1) (SU).
2460 case 'S':
2461 this.scrollUp(this.params);
2462 break;
2463
2464 // CSI Ps T Scroll down Ps lines (default = 1) (SD).
2465 // CSI Ps ; Ps ; Ps ; Ps ; Ps T
2466 // CSI > Ps; Ps T
2467 case 'T':
2468 // if (this.prefix === '>') {
2469 // this.resetTitleModes(this.params);
2470 // break;
2471 // }
2472 // if (this.params.length > 2) {
2473 // this.initMouseTracking(this.params);
2474 // break;
2475 // }
2476 if (this.params.length < 2 && !this.prefix) {
2477 this.scrollDown(this.params);
2478 }
2479 break;
2480
2481 // CSI Ps Z
2482 // Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
2483 case 'Z':
2484 this.cursorBackwardTab(this.params);
2485 break;
2486
2487 // CSI Ps b Repeat the preceding graphic character Ps times (REP).
2488 case 'b':
2489 this.repeatPrecedingCharacter(this.params);
2490 break;
2491
2492 // CSI Ps g Tab Clear (TBC).
2493 case 'g':
2494 this.tabClear(this.params);
2495 break;
2496
2497 // CSI Pm i Media Copy (MC).
2498 // CSI ? Pm i
2499 // case 'i':
2500 // this.mediaCopy(this.params);
2501 // break;
2502
2503 // CSI Pm m Character Attributes (SGR).
2504 // CSI > Ps; Ps m
2505 // case 'm': // duplicate
2506 // if (this.prefix === '>') {
2507 // this.setResources(this.params);
2508 // } else {
2509 // this.charAttributes(this.params);
2510 // }
2511 // break;
2512
2513 // CSI Ps n Device Status Report (DSR).
2514 // CSI > Ps n
2515 // case 'n': // duplicate
2516 // if (this.prefix === '>') {
2517 // this.disableModifiers(this.params);
2518 // } else {
2519 // this.deviceStatus(this.params);
2520 // }
2521 // break;
2522
2523 // CSI > Ps p Set pointer mode.
2524 // CSI ! p Soft terminal reset (DECSTR).
2525 // CSI Ps$ p
2526 // Request ANSI mode (DECRQM).
2527 // CSI ? Ps$ p
2528 // Request DEC private mode (DECRQM).
2529 // CSI Ps ; Ps " p
2530 case 'p':
2531 switch (this.prefix) {
2532 // case '>':
2533 // this.setPointerMode(this.params);
2534 // break;
2535 case '!':
2536 this.softReset(this.params);
2537 break;
2538 // case '?':
2539 // if (this.postfix === '$') {
2540 // this.requestPrivateMode(this.params);
2541 // }
2542 // break;
2543 // default:
2544 // if (this.postfix === '"') {
2545 // this.setConformanceLevel(this.params);
2546 // } else if (this.postfix === '$') {
2547 // this.requestAnsiMode(this.params);
2548 // }
2549 // break;
2550 }
2551 break;
2552
2553 // CSI Ps q Load LEDs (DECLL).
2554 // CSI Ps SP q
2555 // CSI Ps " q
2556 // case 'q':
2557 // if (this.postfix === ' ') {
2558 // this.setCursorStyle(this.params);
2559 // break;
2560 // }
2561 // if (this.postfix === '"') {
2562 // this.setCharProtectionAttr(this.params);
2563 // break;
2564 // }
2565 // this.loadLEDs(this.params);
2566 // break;
2567
2568 // CSI Ps ; Ps r
2569 // Set Scrolling Region [top;bottom] (default = full size of win-
2570 // dow) (DECSTBM).
2571 // CSI ? Pm r
2572 // CSI Pt; Pl; Pb; Pr; Ps$ r
2573 // case 'r': // duplicate
2574 // if (this.prefix === '?') {
2575 // this.restorePrivateValues(this.params);
2576 // } else if (this.postfix === '$') {
2577 // this.setAttrInRectangle(this.params);
2578 // } else {
2579 // this.setScrollRegion(this.params);
2580 // }
2581 // break;
2582
2583 // CSI s Save cursor (ANSI.SYS).
2584 // CSI ? Pm s
2585 // case 's': // duplicate
2586 // if (this.prefix === '?') {
2587 // this.savePrivateValues(this.params);
2588 // } else {
2589 // this.saveCursor(this.params);
2590 // }
2591 // break;
2592
2593 // CSI Ps ; Ps ; Ps t
2594 // CSI Pt; Pl; Pb; Pr; Ps$ t
2595 // CSI > Ps; Ps t
2596 // CSI Ps SP t
2597 // case 't':
2598 // if (this.postfix === '$') {
2599 // this.reverseAttrInRectangle(this.params);
2600 // } else if (this.postfix === ' ') {
2601 // this.setWarningBellVolume(this.params);
2602 // } else {
2603 // if (this.prefix === '>') {
2604 // this.setTitleModeFeature(this.params);
2605 // } else {
2606 // this.manipulateWindow(this.params);
2607 // }
2608 // }
2609 // break;
2610
2611 // CSI u Restore cursor (ANSI.SYS).
2612 // CSI Ps SP u
2613 // case 'u': // duplicate
2614 // if (this.postfix === ' ') {
2615 // this.setMarginBellVolume(this.params);
2616 // } else {
2617 // this.restoreCursor(this.params);
2618 // }
2619 // break;
2620
2621 // CSI Pt; Pl; Pb; Pr; Pp; Pt; Pl; Pp$ v
2622 // case 'v':
2623 // if (this.postfix === '$') {
2624 // this.copyRectagle(this.params);
2625 // }
2626 // break;
2627
2628 // CSI Pt ; Pl ; Pb ; Pr ' w
2629 // case 'w':
2630 // if (this.postfix === '\'') {
2631 // this.enableFilterRectangle(this.params);
2632 // }
2633 // break;
2634
2635 // CSI Ps x Request Terminal Parameters (DECREQTPARM).
2636 // CSI Ps x Select Attribute Change Extent (DECSACE).
2637 // CSI Pc; Pt; Pl; Pb; Pr$ x
2638 // case 'x':
2639 // if (this.postfix === '$') {
2640 // this.fillRectangle(this.params);
2641 // } else {
2642 // this.requestParameters(this.params);
2643 // //this.__(this.params);
2644 // }
2645 // break;
2646
2647 // CSI Ps ; Pu ' z
2648 // CSI Pt; Pl; Pb; Pr$ z
2649 // case 'z':
2650 // if (this.postfix === '\'') {
2651 // this.enableLocatorReporting(this.params);
2652 // } else if (this.postfix === '$') {
2653 // this.eraseRectangle(this.params);
2654 // }
2655 // break;
2656
2657 // CSI Pm ' {
2658 // CSI Pt; Pl; Pb; Pr$ {
2659 // case '{':
2660 // if (this.postfix === '\'') {
2661 // this.setLocatorEvents(this.params);
2662 // } else if (this.postfix === '$') {
2663 // this.selectiveEraseRectangle(this.params);
2664 // }
2665 // break;
2666
2667 // CSI Ps ' |
2668 // case '|':
2669 // if (this.postfix === '\'') {
2670 // this.requestLocatorPosition(this.params);
2671 // }
2672 // break;
2673
2674 // CSI P m SP }
2675 // Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
2676 // case '}':
2677 // if (this.postfix === ' ') {
2678 // this.insertColumns(this.params);
2679 // }
2680 // break;
2681
2682 // CSI P m SP ~
2683 // Delete P s Column(s) (default = 1) (DECDC), VT420 and up
2684 // case '~':
2685 // if (this.postfix === ' ') {
2686 // this.deleteColumns(this.params);
2687 // }
2688 // break;
2689
2690 default:
2691 this.error('Unknown CSI code: %s.', ch);
2692 break;
2693 }
2694
2695 this.prefix = '';
2696 this.postfix = '';
2697 break;
2698
2699 case dcs:
2700 if (ch === '\x1b' || ch === '\x07') {
2701 if (ch === '\x1b') i++;
2702
2703 switch (this.prefix) {
2704 // User-Defined Keys (DECUDK).
2705 case '':
2706 break;
2707
2708 // Request Status String (DECRQSS).
2709 // test: echo -e '\eP$q"p\e\\'
2710 case '$q':
2711 var pt = this.currentParam
2712 , valid = false;
2713
2714 switch (pt) {
2715 // DECSCA
2716 case '"q':
2717 pt = '0"q';
2718 break;
2719
2720 // DECSCL
2721 case '"p':
2722 pt = '61"p';
2723 break;
2724
2725 // DECSTBM
2726 case 'r':
2727 pt = ''
2728 + (this.scrollTop + 1)
2729 + ';'
2730 + (this.scrollBottom + 1)
2731 + 'r';
2732 break;
2733
2734 // SGR
2735 case 'm':
2736 pt = '0m';
2737 break;
2738
2739 default:
2740 this.error('Unknown DCS Pt: %s.', pt);
2741 pt = '';
2742 break;
2743 }
2744
2745 this.send('\x1bP' + +valid + '$r' + pt + '\x1b\\');
2746 break;
2747
2748 // Set Termcap/Terminfo Data (xterm, experimental).
2749 case '+p':
2750 break;
2751
2752 // Request Termcap/Terminfo String (xterm, experimental)
2753 // Regular xterm does not even respond to this sequence.
2754 // This can cause a small glitch in vim.
2755 // test: echo -ne '\eP+q6b64\e\\'
2756 case '+q':
2757 var pt = this.currentParam
2758 , valid = false;
2759
2760 this.send('\x1bP' + +valid + '+r' + pt + '\x1b\\');
2761 break;
2762
2763 default:
2764 this.error('Unknown DCS prefix: %s.', this.prefix);
2765 break;
2766 }
2767
2768 this.currentParam = 0;
2769 this.prefix = '';
2770 this.state = normal;
2771 } else if (!this.currentParam) {
2772 if (!this.prefix && ch !== '$' && ch !== '+') {
2773 this.currentParam = ch;
2774 } else if (this.prefix.length === 2) {
2775 this.currentParam = ch;
2776 } else {
2777 this.prefix += ch;
2778 }
2779 } else {
2780 this.currentParam += ch;
2781 }
2782 break;
2783
2784 case ignore:
2785 // For PM and APC.
2786 if (ch === '\x1b' || ch === '\x07') {
2787 if (ch === '\x1b') i++;
2788 this.state = normal;
2789 }
2790 break;
2791 }
2792 }
2793
2794 this.updateRange(this.y);
2795 this.refresh(this.refreshStart, this.refreshEnd);
2796 };
2797
2798 /**
2799 * Writes text to the terminal, followed by a break line character (\n).
2800 * @param {string} text The text to write to the terminal.
2801 */
2802 Terminal.prototype.writeln = function(data) {
2803 this.write(data + '\r\n');
2804 };
2805
2806 /**
2807 * Attaches a custom keydown handler which is run before keys are processed, giving consumers of
2808 * xterm.js ultimate control as to what keys should be processed by the terminal and what keys
2809 * should not.
2810 * @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
2811 * function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
2812 * the default action. The function returns whether the event should be processed by xterm.js.
2813 */
2814 Terminal.prototype.attachCustomKeydownHandler = function(customKeydownHandler) {
2815 this.customKeydownHandler = customKeydownHandler;
2816 }
2817
2818 /**
2819 * Handle a keydown event
2820 * Key Resources:
2821 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
2822 * @param {KeyboardEvent} ev The keydown event to be handled.
2823 */
2824 Terminal.prototype.keyDown = function(ev) {
2825 if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
2826 return false;
2827 }
2828
2829 if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
2830 return false;
2831 }
2832
2833 var self = this;
2834 var result = this.evaluateKeyEscapeSequence(ev);
2835
2836 if (result.scrollDisp) {
2837 this.scrollDisp(result.scrollDisp);
2838 return this.cancel(ev);
2839 }
2840
2841 if (isThirdLevelShift(this, ev)) {
2842 return true;
2843 }
2844
2845 if (result.cancel ) {
2846 // The event is canceled at the end already, is this necessary?
2847 this.cancel(ev, true);
2848 }
2849
2850 if (!result.key) {
2851 return true;
2852 }
2853
2854 this.emit('keydown', ev);
2855 this.emit('key', result.key, ev);
2856 this.showCursor();
2857 this.handler(result.key);
2858
2859 return this.cancel(ev, true);
2860 };
2861
2862 /**
2863 * Returns an object that determines how a KeyboardEvent should be handled. The key of the
2864 * returned value is the new key code to pass to the PTY.
2865 *
2866 * Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
2867 * @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
2868 */
2869 Terminal.prototype.evaluateKeyEscapeSequence = function(ev) {
2870 var result = {
2871 // Whether to cancel event propogation (NOTE: this may not be needed since the event is
2872 // canceled at the end of keyDown
2873 cancel: false,
2874 // The new key even to emit
2875 key: undefined,
2876 // The number of characters to scroll, if this is defined it will cancel the event
2877 scrollDisp: undefined
2878 };
2879 var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
2880 switch (ev.keyCode) {
2881 // backspace
2882 case 8:
2883 if (ev.shiftKey) {
2884 result.key = '\x08'; // ^H
2885 break;
2886 }
2887 result.key = '\x7f'; // ^?
2888 break;
2889 // tab
2890 case 9:
2891 if (ev.shiftKey) {
2892 result.key = '\x1b[Z';
2893 break;
2894 }
2895 result.key = '\t';
2896 result.cancel = true;
2897 break;
2898 // return/enter
2899 case 13:
2900 result.key = '\r';
2901 result.cancel = true;
2902 break;
2903 // escape
2904 case 27:
2905 result.key = '\x1b';
2906 result.cancel = true;
2907 break;
2908 // left-arrow
2909 case 37:
2910 if (modifiers)
2911 result.key = '\x1b[1;' + (modifiers + 1) + 'D';
2912 else if (this.applicationCursor)
2913 result.key = '\x1bOD';
2914 else
2915 result.key = '\x1b[D';
2916 break;
2917 // right-arrow
2918 case 39:
2919 if (modifiers)
2920 result.key = '\x1b[1;' + (modifiers + 1) + 'C';
2921 else if (this.applicationCursor)
2922 result.key = '\x1bOC';
2923 else
2924 result.key = '\x1b[C';
2925 break;
2926 // up-arrow
2927 case 38:
2928 if (modifiers)
2929 result.key = '\x1b[1;' + (modifiers + 1) + 'A';
2930 else if (this.applicationCursor)
2931 result.key = '\x1bOA';
2932 else
2933 result.key = '\x1b[A';
2934 break;
2935 // down-arrow
2936 case 40:
2937 if (modifiers)
2938 result.key = '\x1b[1;' + (modifiers + 1) + 'B';
2939 else if (this.applicationCursor)
2940 result.key = '\x1bOB';
2941 else
2942 result.key = '\x1b[B';
2943 break;
2944 // insert
2945 case 45:
2946 if (!ev.shiftKey && !ev.ctrlKey) {
2947 // <Ctrl> or <Shift> + <Insert> are used to
2948 // copy-paste on some systems.
2949 result.key = '\x1b[2~';
2950 }
2951 break;
2952 // delete
2953 case 46: result.key = '\x1b[3~'; break;
2954 // home
2955 case 36:
2956 if (modifiers)
2957 result.key = '\x1b[1;' + (modifiers + 1) + 'H';
2958 else if (this.applicationCursor)
2959 result.key = '\x1bOH';
2960 else
2961 result.key = '\x1b[H';
2962 break;
2963 // end
2964 case 35:
2965 if (modifiers)
2966 result.key = '\x1b[1;' + (modifiers + 1) + 'F';
2967 else if (this.applicationCursor)
2968 result.key = '\x1bOF';
2969 else
2970 result.key = '\x1b[F';
2971 break;
2972 // page up
2973 case 33:
2974 if (ev.shiftKey) {
2975 result.scrollDisp = -(this.rows - 1);
2976 } else {
2977 result.key = '\x1b[5~';
2978 }
2979 break;
2980 // page down
2981 case 34:
2982 if (ev.shiftKey) {
2983 result.scrollDisp = this.rows - 1;
2984 } else {
2985 result.key = '\x1b[6~';
2986 }
2987 break;
2988 // F1-F12
2989 case 112: result.key = '\x1bOP'; break;
2990 case 113: result.key = '\x1bOQ'; break;
2991 case 114: result.key = '\x1bOR'; break;
2992 case 115: result.key = '\x1bOS'; break;
2993 case 116: result.key = '\x1b[15~'; break;
2994 case 117: result.key = '\x1b[17~'; break;
2995 case 118: result.key = '\x1b[18~'; break;
2996 case 119: result.key = '\x1b[19~'; break;
2997 case 120: result.key = '\x1b[20~'; break;
2998 case 121: result.key = '\x1b[21~'; break;
2999 case 122: result.key = '\x1b[23~'; break;
3000 case 123: result.key = '\x1b[24~'; break;
3001 default:
3002 // a-z and space
3003 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
3004 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3005 result.key = String.fromCharCode(ev.keyCode - 64);
3006 } else if (ev.keyCode === 32) {
3007 // NUL
3008 result.key = String.fromCharCode(0);
3009 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
3010 // escape, file sep, group sep, record sep, unit sep
3011 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
3012 } else if (ev.keyCode === 56) {
3013 // delete
3014 result.key = String.fromCharCode(127);
3015 } else if (ev.keyCode === 219) {
3016 // ^[ - escape
3017 result.key = String.fromCharCode(27);
3018 } else if (ev.keyCode === 221) {
3019 // ^] - group sep
3020 result.key = String.fromCharCode(29);
3021 }
3022 } else if (!this.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
3023 // On Mac this is a third level shift. Use <Esc> instead.
3024 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3025 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
3026 } else if (ev.keyCode === 192) {
3027 result.key = '\x1b`';
3028 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
3029 result.key = '\x1b' + (ev.keyCode - 48);
3030 }
3031 }
3032 break;
3033 }
3034 return result;
3035 };
3036
3037 /**
3038 * Set the G level of the terminal
3039 * @param g
3040 */
3041 Terminal.prototype.setgLevel = function(g) {
3042 this.glevel = g;
3043 this.charset = this.charsets[g];
3044 };
3045
3046 /**
3047 * Set the charset for the given G level of the terminal
3048 * @param g
3049 * @param charset
3050 */
3051 Terminal.prototype.setgCharset = function(g, charset) {
3052 this.charsets[g] = charset;
3053 if (this.glevel === g) {
3054 this.charset = charset;
3055 }
3056 };
3057
3058 /**
3059 * Handle a keypress event.
3060 * Key Resources:
3061 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
3062 * @param {KeyboardEvent} ev The keypress event to be handled.
3063 */
3064 Terminal.prototype.keyPress = function(ev) {
3065 var key;
3066
3067 this.cancel(ev);
3068
3069 if (ev.charCode) {
3070 key = ev.charCode;
3071 } else if (ev.which == null) {
3072 key = ev.keyCode;
3073 } else if (ev.which !== 0 && ev.charCode !== 0) {
3074 key = ev.which;
3075 } else {
3076 return false;
3077 }
3078
3079 if (!key || (
3080 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
3081 )) {
3082 return false;
3083 }
3084
3085 key = String.fromCharCode(key);
3086
3087 this.emit('keypress', key, ev);
3088 this.emit('key', key, ev);
3089 this.showCursor();
3090 this.handler(key);
3091
3092 return false;
3093 };
3094
3095 /**
3096 * Send data for handling to the terminal
3097 * @param {string} data
3098 */
3099 Terminal.prototype.send = function(data) {
3100 var self = this;
3101
3102 if (!this.queue) {
3103 setTimeout(function() {
3104 self.handler(self.queue);
3105 self.queue = '';
3106 }, 1);
3107 }
3108
3109 this.queue += data;
3110 };
3111
3112 /**
3113 * Ring the bell.
3114 * Note: We could do sweet things with webaudio here
3115 */
3116 Terminal.prototype.bell = function() {
3117 if (!this.visualBell) return;
3118 var self = this;
3119 this.element.style.borderColor = 'white';
3120 setTimeout(function() {
3121 self.element.style.borderColor = '';
3122 }, 10);
3123 if (this.popOnBell) this.focus();
3124 };
3125
3126 /**
3127 * Log the current state to the console.
3128 */
3129 Terminal.prototype.log = function() {
3130 if (!this.debug) return;
3131 if (!this.context.console || !this.context.console.log) return;
3132 var args = Array.prototype.slice.call(arguments);
3133 this.context.console.log.apply(this.context.console, args);
3134 };
3135
3136 /**
3137 * Log the current state as error to the console.
3138 */
3139 Terminal.prototype.error = function() {
3140 if (!this.debug) return;
3141 if (!this.context.console || !this.context.console.error) return;
3142 var args = Array.prototype.slice.call(arguments);
3143 this.context.console.error.apply(this.context.console, args);
3144 };
3145
3146 /**
3147 * Resizes the terminal.
3148 *
3149 * @param {number} x The number of columns to resize to.
3150 * @param {number} y The number of rows to resize to.
3151 */
3152 Terminal.prototype.resize = function(x, y) {
3153 var line
3154 , el
3155 , i
3156 , j
3157 , ch
3158 , addToY;
3159
3160 if (x === this.cols && y === this.rows) {
3161 return;
3162 }
3163
3164 if (x < 1) x = 1;
3165 if (y < 1) y = 1;
3166
3167 // resize cols
3168 j = this.cols;
3169 if (j < x) {
3170 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
3171 i = this.lines.length;
3172 while (i--) {
3173 while (this.lines[i].length < x) {
3174 this.lines[i].push(ch);
3175 }
3176 }
3177 } else { // (j > x)
3178 i = this.lines.length;
3179 while (i--) {
3180 while (this.lines[i].length > x) {
3181 this.lines[i].pop();
3182 }
3183 }
3184 }
3185 this.setupStops(j);
3186 this.cols = x;
3187
3188 // resize rows
3189 j = this.rows;
3190 addToY = 0;
3191 if (j < y) {
3192 el = this.element;
3193 while (j++ < y) {
3194 // y is rows, not this.y
3195 if (this.lines.length < y + this.ybase) {
3196 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
3197 // There is room above the buffer and there are no empty elements below the line,
3198 // scroll up
3199 this.ybase--;
3200 addToY++
3201 if (this.ydisp > 0) {
3202 // Viewport is at the top of the buffer, must increase downwards
3203 this.ydisp--;
3204 }
3205 } else {
3206 // Add a blank line if there is no buffer left at the top to scroll to, or if there
3207 // are blank lines after the cursor
3208 this.lines.push(this.blankLine());
3209 }
3210 }
3211 if (this.children.length < y) {
3212 this.insertRow();
3213 }
3214 }
3215 } else { // (j > y)
3216 while (j-- > y) {
3217 if (this.lines.length > y + this.ybase) {
3218 if (this.lines.length > this.ybase + this.y + 1) {
3219 // The line is a blank line below the cursor, remove it
3220 this.lines.pop();
3221 } else {
3222 // The line is the cursor, scroll down
3223 this.ybase++;
3224 this.ydisp++;
3225 }
3226 }
3227 if (this.children.length > y) {
3228 el = this.children.shift();
3229 if (!el) continue;
3230 el.parentNode.removeChild(el);
3231 }
3232 }
3233 }
3234 this.rows = y;
3235
3236 /*
3237 * Make sure that the cursor stays on screen
3238 */
3239 if (this.y >= y) {
3240 this.y = y - 1;
3241 }
3242 if (addToY) {
3243 this.y += addToY;
3244 }
3245
3246 if (this.x >= x) {
3247 this.x = x - 1;
3248 }
3249
3250 this.scrollTop = 0;
3251 this.scrollBottom = y - 1;
3252
3253 this.refresh(0, this.rows - 1);
3254
3255 this.normal = null;
3256
3257 this.emit('resize', {terminal: this, cols: x, rows: y});
3258 };
3259
3260 /**
3261 * Updates the range of rows to refresh
3262 * @param {number} y The number of rows to refresh next.
3263 */
3264 Terminal.prototype.updateRange = function(y) {
3265 if (y < this.refreshStart) this.refreshStart = y;
3266 if (y > this.refreshEnd) this.refreshEnd = y;
3267 // if (y > this.refreshEnd) {
3268 // this.refreshEnd = y;
3269 // if (y > this.rows - 1) {
3270 // this.refreshEnd = this.rows - 1;
3271 // }
3272 // }
3273 };
3274
3275 /**
3276 * Set the range of refreshing to the maximyum value
3277 */
3278 Terminal.prototype.maxRange = function() {
3279 this.refreshStart = 0;
3280 this.refreshEnd = this.rows - 1;
3281 };
3282
3283
3284
3285 /**
3286 * Setup the tab stops.
3287 * @param {number} i
3288 */
3289 Terminal.prototype.setupStops = function(i) {
3290 if (i != null) {
3291 if (!this.tabs[i]) {
3292 i = this.prevStop(i);
3293 }
3294 } else {
3295 this.tabs = {};
3296 i = 0;
3297 }
3298
3299 for (; i < this.cols; i += 8) {
3300 this.tabs[i] = true;
3301 }
3302 };
3303
3304
3305 /**
3306 * Move the cursor to the previous tab stop from the given position (default is current).
3307 * @param {number} x The position to move the cursor to the previous tab stop.
3308 */
3309 Terminal.prototype.prevStop = function(x) {
3310 if (x == null) x = this.x;
3311 while (!this.tabs[--x] && x > 0);
3312 return x >= this.cols
3313 ? this.cols - 1
3314 : x < 0 ? 0 : x;
3315 };
3316
3317
3318 /**
3319 * Move the cursor one tab stop forward from the given position (default is current).
3320 * @param {number} x The position to move the cursor one tab stop forward.
3321 */
3322 Terminal.prototype.nextStop = function(x) {
3323 if (x == null) x = this.x;
3324 while (!this.tabs[++x] && x < this.cols);
3325 return x >= this.cols
3326 ? this.cols - 1
3327 : x < 0 ? 0 : x;
3328 };
3329
3330
3331 /**
3332 * Erase in the identified line everything from "x" to the end of the line (right).
3333 * @param {number} x The column from which to start erasing to the end of the line.
3334 * @param {number} y The line in which to operate.
3335 */
3336 Terminal.prototype.eraseRight = function(x, y) {
3337 var line = this.lines[this.ybase + y]
3338 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3339
3340
3341 for (; x < this.cols; x++) {
3342 line[x] = ch;
3343 }
3344
3345 this.updateRange(y);
3346 };
3347
3348
3349
3350 /**
3351 * Erase in the identified line everything from "x" to the start of the line (left).
3352 * @param {number} x The column from which to start erasing to the start of the line.
3353 * @param {number} y The line in which to operate.
3354 */
3355 Terminal.prototype.eraseLeft = function(x, y) {
3356 var line = this.lines[this.ybase + y]
3357 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3358
3359 x++;
3360 while (x--) line[x] = ch;
3361
3362 this.updateRange(y);
3363 };
3364
3365
3366 /**
3367 * Erase all content in the given line
3368 * @param {number} y The line to erase all of its contents.
3369 */
3370 Terminal.prototype.eraseLine = function(y) {
3371 this.eraseRight(0, y);
3372 };
3373
3374
3375 /**
3376 * Return the data array of a blank line/
3377 * @param {number} cur First bunch of data for each "blank" character.
3378 */
3379 Terminal.prototype.blankLine = function(cur) {
3380 var attr = cur
3381 ? this.eraseAttr()
3382 : this.defAttr;
3383
3384 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
3385 , line = []
3386 , i = 0;
3387
3388 for (; i < this.cols; i++) {
3389 line[i] = ch;
3390 }
3391
3392 return line;
3393 };
3394
3395
3396 /**
3397 * If cur return the back color xterm feature attribute. Else return defAttr.
3398 * @param {object} cur
3399 */
3400 Terminal.prototype.ch = function(cur) {
3401 return cur
3402 ? [this.eraseAttr(), ' ', 1]
3403 : [this.defAttr, ' ', 1];
3404 };
3405
3406
3407 /**
3408 * Evaluate if the current erminal is the given argument.
3409 * @param {object} term The terminal to evaluate
3410 */
3411 Terminal.prototype.is = function(term) {
3412 var name = this.termName;
3413 return (name + '').indexOf(term) === 0;
3414 };
3415
3416
3417 /**
3418 * Emit the 'data' event and populate the given data.
3419 * @param {string} data The data to populate in the event.
3420 */
3421 Terminal.prototype.handler = function(data) {
3422 this.emit('data', data);
3423 };
3424
3425
3426 /**
3427 * Emit the 'title' event and populate the given title.
3428 * @param {string} title The title to populate in the event.
3429 */
3430 Terminal.prototype.handleTitle = function(title) {
3431 this.emit('title', title);
3432 };
3433
3434
3435 /**
3436 * ESC
3437 */
3438
3439 /**
3440 * ESC D Index (IND is 0x84).
3441 */
3442 Terminal.prototype.index = function() {
3443 this.y++;
3444 if (this.y > this.scrollBottom) {
3445 this.y--;
3446 this.scroll();
3447 }
3448 this.state = normal;
3449 };
3450
3451
3452 /**
3453 * ESC M Reverse Index (RI is 0x8d).
3454 */
3455 Terminal.prototype.reverseIndex = function() {
3456 var j;
3457 this.y--;
3458 if (this.y < this.scrollTop) {
3459 this.y++;
3460 // possibly move the code below to term.reverseScroll();
3461 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
3462 // blankLine(true) is xterm/linux behavior
3463 this.lines.splice(this.y + this.ybase, 0, this.blankLine(true));
3464 j = this.rows - 1 - this.scrollBottom;
3465 this.lines.splice(this.rows - 1 + this.ybase - j + 1, 1);
3466 // this.maxRange();
3467 this.updateRange(this.scrollTop);
3468 this.updateRange(this.scrollBottom);
3469 }
3470 this.state = normal;
3471 };
3472
3473
3474 /**
3475 * ESC c Full Reset (RIS).
3476 */
3477 Terminal.prototype.reset = function() {
3478 this.options.rows = this.rows;
3479 this.options.cols = this.cols;
3480 var customKeydownHandler = this.customKeydownHandler;
3481 Terminal.call(this, this.options);
3482 this.customKeydownHandler = customKeydownHandler;
3483 this.refresh(0, this.rows - 1);
3484 };
3485
3486
3487 /**
3488 * ESC H Tab Set (HTS is 0x88).
3489 */
3490 Terminal.prototype.tabSet = function() {
3491 this.tabs[this.x] = true;
3492 this.state = normal;
3493 };
3494
3495
3496 /**
3497 * CSI
3498 */
3499
3500 /**
3501 * CSI Ps A
3502 * Cursor Up Ps Times (default = 1) (CUU).
3503 */
3504 Terminal.prototype.cursorUp = function(params) {
3505 var param = params[0];
3506 if (param < 1) param = 1;
3507 this.y -= param;
3508 if (this.y < 0) this.y = 0;
3509 };
3510
3511
3512 /**
3513 * CSI Ps B
3514 * Cursor Down Ps Times (default = 1) (CUD).
3515 */
3516 Terminal.prototype.cursorDown = function(params) {
3517 var param = params[0];
3518 if (param < 1) param = 1;
3519 this.y += param;
3520 if (this.y >= this.rows) {
3521 this.y = this.rows - 1;
3522 }
3523 };
3524
3525
3526 /**
3527 * CSI Ps C
3528 * Cursor Forward Ps Times (default = 1) (CUF).
3529 */
3530 Terminal.prototype.cursorForward = function(params) {
3531 var param = params[0];
3532 if (param < 1) param = 1;
3533 this.x += param;
3534 if (this.x >= this.cols) {
3535 this.x = this.cols - 1;
3536 }
3537 };
3538
3539
3540 /**
3541 * CSI Ps D
3542 * Cursor Backward Ps Times (default = 1) (CUB).
3543 */
3544 Terminal.prototype.cursorBackward = function(params) {
3545 var param = params[0];
3546 if (param < 1) param = 1;
3547 this.x -= param;
3548 if (this.x < 0) this.x = 0;
3549 };
3550
3551
3552 /**
3553 * CSI Ps ; Ps H
3554 * Cursor Position [row;column] (default = [1,1]) (CUP).
3555 */
3556 Terminal.prototype.cursorPos = function(params) {
3557 var row, col;
3558
3559 row = params[0] - 1;
3560
3561 if (params.length >= 2) {
3562 col = params[1] - 1;
3563 } else {
3564 col = 0;
3565 }
3566
3567 if (row < 0) {
3568 row = 0;
3569 } else if (row >= this.rows) {
3570 row = this.rows - 1;
3571 }
3572
3573 if (col < 0) {
3574 col = 0;
3575 } else if (col >= this.cols) {
3576 col = this.cols - 1;
3577 }
3578
3579 this.x = col;
3580 this.y = row;
3581 };
3582
3583
3584 /**
3585 * CSI Ps J Erase in Display (ED).
3586 * Ps = 0 -> Erase Below (default).
3587 * Ps = 1 -> Erase Above.
3588 * Ps = 2 -> Erase All.
3589 * Ps = 3 -> Erase Saved Lines (xterm).
3590 * CSI ? Ps J
3591 * Erase in Display (DECSED).
3592 * Ps = 0 -> Selective Erase Below (default).
3593 * Ps = 1 -> Selective Erase Above.
3594 * Ps = 2 -> Selective Erase All.
3595 */
3596 Terminal.prototype.eraseInDisplay = function(params) {
3597 var j;
3598 switch (params[0]) {
3599 case 0:
3600 this.eraseRight(this.x, this.y);
3601 j = this.y + 1;
3602 for (; j < this.rows; j++) {
3603 this.eraseLine(j);
3604 }
3605 break;
3606 case 1:
3607 this.eraseLeft(this.x, this.y);
3608 j = this.y;
3609 while (j--) {
3610 this.eraseLine(j);
3611 }
3612 break;
3613 case 2:
3614 j = this.rows;
3615 while (j--) this.eraseLine(j);
3616 break;
3617 case 3:
3618 ; // no saved lines
3619 break;
3620 }
3621 };
3622
3623
3624 /**
3625 * CSI Ps K Erase in Line (EL).
3626 * Ps = 0 -> Erase to Right (default).
3627 * Ps = 1 -> Erase to Left.
3628 * Ps = 2 -> Erase All.
3629 * CSI ? Ps K
3630 * Erase in Line (DECSEL).
3631 * Ps = 0 -> Selective Erase to Right (default).
3632 * Ps = 1 -> Selective Erase to Left.
3633 * Ps = 2 -> Selective Erase All.
3634 */
3635 Terminal.prototype.eraseInLine = function(params) {
3636 switch (params[0]) {
3637 case 0:
3638 this.eraseRight(this.x, this.y);
3639 break;
3640 case 1:
3641 this.eraseLeft(this.x, this.y);
3642 break;
3643 case 2:
3644 this.eraseLine(this.y);
3645 break;
3646 }
3647 };
3648
3649
3650 /**
3651 * CSI Pm m Character Attributes (SGR).
3652 * Ps = 0 -> Normal (default).
3653 * Ps = 1 -> Bold.
3654 * Ps = 4 -> Underlined.
3655 * Ps = 5 -> Blink (appears as Bold).
3656 * Ps = 7 -> Inverse.
3657 * Ps = 8 -> Invisible, i.e., hidden (VT300).
3658 * Ps = 2 2 -> Normal (neither bold nor faint).
3659 * Ps = 2 4 -> Not underlined.
3660 * Ps = 2 5 -> Steady (not blinking).
3661 * Ps = 2 7 -> Positive (not inverse).
3662 * Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3663 * Ps = 3 0 -> Set foreground color to Black.
3664 * Ps = 3 1 -> Set foreground color to Red.
3665 * Ps = 3 2 -> Set foreground color to Green.
3666 * Ps = 3 3 -> Set foreground color to Yellow.
3667 * Ps = 3 4 -> Set foreground color to Blue.
3668 * Ps = 3 5 -> Set foreground color to Magenta.
3669 * Ps = 3 6 -> Set foreground color to Cyan.
3670 * Ps = 3 7 -> Set foreground color to White.
3671 * Ps = 3 9 -> Set foreground color to default (original).
3672 * Ps = 4 0 -> Set background color to Black.
3673 * Ps = 4 1 -> Set background color to Red.
3674 * Ps = 4 2 -> Set background color to Green.
3675 * Ps = 4 3 -> Set background color to Yellow.
3676 * Ps = 4 4 -> Set background color to Blue.
3677 * Ps = 4 5 -> Set background color to Magenta.
3678 * Ps = 4 6 -> Set background color to Cyan.
3679 * Ps = 4 7 -> Set background color to White.
3680 * Ps = 4 9 -> Set background color to default (original).
3681 *
3682 * If 16-color support is compiled, the following apply. Assume
3683 * that xterm's resources are set so that the ISO color codes are
3684 * the first 8 of a set of 16. Then the aixterm colors are the
3685 * bright versions of the ISO colors:
3686 * Ps = 9 0 -> Set foreground color to Black.
3687 * Ps = 9 1 -> Set foreground color to Red.
3688 * Ps = 9 2 -> Set foreground color to Green.
3689 * Ps = 9 3 -> Set foreground color to Yellow.
3690 * Ps = 9 4 -> Set foreground color to Blue.
3691 * Ps = 9 5 -> Set foreground color to Magenta.
3692 * Ps = 9 6 -> Set foreground color to Cyan.
3693 * Ps = 9 7 -> Set foreground color to White.
3694 * Ps = 1 0 0 -> Set background color to Black.
3695 * Ps = 1 0 1 -> Set background color to Red.
3696 * Ps = 1 0 2 -> Set background color to Green.
3697 * Ps = 1 0 3 -> Set background color to Yellow.
3698 * Ps = 1 0 4 -> Set background color to Blue.
3699 * Ps = 1 0 5 -> Set background color to Magenta.
3700 * Ps = 1 0 6 -> Set background color to Cyan.
3701 * Ps = 1 0 7 -> Set background color to White.
3702 *
3703 * If xterm is compiled with the 16-color support disabled, it
3704 * supports the following, from rxvt:
3705 * Ps = 1 0 0 -> Set foreground and background color to
3706 * default.
3707 *
3708 * If 88- or 256-color support is compiled, the following apply.
3709 * Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3710 * Ps.
3711 * Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3712 * Ps.
3713 */
3714 Terminal.prototype.charAttributes = function(params) {
3715 // Optimize a single SGR0.
3716 if (params.length === 1 && params[0] === 0) {
3717 this.curAttr = this.defAttr;
3718 return;
3719 }
3720
3721 var l = params.length
3722 , i = 0
3723 , flags = this.curAttr >> 18
3724 , fg = (this.curAttr >> 9) & 0x1ff
3725 , bg = this.curAttr & 0x1ff
3726 , p;
3727
3728 for (; i < l; i++) {
3729 p = params[i];
3730 if (p >= 30 && p <= 37) {
3731 // fg color 8
3732 fg = p - 30;
3733 } else if (p >= 40 && p <= 47) {
3734 // bg color 8
3735 bg = p - 40;
3736 } else if (p >= 90 && p <= 97) {
3737 // fg color 16
3738 p += 8;
3739 fg = p - 90;
3740 } else if (p >= 100 && p <= 107) {
3741 // bg color 16
3742 p += 8;
3743 bg = p - 100;
3744 } else if (p === 0) {
3745 // default
3746 flags = this.defAttr >> 18;
3747 fg = (this.defAttr >> 9) & 0x1ff;
3748 bg = this.defAttr & 0x1ff;
3749 // flags = 0;
3750 // fg = 0x1ff;
3751 // bg = 0x1ff;
3752 } else if (p === 1) {
3753 // bold text
3754 flags |= 1;
3755 } else if (p === 4) {
3756 // underlined text
3757 flags |= 2;
3758 } else if (p === 5) {
3759 // blink
3760 flags |= 4;
3761 } else if (p === 7) {
3762 // inverse and positive
3763 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3764 flags |= 8;
3765 } else if (p === 8) {
3766 // invisible
3767 flags |= 16;
3768 } else if (p === 22) {
3769 // not bold
3770 flags &= ~1;
3771 } else if (p === 24) {
3772 // not underlined
3773 flags &= ~2;
3774 } else if (p === 25) {
3775 // not blink
3776 flags &= ~4;
3777 } else if (p === 27) {
3778 // not inverse
3779 flags &= ~8;
3780 } else if (p === 28) {
3781 // not invisible
3782 flags &= ~16;
3783 } else if (p === 39) {
3784 // reset fg
3785 fg = (this.defAttr >> 9) & 0x1ff;
3786 } else if (p === 49) {
3787 // reset bg
3788 bg = this.defAttr & 0x1ff;
3789 } else if (p === 38) {
3790 // fg color 256
3791 if (params[i + 1] === 2) {
3792 i += 2;
3793 fg = matchColor(
3794 params[i] & 0xff,
3795 params[i + 1] & 0xff,
3796 params[i + 2] & 0xff);
3797 if (fg === -1) fg = 0x1ff;
3798 i += 2;
3799 } else if (params[i + 1] === 5) {
3800 i += 2;
3801 p = params[i] & 0xff;
3802 fg = p;
3803 }
3804 } else if (p === 48) {
3805 // bg color 256
3806 if (params[i + 1] === 2) {
3807 i += 2;
3808 bg = matchColor(
3809 params[i] & 0xff,
3810 params[i + 1] & 0xff,
3811 params[i + 2] & 0xff);
3812 if (bg === -1) bg = 0x1ff;
3813 i += 2;
3814 } else if (params[i + 1] === 5) {
3815 i += 2;
3816 p = params[i] & 0xff;
3817 bg = p;
3818 }
3819 } else if (p === 100) {
3820 // reset fg/bg
3821 fg = (this.defAttr >> 9) & 0x1ff;
3822 bg = this.defAttr & 0x1ff;
3823 } else {
3824 this.error('Unknown SGR attribute: %d.', p);
3825 }
3826 }
3827
3828 this.curAttr = (flags << 18) | (fg << 9) | bg;
3829 };
3830
3831
3832 /**
3833 * CSI Ps n Device Status Report (DSR).
3834 * Ps = 5 -> Status Report. Result (``OK'') is
3835 * CSI 0 n
3836 * Ps = 6 -> Report Cursor Position (CPR) [row;column].
3837 * Result is
3838 * CSI r ; c R
3839 * CSI ? Ps n
3840 * Device Status Report (DSR, DEC-specific).
3841 * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3842 * ? r ; c R (assumes page is zero).
3843 * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3844 * or CSI ? 1 1 n (not ready).
3845 * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3846 * or CSI ? 2 1 n (locked).
3847 * Ps = 2 6 -> Report Keyboard status as
3848 * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3849 * The last two parameters apply to VT400 & up, and denote key-
3850 * board ready and LK01 respectively.
3851 * Ps = 5 3 -> Report Locator status as
3852 * CSI ? 5 3 n Locator available, if compiled-in, or
3853 * CSI ? 5 0 n No Locator, if not.
3854 */
3855 Terminal.prototype.deviceStatus = function(params) {
3856 if (!this.prefix) {
3857 switch (params[0]) {
3858 case 5:
3859 // status report
3860 this.send('\x1b[0n');
3861 break;
3862 case 6:
3863 // cursor position
3864 this.send('\x1b['
3865 + (this.y + 1)
3866 + ';'
3867 + (this.x + 1)
3868 + 'R');
3869 break;
3870 }
3871 } else if (this.prefix === '?') {
3872 // modern xterm doesnt seem to
3873 // respond to any of these except ?6, 6, and 5
3874 switch (params[0]) {
3875 case 6:
3876 // cursor position
3877 this.send('\x1b[?'
3878 + (this.y + 1)
3879 + ';'
3880 + (this.x + 1)
3881 + 'R');
3882 break;
3883 case 15:
3884 // no printer
3885 // this.send('\x1b[?11n');
3886 break;
3887 case 25:
3888 // dont support user defined keys
3889 // this.send('\x1b[?21n');
3890 break;
3891 case 26:
3892 // north american keyboard
3893 // this.send('\x1b[?27;1;0;0n');
3894 break;
3895 case 53:
3896 // no dec locator/mouse
3897 // this.send('\x1b[?50n');
3898 break;
3899 }
3900 }
3901 };
3902
3903
3904 /**
3905 * Additions
3906 */
3907
3908 /**
3909 * CSI Ps @
3910 * Insert Ps (Blank) Character(s) (default = 1) (ICH).
3911 */
3912 Terminal.prototype.insertChars = function(params) {
3913 var param, row, j, ch;
3914
3915 param = params[0];
3916 if (param < 1) param = 1;
3917
3918 row = this.y + this.ybase;
3919 j = this.x;
3920 ch = [this.eraseAttr(), ' ', 1]; // xterm
3921
3922 while (param-- && j < this.cols) {
3923 this.lines[row].splice(j++, 0, ch);
3924 this.lines[row].pop();
3925 }
3926 };
3927
3928 /**
3929 * CSI Ps E
3930 * Cursor Next Line Ps Times (default = 1) (CNL).
3931 * same as CSI Ps B ?
3932 */
3933 Terminal.prototype.cursorNextLine = function(params) {
3934 var param = params[0];
3935 if (param < 1) param = 1;
3936 this.y += param;
3937 if (this.y >= this.rows) {
3938 this.y = this.rows - 1;
3939 }
3940 this.x = 0;
3941 };
3942
3943
3944 /**
3945 * CSI Ps F
3946 * Cursor Preceding Line Ps Times (default = 1) (CNL).
3947 * reuse CSI Ps A ?
3948 */
3949 Terminal.prototype.cursorPrecedingLine = function(params) {
3950 var param = params[0];
3951 if (param < 1) param = 1;
3952 this.y -= param;
3953 if (this.y < 0) this.y = 0;
3954 this.x = 0;
3955 };
3956
3957
3958 /**
3959 * CSI Ps G
3960 * Cursor Character Absolute [column] (default = [row,1]) (CHA).
3961 */
3962 Terminal.prototype.cursorCharAbsolute = function(params) {
3963 var param = params[0];
3964 if (param < 1) param = 1;
3965 this.x = param - 1;
3966 };
3967
3968
3969 /**
3970 * CSI Ps L
3971 * Insert Ps Line(s) (default = 1) (IL).
3972 */
3973 Terminal.prototype.insertLines = function(params) {
3974 var param, row, j;
3975
3976 param = params[0];
3977 if (param < 1) param = 1;
3978 row = this.y + this.ybase;
3979
3980 j = this.rows - 1 - this.scrollBottom;
3981 j = this.rows - 1 + this.ybase - j + 1;
3982
3983 while (param--) {
3984 // test: echo -e '\e[44m\e[1L\e[0m'
3985 // blankLine(true) - xterm/linux behavior
3986 this.lines.splice(row, 0, this.blankLine(true));
3987 this.lines.splice(j, 1);
3988 }
3989
3990 // this.maxRange();
3991 this.updateRange(this.y);
3992 this.updateRange(this.scrollBottom);
3993 };
3994
3995
3996 /**
3997 * CSI Ps M
3998 * Delete Ps Line(s) (default = 1) (DL).
3999 */
4000 Terminal.prototype.deleteLines = function(params) {
4001 var param, row, j;
4002
4003 param = params[0];
4004 if (param < 1) param = 1;
4005 row = this.y + this.ybase;
4006
4007 j = this.rows - 1 - this.scrollBottom;
4008 j = this.rows - 1 + this.ybase - j;
4009
4010 while (param--) {
4011 // test: echo -e '\e[44m\e[1M\e[0m'
4012 // blankLine(true) - xterm/linux behavior
4013 this.lines.splice(j + 1, 0, this.blankLine(true));
4014 this.lines.splice(row, 1);
4015 }
4016
4017 // this.maxRange();
4018 this.updateRange(this.y);
4019 this.updateRange(this.scrollBottom);
4020 };
4021
4022
4023 /**
4024 * CSI Ps P
4025 * Delete Ps Character(s) (default = 1) (DCH).
4026 */
4027 Terminal.prototype.deleteChars = function(params) {
4028 var param, row, ch;
4029
4030 param = params[0];
4031 if (param < 1) param = 1;
4032
4033 row = this.y + this.ybase;
4034 ch = [this.eraseAttr(), ' ', 1]; // xterm
4035
4036 while (param--) {
4037 this.lines[row].splice(this.x, 1);
4038 this.lines[row].push(ch);
4039 }
4040 };
4041
4042 /**
4043 * CSI Ps X
4044 * Erase Ps Character(s) (default = 1) (ECH).
4045 */
4046 Terminal.prototype.eraseChars = function(params) {
4047 var param, row, j, ch;
4048
4049 param = params[0];
4050 if (param < 1) param = 1;
4051
4052 row = this.y + this.ybase;
4053 j = this.x;
4054 ch = [this.eraseAttr(), ' ', 1]; // xterm
4055
4056 while (param-- && j < this.cols) {
4057 this.lines[row][j++] = ch;
4058 }
4059 };
4060
4061 /**
4062 * CSI Pm ` Character Position Absolute
4063 * [column] (default = [row,1]) (HPA).
4064 */
4065 Terminal.prototype.charPosAbsolute = function(params) {
4066 var param = params[0];
4067 if (param < 1) param = 1;
4068 this.x = param - 1;
4069 if (this.x >= this.cols) {
4070 this.x = this.cols - 1;
4071 }
4072 };
4073
4074
4075 /**
4076 * 141 61 a * HPR -
4077 * Horizontal Position Relative
4078 * reuse CSI Ps C ?
4079 */
4080 Terminal.prototype.HPositionRelative = function(params) {
4081 var param = params[0];
4082 if (param < 1) param = 1;
4083 this.x += param;
4084 if (this.x >= this.cols) {
4085 this.x = this.cols - 1;
4086 }
4087 };
4088
4089
4090 /**
4091 * CSI Ps c Send Device Attributes (Primary DA).
4092 * Ps = 0 or omitted -> request attributes from terminal. The
4093 * response depends on the decTerminalID resource setting.
4094 * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
4095 * -> CSI ? 1 ; 0 c (``VT101 with No Options'')
4096 * -> CSI ? 6 c (``VT102'')
4097 * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
4098 * The VT100-style response parameters do not mean anything by
4099 * themselves. VT220 parameters do, telling the host what fea-
4100 * tures the terminal supports:
4101 * Ps = 1 -> 132-columns.
4102 * Ps = 2 -> Printer.
4103 * Ps = 6 -> Selective erase.
4104 * Ps = 8 -> User-defined keys.
4105 * Ps = 9 -> National replacement character sets.
4106 * Ps = 1 5 -> Technical characters.
4107 * Ps = 2 2 -> ANSI color, e.g., VT525.
4108 * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
4109 * CSI > Ps c
4110 * Send Device Attributes (Secondary DA).
4111 * Ps = 0 or omitted -> request the terminal's identification
4112 * code. The response depends on the decTerminalID resource set-
4113 * ting. It should apply only to VT220 and up, but xterm extends
4114 * this to VT100.
4115 * -> CSI > Pp ; Pv ; Pc c
4116 * where Pp denotes the terminal type
4117 * Pp = 0 -> ``VT100''.
4118 * Pp = 1 -> ``VT220''.
4119 * and Pv is the firmware version (for xterm, this was originally
4120 * the XFree86 patch number, starting with 95). In a DEC termi-
4121 * nal, Pc indicates the ROM cartridge registration number and is
4122 * always zero.
4123 * More information:
4124 * xterm/charproc.c - line 2012, for more information.
4125 * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
4126 */
4127 Terminal.prototype.sendDeviceAttributes = function(params) {
4128 if (params[0] > 0) return;
4129
4130 if (!this.prefix) {
4131 if (this.is('xterm')
4132 || this.is('rxvt-unicode')
4133 || this.is('screen')) {
4134 this.send('\x1b[?1;2c');
4135 } else if (this.is('linux')) {
4136 this.send('\x1b[?6c');
4137 }
4138 } else if (this.prefix === '>') {
4139 // xterm and urxvt
4140 // seem to spit this
4141 // out around ~370 times (?).
4142 if (this.is('xterm')) {
4143 this.send('\x1b[>0;276;0c');
4144 } else if (this.is('rxvt-unicode')) {
4145 this.send('\x1b[>85;95;0c');
4146 } else if (this.is('linux')) {
4147 // not supported by linux console.
4148 // linux console echoes parameters.
4149 this.send(params[0] + 'c');
4150 } else if (this.is('screen')) {
4151 this.send('\x1b[>83;40003;0c');
4152 }
4153 }
4154 };
4155
4156
4157 /**
4158 * CSI Pm d
4159 * Line Position Absolute [row] (default = [1,column]) (VPA).
4160 */
4161 Terminal.prototype.linePosAbsolute = function(params) {
4162 var param = params[0];
4163 if (param < 1) param = 1;
4164 this.y = param - 1;
4165 if (this.y >= this.rows) {
4166 this.y = this.rows - 1;
4167 }
4168 };
4169
4170
4171 /**
4172 * 145 65 e * VPR - Vertical Position Relative
4173 * reuse CSI Ps B ?
4174 */
4175 Terminal.prototype.VPositionRelative = function(params) {
4176 var param = params[0];
4177 if (param < 1) param = 1;
4178 this.y += param;
4179 if (this.y >= this.rows) {
4180 this.y = this.rows - 1;
4181 }
4182 };
4183
4184
4185 /**
4186 * CSI Ps ; Ps f
4187 * Horizontal and Vertical Position [row;column] (default =
4188 * [1,1]) (HVP).
4189 */
4190 Terminal.prototype.HVPosition = function(params) {
4191 if (params[0] < 1) params[0] = 1;
4192 if (params[1] < 1) params[1] = 1;
4193
4194 this.y = params[0] - 1;
4195 if (this.y >= this.rows) {
4196 this.y = this.rows - 1;
4197 }
4198
4199 this.x = params[1] - 1;
4200 if (this.x >= this.cols) {
4201 this.x = this.cols - 1;
4202 }
4203 };
4204
4205
4206 /**
4207 * CSI Pm h Set Mode (SM).
4208 * Ps = 2 -> Keyboard Action Mode (AM).
4209 * Ps = 4 -> Insert Mode (IRM).
4210 * Ps = 1 2 -> Send/receive (SRM).
4211 * Ps = 2 0 -> Automatic Newline (LNM).
4212 * CSI ? Pm h
4213 * DEC Private Mode Set (DECSET).
4214 * Ps = 1 -> Application Cursor Keys (DECCKM).
4215 * Ps = 2 -> Designate USASCII for character sets G0-G3
4216 * (DECANM), and set VT100 mode.
4217 * Ps = 3 -> 132 Column Mode (DECCOLM).
4218 * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
4219 * Ps = 5 -> Reverse Video (DECSCNM).
4220 * Ps = 6 -> Origin Mode (DECOM).
4221 * Ps = 7 -> Wraparound Mode (DECAWM).
4222 * Ps = 8 -> Auto-repeat Keys (DECARM).
4223 * Ps = 9 -> Send Mouse X & Y on button press. See the sec-
4224 * tion Mouse Tracking.
4225 * Ps = 1 0 -> Show toolbar (rxvt).
4226 * Ps = 1 2 -> Start Blinking Cursor (att610).
4227 * Ps = 1 8 -> Print form feed (DECPFF).
4228 * Ps = 1 9 -> Set print extent to full screen (DECPEX).
4229 * Ps = 2 5 -> Show Cursor (DECTCEM).
4230 * Ps = 3 0 -> Show scrollbar (rxvt).
4231 * Ps = 3 5 -> Enable font-shifting functions (rxvt).
4232 * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
4233 * Ps = 4 0 -> Allow 80 -> 132 Mode.
4234 * Ps = 4 1 -> more(1) fix (see curses resource).
4235 * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
4236 * RCM).
4237 * Ps = 4 4 -> Turn On Margin Bell.
4238 * Ps = 4 5 -> Reverse-wraparound Mode.
4239 * Ps = 4 6 -> Start Logging. This is normally disabled by a
4240 * compile-time option.
4241 * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
4242 * abled by the titeInhibit resource).
4243 * Ps = 6 6 -> Application keypad (DECNKM).
4244 * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
4245 * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
4246 * release. See the section Mouse Tracking.
4247 * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
4248 * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
4249 * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
4250 * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
4251 * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
4252 * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
4253 * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
4254 * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
4255 * (enables the eightBitInput resource).
4256 * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
4257 * Lock keys. (This enables the numLock resource).
4258 * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
4259 * enables the metaSendsEscape resource).
4260 * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
4261 * key.
4262 * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
4263 * enables the altSendsEscape resource).
4264 * Ps = 1 0 4 0 -> Keep selection even if not highlighted.
4265 * (This enables the keepSelection resource).
4266 * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
4267 * the selectToClipboard resource).
4268 * Ps = 1 0 4 2 -> Enable Urgency window manager hint when
4269 * Control-G is received. (This enables the bellIsUrgent
4270 * resource).
4271 * Ps = 1 0 4 3 -> Enable raising of the window when Control-G
4272 * is received. (enables the popOnBell resource).
4273 * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
4274 * disabled by the titeInhibit resource).
4275 * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
4276 * abled by the titeInhibit resource).
4277 * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
4278 * Screen Buffer, clearing it first. (This may be disabled by
4279 * the titeInhibit resource). This combines the effects of the 1
4280 * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
4281 * applications rather than the 4 7 mode.
4282 * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
4283 * Ps = 1 0 5 1 -> Set Sun function-key mode.
4284 * Ps = 1 0 5 2 -> Set HP function-key mode.
4285 * Ps = 1 0 5 3 -> Set SCO function-key mode.
4286 * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
4287 * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
4288 * Ps = 2 0 0 4 -> Set bracketed paste mode.
4289 * Modes:
4290 * http: *vt100.net/docs/vt220-rm/chapter4.html
4291 */
4292 Terminal.prototype.setMode = function(params) {
4293 if (typeof params === 'object') {
4294 var l = params.length
4295 , i = 0;
4296
4297 for (; i < l; i++) {
4298 this.setMode(params[i]);
4299 }
4300
4301 return;
4302 }
4303
4304 if (!this.prefix) {
4305 switch (params) {
4306 case 4:
4307 this.insertMode = true;
4308 break;
4309 case 20:
4310 //this.convertEol = true;
4311 break;
4312 }
4313 } else if (this.prefix === '?') {
4314 switch (params) {
4315 case 1:
4316 this.applicationCursor = true;
4317 break;
4318 case 2:
4319 this.setgCharset(0, Terminal.charsets.US);
4320 this.setgCharset(1, Terminal.charsets.US);
4321 this.setgCharset(2, Terminal.charsets.US);
4322 this.setgCharset(3, Terminal.charsets.US);
4323 // set VT100 mode here
4324 break;
4325 case 3: // 132 col mode
4326 this.savedCols = this.cols;
4327 this.resize(132, this.rows);
4328 break;
4329 case 6:
4330 this.originMode = true;
4331 break;
4332 case 7:
4333 this.wraparoundMode = true;
4334 break;
4335 case 12:
4336 // this.cursorBlink = true;
4337 break;
4338 case 66:
4339 this.log('Serial port requested application keypad.');
4340 this.applicationKeypad = true;
4341 this.viewport.setApplicationMode(true);
4342 break;
4343 case 9: // X10 Mouse
4344 // no release, no motion, no wheel, no modifiers.
4345 case 1000: // vt200 mouse
4346 // no motion.
4347 // no modifiers, except control on the wheel.
4348 case 1002: // button event mouse
4349 case 1003: // any event mouse
4350 // any event - sends motion events,
4351 // even if there is no button held down.
4352 this.x10Mouse = params === 9;
4353 this.vt200Mouse = params === 1000;
4354 this.normalMouse = params > 1000;
4355 this.mouseEvents = true;
4356 this.element.style.cursor = 'default';
4357 this.log('Binding to mouse events.');
4358 break;
4359 case 1004: // send focusin/focusout events
4360 // focusin: ^[[I
4361 // focusout: ^[[O
4362 this.sendFocus = true;
4363 break;
4364 case 1005: // utf8 ext mode mouse
4365 this.utfMouse = true;
4366 // for wide terminals
4367 // simply encodes large values as utf8 characters
4368 break;
4369 case 1006: // sgr ext mode mouse
4370 this.sgrMouse = true;
4371 // for wide terminals
4372 // does not add 32 to fields
4373 // press: ^[[<b;x;yM
4374 // release: ^[[<b;x;ym
4375 break;
4376 case 1015: // urxvt ext mode mouse
4377 this.urxvtMouse = true;
4378 // for wide terminals
4379 // numbers for fields
4380 // press: ^[[b;x;yM
4381 // motion: ^[[b;x;yT
4382 break;
4383 case 25: // show cursor
4384 this.cursorHidden = false;
4385 break;
4386 case 1049: // alt screen buffer cursor
4387 //this.saveCursor();
4388 ; // FALL-THROUGH
4389 case 47: // alt screen buffer
4390 case 1047: // alt screen buffer
4391 if (!this.normal) {
4392 var normal = {
4393 lines: this.lines,
4394 ybase: this.ybase,
4395 ydisp: this.ydisp,
4396 x: this.x,
4397 y: this.y,
4398 scrollTop: this.scrollTop,
4399 scrollBottom: this.scrollBottom,
4400 tabs: this.tabs
4401 // XXX save charset(s) here?
4402 // charset: this.charset,
4403 // glevel: this.glevel,
4404 // charsets: this.charsets
4405 };
4406 this.reset();
4407 this.normal = normal;
4408 this.showCursor();
4409 }
4410 break;
4411 }
4412 }
4413 };
4414
4415 /**
4416 * CSI Pm l Reset Mode (RM).
4417 * Ps = 2 -> Keyboard Action Mode (AM).
4418 * Ps = 4 -> Replace Mode (IRM).
4419 * Ps = 1 2 -> Send/receive (SRM).
4420 * Ps = 2 0 -> Normal Linefeed (LNM).
4421 * CSI ? Pm l
4422 * DEC Private Mode Reset (DECRST).
4423 * Ps = 1 -> Normal Cursor Keys (DECCKM).
4424 * Ps = 2 -> Designate VT52 mode (DECANM).
4425 * Ps = 3 -> 80 Column Mode (DECCOLM).
4426 * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
4427 * Ps = 5 -> Normal Video (DECSCNM).
4428 * Ps = 6 -> Normal Cursor Mode (DECOM).
4429 * Ps = 7 -> No Wraparound Mode (DECAWM).
4430 * Ps = 8 -> No Auto-repeat Keys (DECARM).
4431 * Ps = 9 -> Don't send Mouse X & Y on button press.
4432 * Ps = 1 0 -> Hide toolbar (rxvt).
4433 * Ps = 1 2 -> Stop Blinking Cursor (att610).
4434 * Ps = 1 8 -> Don't print form feed (DECPFF).
4435 * Ps = 1 9 -> Limit print to scrolling region (DECPEX).
4436 * Ps = 2 5 -> Hide Cursor (DECTCEM).
4437 * Ps = 3 0 -> Don't show scrollbar (rxvt).
4438 * Ps = 3 5 -> Disable font-shifting functions (rxvt).
4439 * Ps = 4 0 -> Disallow 80 -> 132 Mode.
4440 * Ps = 4 1 -> No more(1) fix (see curses resource).
4441 * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
4442 * NRCM).
4443 * Ps = 4 4 -> Turn Off Margin Bell.
4444 * Ps = 4 5 -> No Reverse-wraparound Mode.
4445 * Ps = 4 6 -> Stop Logging. (This is normally disabled by a
4446 * compile-time option).
4447 * Ps = 4 7 -> Use Normal Screen Buffer.
4448 * Ps = 6 6 -> Numeric keypad (DECNKM).
4449 * Ps = 6 7 -> Backarrow key sends delete (DECBKM).
4450 * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
4451 * release. See the section Mouse Tracking.
4452 * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
4453 * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
4454 * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
4455 * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
4456 * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
4457 * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
4458 * (rxvt).
4459 * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
4460 * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
4461 * the eightBitInput resource).
4462 * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
4463 * Lock keys. (This disables the numLock resource).
4464 * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
4465 * (This disables the metaSendsEscape resource).
4466 * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
4467 * Delete key.
4468 * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
4469 * (This disables the altSendsEscape resource).
4470 * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
4471 * (This disables the keepSelection resource).
4472 * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
4473 * the selectToClipboard resource).
4474 * Ps = 1 0 4 2 -> Disable Urgency window manager hint when
4475 * Control-G is received. (This disables the bellIsUrgent
4476 * resource).
4477 * Ps = 1 0 4 3 -> Disable raising of the window when Control-
4478 * G is received. (This disables the popOnBell resource).
4479 * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
4480 * first if in the Alternate Screen. (This may be disabled by
4481 * the titeInhibit resource).
4482 * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
4483 * disabled by the titeInhibit resource).
4484 * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
4485 * as in DECRC. (This may be disabled by the titeInhibit
4486 * resource). This combines the effects of the 1 0 4 7 and 1 0
4487 * 4 8 modes. Use this with terminfo-based applications rather
4488 * than the 4 7 mode.
4489 * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
4490 * Ps = 1 0 5 1 -> Reset Sun function-key mode.
4491 * Ps = 1 0 5 2 -> Reset HP function-key mode.
4492 * Ps = 1 0 5 3 -> Reset SCO function-key mode.
4493 * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
4494 * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
4495 * Ps = 2 0 0 4 -> Reset bracketed paste mode.
4496 */
4497 Terminal.prototype.resetMode = function(params) {
4498 if (typeof params === 'object') {
4499 var l = params.length
4500 , i = 0;
4501
4502 for (; i < l; i++) {
4503 this.resetMode(params[i]);
4504 }
4505
4506 return;
4507 }
4508
4509 if (!this.prefix) {
4510 switch (params) {
4511 case 4:
4512 this.insertMode = false;
4513 break;
4514 case 20:
4515 //this.convertEol = false;
4516 break;
4517 }
4518 } else if (this.prefix === '?') {
4519 switch (params) {
4520 case 1:
4521 this.applicationCursor = false;
4522 break;
4523 case 3:
4524 if (this.cols === 132 && this.savedCols) {
4525 this.resize(this.savedCols, this.rows);
4526 }
4527 delete this.savedCols;
4528 break;
4529 case 6:
4530 this.originMode = false;
4531 break;
4532 case 7:
4533 this.wraparoundMode = false;
4534 break;
4535 case 12:
4536 // this.cursorBlink = false;
4537 break;
4538 case 66:
4539 this.log('Switching back to normal keypad.');
4540 this.viewport.setApplicationMode(false);
4541 this.applicationKeypad = false;
4542 break;
4543 case 9: // X10 Mouse
4544 case 1000: // vt200 mouse
4545 case 1002: // button event mouse
4546 case 1003: // any event mouse
4547 this.x10Mouse = false;
4548 this.vt200Mouse = false;
4549 this.normalMouse = false;
4550 this.mouseEvents = false;
4551 this.element.style.cursor = '';
4552 break;
4553 case 1004: // send focusin/focusout events
4554 this.sendFocus = false;
4555 break;
4556 case 1005: // utf8 ext mode mouse
4557 this.utfMouse = false;
4558 break;
4559 case 1006: // sgr ext mode mouse
4560 this.sgrMouse = false;
4561 break;
4562 case 1015: // urxvt ext mode mouse
4563 this.urxvtMouse = false;
4564 break;
4565 case 25: // hide cursor
4566 this.cursorHidden = true;
4567 break;
4568 case 1049: // alt screen buffer cursor
4569 ; // FALL-THROUGH
4570 case 47: // normal screen buffer
4571 case 1047: // normal screen buffer - clearing it first
4572 if (this.normal) {
4573 this.lines = this.normal.lines;
4574 this.ybase = this.normal.ybase;
4575 this.ydisp = this.normal.ydisp;
4576 this.x = this.normal.x;
4577 this.y = this.normal.y;
4578 this.scrollTop = this.normal.scrollTop;
4579 this.scrollBottom = this.normal.scrollBottom;
4580 this.tabs = this.normal.tabs;
4581 this.normal = null;
4582 // if (params === 1049) {
4583 // this.x = this.savedX;
4584 // this.y = this.savedY;
4585 // }
4586 this.refresh(0, this.rows - 1);
4587 this.showCursor();
4588 }
4589 break;
4590 }
4591 }
4592 };
4593
4594
4595 /**
4596 * CSI Ps ; Ps r
4597 * Set Scrolling Region [top;bottom] (default = full size of win-
4598 * dow) (DECSTBM).
4599 * CSI ? Pm r
4600 */
4601 Terminal.prototype.setScrollRegion = function(params) {
4602 if (this.prefix) return;
4603 this.scrollTop = (params[0] || 1) - 1;
4604 this.scrollBottom = (params[1] || this.rows) - 1;
4605 this.x = 0;
4606 this.y = 0;
4607 };
4608
4609
4610 /**
4611 * CSI s
4612 * Save cursor (ANSI.SYS).
4613 */
4614 Terminal.prototype.saveCursor = function(params) {
4615 this.savedX = this.x;
4616 this.savedY = this.y;
4617 };
4618
4619
4620 /**
4621 * CSI u
4622 * Restore cursor (ANSI.SYS).
4623 */
4624 Terminal.prototype.restoreCursor = function(params) {
4625 this.x = this.savedX || 0;
4626 this.y = this.savedY || 0;
4627 };
4628
4629
4630 /**
4631 * Lesser Used
4632 */
4633
4634 /**
4635 * CSI Ps I
4636 * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
4637 */
4638 Terminal.prototype.cursorForwardTab = function(params) {
4639 var param = params[0] || 1;
4640 while (param--) {
4641 this.x = this.nextStop();
4642 }
4643 };
4644
4645
4646 /**
4647 * CSI Ps S Scroll up Ps lines (default = 1) (SU).
4648 */
4649 Terminal.prototype.scrollUp = function(params) {
4650 var param = params[0] || 1;
4651 while (param--) {
4652 this.lines.splice(this.ybase + this.scrollTop, 1);
4653 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
4654 }
4655 // this.maxRange();
4656 this.updateRange(this.scrollTop);
4657 this.updateRange(this.scrollBottom);
4658 };
4659
4660
4661 /**
4662 * CSI Ps T Scroll down Ps lines (default = 1) (SD).
4663 */
4664 Terminal.prototype.scrollDown = function(params) {
4665 var param = params[0] || 1;
4666 while (param--) {
4667 this.lines.splice(this.ybase + this.scrollBottom, 1);
4668 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
4669 }
4670 // this.maxRange();
4671 this.updateRange(this.scrollTop);
4672 this.updateRange(this.scrollBottom);
4673 };
4674
4675
4676 /**
4677 * CSI Ps ; Ps ; Ps ; Ps ; Ps T
4678 * Initiate highlight mouse tracking. Parameters are
4679 * [func;startx;starty;firstrow;lastrow]. See the section Mouse
4680 * Tracking.
4681 */
4682 Terminal.prototype.initMouseTracking = function(params) {
4683 // Relevant: DECSET 1001
4684 };
4685
4686
4687 /**
4688 * CSI > Ps; Ps T
4689 * Reset one or more features of the title modes to the default
4690 * value. Normally, "reset" disables the feature. It is possi-
4691 * ble to disable the ability to reset features by compiling a
4692 * different default for the title modes into xterm.
4693 * Ps = 0 -> Do not set window/icon labels using hexadecimal.
4694 * Ps = 1 -> Do not query window/icon labels using hexadeci-
4695 * mal.
4696 * Ps = 2 -> Do not set window/icon labels using UTF-8.
4697 * Ps = 3 -> Do not query window/icon labels using UTF-8.
4698 * (See discussion of "Title Modes").
4699 */
4700 Terminal.prototype.resetTitleModes = function(params) {
4701 ;
4702 };
4703
4704
4705 /**
4706 * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4707 */
4708 Terminal.prototype.cursorBackwardTab = function(params) {
4709 var param = params[0] || 1;
4710 while (param--) {
4711 this.x = this.prevStop();
4712 }
4713 };
4714
4715
4716 /**
4717 * CSI Ps b Repeat the preceding graphic character Ps times (REP).
4718 */
4719 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4720 var param = params[0] || 1
4721 , line = this.lines[this.ybase + this.y]
4722 , ch = line[this.x - 1] || [this.defAttr, ' ', 1];
4723
4724 while (param--) line[this.x++] = ch;
4725 };
4726
4727
4728 /**
4729 * CSI Ps g Tab Clear (TBC).
4730 * Ps = 0 -> Clear Current Column (default).
4731 * Ps = 3 -> Clear All.
4732 * Potentially:
4733 * Ps = 2 -> Clear Stops on Line.
4734 * http://vt100.net/annarbor/aaa-ug/section6.html
4735 */
4736 Terminal.prototype.tabClear = function(params) {
4737 var param = params[0];
4738 if (param <= 0) {
4739 delete this.tabs[this.x];
4740 } else if (param === 3) {
4741 this.tabs = {};
4742 }
4743 };
4744
4745
4746 /**
4747 * CSI Pm i Media Copy (MC).
4748 * Ps = 0 -> Print screen (default).
4749 * Ps = 4 -> Turn off printer controller mode.
4750 * Ps = 5 -> Turn on printer controller mode.
4751 * CSI ? Pm i
4752 * Media Copy (MC, DEC-specific).
4753 * Ps = 1 -> Print line containing cursor.
4754 * Ps = 4 -> Turn off autoprint mode.
4755 * Ps = 5 -> Turn on autoprint mode.
4756 * Ps = 1 0 -> Print composed display, ignores DECPEX.
4757 * Ps = 1 1 -> Print all pages.
4758 */
4759 Terminal.prototype.mediaCopy = function(params) {
4760 ;
4761 };
4762
4763
4764 /**
4765 * CSI > Ps; Ps m
4766 * Set or reset resource-values used by xterm to decide whether
4767 * to construct escape sequences holding information about the
4768 * modifiers pressed with a given key. The first parameter iden-
4769 * tifies the resource to set/reset. The second parameter is the
4770 * value to assign to the resource. If the second parameter is
4771 * omitted, the resource is reset to its initial value.
4772 * Ps = 1 -> modifyCursorKeys.
4773 * Ps = 2 -> modifyFunctionKeys.
4774 * Ps = 4 -> modifyOtherKeys.
4775 * If no parameters are given, all resources are reset to their
4776 * initial values.
4777 */
4778 Terminal.prototype.setResources = function(params) {
4779 ;
4780 };
4781
4782
4783 /**
4784 * CSI > Ps n
4785 * Disable modifiers which may be enabled via the CSI > Ps; Ps m
4786 * sequence. This corresponds to a resource value of "-1", which
4787 * cannot be set with the other sequence. The parameter identi-
4788 * fies the resource to be disabled:
4789 * Ps = 1 -> modifyCursorKeys.
4790 * Ps = 2 -> modifyFunctionKeys.
4791 * Ps = 4 -> modifyOtherKeys.
4792 * If the parameter is omitted, modifyFunctionKeys is disabled.
4793 * When modifyFunctionKeys is disabled, xterm uses the modifier
4794 * keys to make an extended sequence of functions rather than
4795 * adding a parameter to each function key to denote the modi-
4796 * fiers.
4797 */
4798 Terminal.prototype.disableModifiers = function(params) {
4799 ;
4800 };
4801
4802
4803 /**
4804 * CSI > Ps p
4805 * Set resource value pointerMode. This is used by xterm to
4806 * decide whether to hide the pointer cursor as the user types.
4807 * Valid values for the parameter:
4808 * Ps = 0 -> never hide the pointer.
4809 * Ps = 1 -> hide if the mouse tracking mode is not enabled.
4810 * Ps = 2 -> always hide the pointer. If no parameter is
4811 * given, xterm uses the default, which is 1 .
4812 */
4813 Terminal.prototype.setPointerMode = function(params) {
4814 ;
4815 };
4816
4817
4818 /**
4819 * CSI ! p Soft terminal reset (DECSTR).
4820 * http://vt100.net/docs/vt220-rm/table4-10.html
4821 */
4822 Terminal.prototype.softReset = function(params) {
4823 this.cursorHidden = false;
4824 this.insertMode = false;
4825 this.originMode = false;
4826 this.wraparoundMode = false; // autowrap
4827 this.applicationKeypad = false; // ?
4828 this.applicationCursor = false;
4829 this.scrollTop = 0;
4830 this.scrollBottom = this.rows - 1;
4831 this.curAttr = this.defAttr;
4832 this.x = this.y = 0; // ?
4833 this.charset = null;
4834 this.glevel = 0; // ??
4835 this.charsets = [null]; // ??
4836 };
4837
4838
4839 /**
4840 * CSI Ps$ p
4841 * Request ANSI mode (DECRQM). For VT300 and up, reply is
4842 * CSI Ps; Pm$ y
4843 * where Ps is the mode number as in RM, and Pm is the mode
4844 * value:
4845 * 0 - not recognized
4846 * 1 - set
4847 * 2 - reset
4848 * 3 - permanently set
4849 * 4 - permanently reset
4850 */
4851 Terminal.prototype.requestAnsiMode = function(params) {
4852 ;
4853 };
4854
4855
4856 /**
4857 * CSI ? Ps$ p
4858 * Request DEC private mode (DECRQM). For VT300 and up, reply is
4859 * CSI ? Ps; Pm$ p
4860 * where Ps is the mode number as in DECSET, Pm is the mode value
4861 * as in the ANSI DECRQM.
4862 */
4863 Terminal.prototype.requestPrivateMode = function(params) {
4864 ;
4865 };
4866
4867
4868 /**
4869 * CSI Ps ; Ps " p
4870 * Set conformance level (DECSCL). Valid values for the first
4871 * parameter:
4872 * Ps = 6 1 -> VT100.
4873 * Ps = 6 2 -> VT200.
4874 * Ps = 6 3 -> VT300.
4875 * Valid values for the second parameter:
4876 * Ps = 0 -> 8-bit controls.
4877 * Ps = 1 -> 7-bit controls (always set for VT100).
4878 * Ps = 2 -> 8-bit controls.
4879 */
4880 Terminal.prototype.setConformanceLevel = function(params) {
4881 ;
4882 };
4883
4884
4885 /**
4886 * CSI Ps q Load LEDs (DECLL).
4887 * Ps = 0 -> Clear all LEDS (default).
4888 * Ps = 1 -> Light Num Lock.
4889 * Ps = 2 -> Light Caps Lock.
4890 * Ps = 3 -> Light Scroll Lock.
4891 * Ps = 2 1 -> Extinguish Num Lock.
4892 * Ps = 2 2 -> Extinguish Caps Lock.
4893 * Ps = 2 3 -> Extinguish Scroll Lock.
4894 */
4895 Terminal.prototype.loadLEDs = function(params) {
4896 ;
4897 };
4898
4899
4900 /**
4901 * CSI Ps SP q
4902 * Set cursor style (DECSCUSR, VT520).
4903 * Ps = 0 -> blinking block.
4904 * Ps = 1 -> blinking block (default).
4905 * Ps = 2 -> steady block.
4906 * Ps = 3 -> blinking underline.
4907 * Ps = 4 -> steady underline.
4908 */
4909 Terminal.prototype.setCursorStyle = function(params) {
4910 ;
4911 };
4912
4913
4914 /**
4915 * CSI Ps " q
4916 * Select character protection attribute (DECSCA). Valid values
4917 * for the parameter:
4918 * Ps = 0 -> DECSED and DECSEL can erase (default).
4919 * Ps = 1 -> DECSED and DECSEL cannot erase.
4920 * Ps = 2 -> DECSED and DECSEL can erase.
4921 */
4922 Terminal.prototype.setCharProtectionAttr = function(params) {
4923 ;
4924 };
4925
4926
4927 /**
4928 * CSI ? Pm r
4929 * Restore DEC Private Mode Values. The value of Ps previously
4930 * saved is restored. Ps values are the same as for DECSET.
4931 */
4932 Terminal.prototype.restorePrivateValues = function(params) {
4933 ;
4934 };
4935
4936
4937 /**
4938 * CSI Pt; Pl; Pb; Pr; Ps$ r
4939 * Change Attributes in Rectangular Area (DECCARA), VT400 and up.
4940 * Pt; Pl; Pb; Pr denotes the rectangle.
4941 * Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
4942 * NOTE: xterm doesn't enable this code by default.
4943 */
4944 Terminal.prototype.setAttrInRectangle = function(params) {
4945 var t = params[0]
4946 , l = params[1]
4947 , b = params[2]
4948 , r = params[3]
4949 , attr = params[4];
4950
4951 var line
4952 , i;
4953
4954 for (; t < b + 1; t++) {
4955 line = this.lines[this.ybase + t];
4956 for (i = l; i < r; i++) {
4957 line[i] = [attr, line[i][1]];
4958 }
4959 }
4960
4961 // this.maxRange();
4962 this.updateRange(params[0]);
4963 this.updateRange(params[2]);
4964 };
4965
4966
4967 /**
4968 * CSI Pc; Pt; Pl; Pb; Pr$ x
4969 * Fill Rectangular Area (DECFRA), VT420 and up.
4970 * Pc is the character to use.
4971 * Pt; Pl; Pb; Pr denotes the rectangle.
4972 * NOTE: xterm doesn't enable this code by default.
4973 */
4974 Terminal.prototype.fillRectangle = function(params) {
4975 var ch = params[0]
4976 , t = params[1]
4977 , l = params[2]
4978 , b = params[3]
4979 , r = params[4];
4980
4981 var line
4982 , i;
4983
4984 for (; t < b + 1; t++) {
4985 line = this.lines[this.ybase + t];
4986 for (i = l; i < r; i++) {
4987 line[i] = [line[i][0], String.fromCharCode(ch)];
4988 }
4989 }
4990
4991 // this.maxRange();
4992 this.updateRange(params[1]);
4993 this.updateRange(params[3]);
4994 };
4995
4996
4997 /**
4998 * CSI Ps ; Pu ' z
4999 * Enable Locator Reporting (DECELR).
5000 * Valid values for the first parameter:
5001 * Ps = 0 -> Locator disabled (default).
5002 * Ps = 1 -> Locator enabled.
5003 * Ps = 2 -> Locator enabled for one report, then disabled.
5004 * The second parameter specifies the coordinate unit for locator
5005 * reports.
5006 * Valid values for the second parameter:
5007 * Pu = 0 <- or omitted -> default to character cells.
5008 * Pu = 1 <- device physical pixels.
5009 * Pu = 2 <- character cells.
5010 */
5011 Terminal.prototype.enableLocatorReporting = function(params) {
5012 var val = params[0] > 0;
5013 //this.mouseEvents = val;
5014 //this.decLocator = val;
5015 };
5016
5017
5018 /**
5019 * CSI Pt; Pl; Pb; Pr$ z
5020 * Erase Rectangular Area (DECERA), VT400 and up.
5021 * Pt; Pl; Pb; Pr denotes the rectangle.
5022 * NOTE: xterm doesn't enable this code by default.
5023 */
5024 Terminal.prototype.eraseRectangle = function(params) {
5025 var t = params[0]
5026 , l = params[1]
5027 , b = params[2]
5028 , r = params[3];
5029
5030 var line
5031 , i
5032 , ch;
5033
5034 ch = [this.eraseAttr(), ' ', 1]; // xterm?
5035
5036 for (; t < b + 1; t++) {
5037 line = this.lines[this.ybase + t];
5038 for (i = l; i < r; i++) {
5039 line[i] = ch;
5040 }
5041 }
5042
5043 // this.maxRange();
5044 this.updateRange(params[0]);
5045 this.updateRange(params[2]);
5046 };
5047
5048
5049 /**
5050 * CSI P m SP }
5051 * Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
5052 * NOTE: xterm doesn't enable this code by default.
5053 */
5054 Terminal.prototype.insertColumns = function() {
5055 var param = params[0]
5056 , l = this.ybase + this.rows
5057 , ch = [this.eraseAttr(), ' ', 1] // xterm?
5058 , i;
5059
5060 while (param--) {
5061 for (i = this.ybase; i < l; i++) {
5062 this.lines[i].splice(this.x + 1, 0, ch);
5063 this.lines[i].pop();
5064 }
5065 }
5066
5067 this.maxRange();
5068 };
5069
5070
5071 /**
5072 * CSI P m SP ~
5073 * Delete P s Column(s) (default = 1) (DECDC), VT420 and up
5074 * NOTE: xterm doesn't enable this code by default.
5075 */
5076 Terminal.prototype.deleteColumns = function() {
5077 var param = params[0]
5078 , l = this.ybase + this.rows
5079 , ch = [this.eraseAttr(), ' ', 1] // xterm?
5080 , i;
5081
5082 while (param--) {
5083 for (i = this.ybase; i < l; i++) {
5084 this.lines[i].splice(this.x, 1);
5085 this.lines[i].push(ch);
5086 }
5087 }
5088
5089 this.maxRange();
5090 };
5091
5092 /**
5093 * Character Sets
5094 */
5095
5096 Terminal.charsets = {};
5097
5098 // DEC Special Character and Line Drawing Set.
5099 // http://vt100.net/docs/vt102-ug/table5-13.html
5100 // A lot of curses apps use this if they see TERM=xterm.
5101 // testing: echo -e '\e(0a\e(B'
5102 // The xterm output sometimes seems to conflict with the
5103 // reference above. xterm seems in line with the reference
5104 // when running vttest however.
5105 // The table below now uses xterm's output from vttest.
5106 Terminal.charsets.SCLD = { // (0
5107 '`': '\u25c6', // '◆'
5108 'a': '\u2592', // '▒'
5109 'b': '\u0009', // '\t'
5110 'c': '\u000c', // '\f'
5111 'd': '\u000d', // '\r'
5112 'e': '\u000a', // '\n'
5113 'f': '\u00b0', // '°'
5114 'g': '\u00b1', // '±'
5115 'h': '\u2424', // '\u2424' (NL)
5116 'i': '\u000b', // '\v'
5117 'j': '\u2518', // '┘'
5118 'k': '\u2510', // '┐'
5119 'l': '\u250c', // '┌'
5120 'm': '\u2514', // '└'
5121 'n': '\u253c', // '┼'
5122 'o': '\u23ba', // '⎺'
5123 'p': '\u23bb', // '⎻'
5124 'q': '\u2500', // '─'
5125 'r': '\u23bc', // '⎼'
5126 's': '\u23bd', // '⎽'
5127 't': '\u251c', // '├'
5128 'u': '\u2524', // '┤'
5129 'v': '\u2534', // '┴'
5130 'w': '\u252c', // '┬'
5131 'x': '\u2502', // '│'
5132 'y': '\u2264', // '≤'
5133 'z': '\u2265', // '≥'
5134 '{': '\u03c0', // 'π'
5135 '|': '\u2260', // '≠'
5136 '}': '\u00a3', // '£'
5137 '~': '\u00b7' // '·'
5138 };
5139
5140 Terminal.charsets.UK = null; // (A
5141 Terminal.charsets.US = null; // (B (USASCII)
5142 Terminal.charsets.Dutch = null; // (4
5143 Terminal.charsets.Finnish = null; // (C or (5
5144 Terminal.charsets.French = null; // (R
5145 Terminal.charsets.FrenchCanadian = null; // (Q
5146 Terminal.charsets.German = null; // (K
5147 Terminal.charsets.Italian = null; // (Y
5148 Terminal.charsets.NorwegianDanish = null; // (E or (6
5149 Terminal.charsets.Spanish = null; // (Z
5150 Terminal.charsets.Swedish = null; // (H or (7
5151 Terminal.charsets.Swiss = null; // (=
5152 Terminal.charsets.ISOLatin = null; // /A
5153
5154 /**
5155 * Helpers
5156 */
5157
5158 function contains(el, arr) {
5159 for (var i = 0; i < arr.length; i += 1) {
5160 if (el === arr[i]) {
5161 return true;
5162 }
5163 }
5164 return false;
5165 }
5166
5167 function on(el, type, handler, capture) {
5168 if (!Array.isArray(el)) {
5169 el = [el];
5170 }
5171 el.forEach(function (element) {
5172 element.addEventListener(type, handler, capture || false);
5173 });
5174 }
5175
5176 function off(el, type, handler, capture) {
5177 el.removeEventListener(type, handler, capture || false);
5178 }
5179
5180 function cancel(ev, force) {
5181 if (!this.cancelEvents && !force) {
5182 return;
5183 }
5184 ev.preventDefault();
5185 ev.stopPropagation();
5186 return false;
5187 }
5188
5189 function inherits(child, parent) {
5190 function f() {
5191 this.constructor = child;
5192 }
5193 f.prototype = parent.prototype;
5194 child.prototype = new f;
5195 }
5196
5197 // if bold is broken, we can't
5198 // use it in the terminal.
5199 function isBoldBroken(document) {
5200 var body = document.getElementsByTagName('body')[0];
5201 var el = document.createElement('span');
5202 el.innerHTML = 'hello world';
5203 body.appendChild(el);
5204 var w1 = el.scrollWidth;
5205 el.style.fontWeight = 'bold';
5206 var w2 = el.scrollWidth;
5207 body.removeChild(el);
5208 return w1 !== w2;
5209 }
5210
5211 var String = this.String;
5212 var setTimeout = this.setTimeout;
5213 var setInterval = this.setInterval;
5214
5215 function indexOf(obj, el) {
5216 var i = obj.length;
5217 while (i--) {
5218 if (obj[i] === el) return i;
5219 }
5220 return -1;
5221 }
5222
5223 function isThirdLevelShift(term, ev) {
5224 var thirdLevelKey =
5225 (term.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
5226 (term.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
5227
5228 if (ev.type == 'keypress') {
5229 return thirdLevelKey;
5230 }
5231
5232 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
5233 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
5234 }
5235
5236 function matchColor(r1, g1, b1) {
5237 var hash = (r1 << 16) | (g1 << 8) | b1;
5238
5239 if (matchColor._cache[hash] != null) {
5240 return matchColor._cache[hash];
5241 }
5242
5243 var ldiff = Infinity
5244 , li = -1
5245 , i = 0
5246 , c
5247 , r2
5248 , g2
5249 , b2
5250 , diff;
5251
5252 for (; i < Terminal.vcolors.length; i++) {
5253 c = Terminal.vcolors[i];
5254 r2 = c[0];
5255 g2 = c[1];
5256 b2 = c[2];
5257
5258 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
5259
5260 if (diff === 0) {
5261 li = i;
5262 break;
5263 }
5264
5265 if (diff < ldiff) {
5266 ldiff = diff;
5267 li = i;
5268 }
5269 }
5270
5271 return matchColor._cache[hash] = li;
5272 }
5273
5274 matchColor._cache = {};
5275
5276 // http://stackoverflow.com/questions/1633828
5277 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
5278 return Math.pow(30 * (r1 - r2), 2)
5279 + Math.pow(59 * (g1 - g2), 2)
5280 + Math.pow(11 * (b1 - b2), 2);
5281 };
5282
5283 function each(obj, iter, con) {
5284 if (obj.forEach) return obj.forEach(iter, con);
5285 for (var i = 0; i < obj.length; i++) {
5286 iter.call(con, obj[i], i, obj);
5287 }
5288 }
5289
5290 function keys(obj) {
5291 if (Object.keys) return Object.keys(obj);
5292 var key, keys = [];
5293 for (key in obj) {
5294 if (Object.prototype.hasOwnProperty.call(obj, key)) {
5295 keys.push(key);
5296 }
5297 }
5298 return keys;
5299 }
5300
5301 var wcwidth = (function(opts) {
5302 // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
5303 // combining characters
5304 var COMBINING = [
5305 [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
5306 [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
5307 [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
5308 [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
5309 [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
5310 [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
5311 [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
5312 [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
5313 [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
5314 [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
5315 [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
5316 [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
5317 [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
5318 [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
5319 [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
5320 [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
5321 [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
5322 [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
5323 [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
5324 [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
5325 [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
5326 [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
5327 [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
5328 [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
5329 [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
5330 [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
5331 [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
5332 [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
5333 [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
5334 [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
5335 [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
5336 [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
5337 [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
5338 [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
5339 [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
5340 [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
5341 [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
5342 [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
5343 [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
5344 [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
5345 [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
5346 [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
5347 [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB],
5348 [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
5349 [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
5350 [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
5351 [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
5352 [0xE0100, 0xE01EF]
5353 ];
5354 // binary search
5355 function bisearch(ucs) {
5356 var min = 0;
5357 var max = COMBINING.length - 1;
5358 var mid;
5359 if (ucs < COMBINING[0][0] || ucs > COMBINING[max][1])
5360 return false;
5361 while (max >= min) {
5362 mid = Math.floor((min + max) / 2);
5363 if (ucs > COMBINING[mid][1])
5364 min = mid + 1;
5365 else if (ucs < COMBINING[mid][0])
5366 max = mid - 1;
5367 else
5368 return true;
5369 }
5370 return false;
5371 }
5372 function wcwidth(ucs) {
5373 // test for 8-bit control characters
5374 if (ucs === 0)
5375 return opts.nul;
5376 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
5377 return opts.control;
5378 // binary search in table of non-spacing characters
5379 if (bisearch(ucs))
5380 return 0;
5381 // if we arrive here, ucs is not a combining or C0/C1 control character
5382 return 1 +
5383 (
5384 ucs >= 0x1100 &&
5385 (
5386 ucs <= 0x115f || // Hangul Jamo init. consonants
5387 ucs == 0x2329 ||
5388 ucs == 0x232a ||
5389 (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) || // CJK..Yi
5390 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
5391 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compat Ideographs
5392 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
5393 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compat Forms
5394 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
5395 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
5396 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
5397 (ucs >= 0x30000 && ucs <= 0x3fffd)
5398 )
5399 );
5400 }
5401 return wcwidth;
5402 })({nul: 0, control: 0}); // configurable options
5403
5404 /**
5405 * Expose
5406 */
5407
5408 Terminal.EventEmitter = EventEmitter;
5409 Terminal.CompositionHelper = CompositionHelper;
5410 Terminal.Viewport = Viewport;
5411 Terminal.inherits = inherits;
5412
5413 /**
5414 * Adds an event listener to the terminal.
5415 *
5416 * @param {string} event The name of the event. TODO: Document all event types
5417 * @param {function} callback The function to call when the event is triggered.
5418 */
5419 Terminal.on = on;
5420 Terminal.off = off;
5421 Terminal.cancel = cancel;
5422
5423
5424 return Terminal;
5425 });