]> git.proxmox.com Git - mirror_xterm.js.git/blob - src/xterm.js
add modifier+F1-F12 keys
[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 // HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
2913 // http://unix.stackexchange.com/a/108106
2914 if (result.key == '\x1b[1;3D') {
2915 result.key = '\x1b[1;5D';
2916 }
2917 } else if (this.applicationCursor) {
2918 result.key = '\x1bOD';
2919 } else {
2920 result.key = '\x1b[D';
2921 }
2922 break;
2923 // right-arrow
2924 case 39:
2925 if (modifiers) {
2926 result.key = '\x1b[1;' + (modifiers + 1) + 'C';
2927 // HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
2928 // http://unix.stackexchange.com/a/108106
2929 if (result.key == '\x1b[1;3C') {
2930 result.key = '\x1b[1;5C';
2931 }
2932 } else if (this.applicationCursor) {
2933 result.key = '\x1bOC';
2934 } else {
2935 result.key = '\x1b[C';
2936 }
2937 break;
2938 // up-arrow
2939 case 38:
2940 if (modifiers) {
2941 result.key = '\x1b[1;' + (modifiers + 1) + 'A';
2942 // HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
2943 // http://unix.stackexchange.com/a/108106
2944 if (result.key == '\x1b[1;3A') {
2945 result.key = '\x1b[1;5A';
2946 }
2947 } else if (this.applicationCursor) {
2948 result.key = '\x1bOA';
2949 } else {
2950 result.key = '\x1b[A';
2951 }
2952 break;
2953 // down-arrow
2954 case 40:
2955 if (modifiers) {
2956 result.key = '\x1b[1;' + (modifiers + 1) + 'B';
2957 // HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
2958 // http://unix.stackexchange.com/a/108106
2959 if (result.key == '\x1b[1;3B') {
2960 result.key = '\x1b[1;5B';
2961 }
2962 } else if (this.applicationCursor) {
2963 result.key = '\x1bOB';
2964 } else {
2965 result.key = '\x1b[B';
2966 }
2967 break;
2968 // insert
2969 case 45:
2970 if (!ev.shiftKey && !ev.ctrlKey) {
2971 // <Ctrl> or <Shift> + <Insert> are used to
2972 // copy-paste on some systems.
2973 result.key = '\x1b[2~';
2974 }
2975 break;
2976 // delete
2977 case 46:
2978 if (modifiers) {
2979 result.key = '\x1b[3;' + (modifiers + 1) + '~';
2980 } else {
2981 result.key = '\x1b[3~';
2982 }
2983 break;
2984 // home
2985 case 36:
2986 if (modifiers)
2987 result.key = '\x1b[1;' + (modifiers + 1) + 'H';
2988 else if (this.applicationCursor)
2989 result.key = '\x1bOH';
2990 else
2991 result.key = '\x1b[H';
2992 break;
2993 // end
2994 case 35:
2995 if (modifiers)
2996 result.key = '\x1b[1;' + (modifiers + 1) + 'F';
2997 else if (this.applicationCursor)
2998 result.key = '\x1bOF';
2999 else
3000 result.key = '\x1b[F';
3001 break;
3002 // page up
3003 case 33:
3004 if (ev.shiftKey) {
3005 result.scrollDisp = -(this.rows - 1);
3006 } else {
3007 result.key = '\x1b[5~';
3008 }
3009 break;
3010 // page down
3011 case 34:
3012 if (ev.shiftKey) {
3013 result.scrollDisp = this.rows - 1;
3014 } else {
3015 result.key = '\x1b[6~';
3016 }
3017 break;
3018 // F1-F12
3019 case 112:
3020 if (modifiers) {
3021 result.key = '\x1b[1;' + (modifiers + 1) + 'P';
3022 } else {
3023 result.key = '\x1bOP';
3024 }
3025 break;
3026 case 113:
3027 if (modifiers) {
3028 result.key = '\x1b[1;' + (modifiers + 1) + 'Q';
3029 } else {
3030 result.key = '\x1bOQ';
3031 }
3032 break;
3033 case 114:
3034 if (modifiers) {
3035 result.key = '\x1b[1;' + (modifiers + 1) + 'R';
3036 } else {
3037 result.key = '\x1bOR';
3038 }
3039 break;
3040 case 115:
3041 if (modifiers) {
3042 result.key = '\x1b[1;' + (modifiers + 1) + 'S';
3043 } else {
3044 result.key = '\x1bOS';
3045 }
3046 break;
3047 case 116:
3048 if (modifiers) {
3049 result.key = '\x1b[15;' + (modifiers + 1) + '~';
3050 } else {
3051 result.key = '\x1b[15~';
3052 }
3053 break;
3054 case 117:
3055 if (modifiers) {
3056 result.key = '\x1b[17;' + (modifiers + 1) + '~';
3057 } else {
3058 result.key = '\x1b[17~';
3059 }
3060 break;
3061 case 118:
3062 if (modifiers) {
3063 result.key = '\x1b[18;' + (modifiers + 1) + '~';
3064 } else {
3065 result.key = '\x1b[18~';
3066 }
3067 break;
3068 case 119:
3069 if (modifiers) {
3070 result.key = '\x1b[19;' + (modifiers + 1) + '~';
3071 } else {
3072 result.key = '\x1b[19~';
3073 }
3074 break;
3075 case 120:
3076 if (modifiers) {
3077 result.key = '\x1b[20;' + (modifiers + 1) + '~';
3078 } else {
3079 result.key = '\x1b[20~';
3080 }
3081 break;
3082 case 121:
3083 if (modifiers) {
3084 result.key = '\x1b[21;' + (modifiers + 1) + '~';
3085 } else {
3086 result.key = '\x1b[21~';
3087 }
3088 break;
3089 case 122:
3090 if (modifiers) {
3091 result.key = '\x1b[23;' + (modifiers + 1) + '~';
3092 } else {
3093 result.key = '\x1b[23~';
3094 }
3095 break;
3096 case 123:
3097 if (modifiers) {
3098 result.key = '\x1b[24;' + (modifiers + 1) + '~';
3099 } else {
3100 result.key = '\x1b[24~';
3101 }
3102 break;
3103 default:
3104 // a-z and space
3105 if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
3106 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3107 result.key = String.fromCharCode(ev.keyCode - 64);
3108 } else if (ev.keyCode === 32) {
3109 // NUL
3110 result.key = String.fromCharCode(0);
3111 } else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
3112 // escape, file sep, group sep, record sep, unit sep
3113 result.key = String.fromCharCode(ev.keyCode - 51 + 27);
3114 } else if (ev.keyCode === 56) {
3115 // delete
3116 result.key = String.fromCharCode(127);
3117 } else if (ev.keyCode === 219) {
3118 // ^[ - escape
3119 result.key = String.fromCharCode(27);
3120 } else if (ev.keyCode === 221) {
3121 // ^] - group sep
3122 result.key = String.fromCharCode(29);
3123 }
3124 } else if (!this.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
3125 // On Mac this is a third level shift. Use <Esc> instead.
3126 if (ev.keyCode >= 65 && ev.keyCode <= 90) {
3127 result.key = '\x1b' + String.fromCharCode(ev.keyCode + 32);
3128 } else if (ev.keyCode === 192) {
3129 result.key = '\x1b`';
3130 } else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
3131 result.key = '\x1b' + (ev.keyCode - 48);
3132 }
3133 }
3134 break;
3135 }
3136 return result;
3137 };
3138
3139 /**
3140 * Set the G level of the terminal
3141 * @param g
3142 */
3143 Terminal.prototype.setgLevel = function(g) {
3144 this.glevel = g;
3145 this.charset = this.charsets[g];
3146 };
3147
3148 /**
3149 * Set the charset for the given G level of the terminal
3150 * @param g
3151 * @param charset
3152 */
3153 Terminal.prototype.setgCharset = function(g, charset) {
3154 this.charsets[g] = charset;
3155 if (this.glevel === g) {
3156 this.charset = charset;
3157 }
3158 };
3159
3160 /**
3161 * Handle a keypress event.
3162 * Key Resources:
3163 * - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
3164 * @param {KeyboardEvent} ev The keypress event to be handled.
3165 */
3166 Terminal.prototype.keyPress = function(ev) {
3167 var key;
3168
3169 this.cancel(ev);
3170
3171 if (ev.charCode) {
3172 key = ev.charCode;
3173 } else if (ev.which == null) {
3174 key = ev.keyCode;
3175 } else if (ev.which !== 0 && ev.charCode !== 0) {
3176 key = ev.which;
3177 } else {
3178 return false;
3179 }
3180
3181 if (!key || (
3182 (ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
3183 )) {
3184 return false;
3185 }
3186
3187 key = String.fromCharCode(key);
3188
3189 this.emit('keypress', key, ev);
3190 this.emit('key', key, ev);
3191 this.showCursor();
3192 this.handler(key);
3193
3194 return false;
3195 };
3196
3197 /**
3198 * Send data for handling to the terminal
3199 * @param {string} data
3200 */
3201 Terminal.prototype.send = function(data) {
3202 var self = this;
3203
3204 if (!this.queue) {
3205 setTimeout(function() {
3206 self.handler(self.queue);
3207 self.queue = '';
3208 }, 1);
3209 }
3210
3211 this.queue += data;
3212 };
3213
3214 /**
3215 * Ring the bell.
3216 * Note: We could do sweet things with webaudio here
3217 */
3218 Terminal.prototype.bell = function() {
3219 if (!this.visualBell) return;
3220 var self = this;
3221 this.element.style.borderColor = 'white';
3222 setTimeout(function() {
3223 self.element.style.borderColor = '';
3224 }, 10);
3225 if (this.popOnBell) this.focus();
3226 };
3227
3228 /**
3229 * Log the current state to the console.
3230 */
3231 Terminal.prototype.log = function() {
3232 if (!this.debug) return;
3233 if (!this.context.console || !this.context.console.log) return;
3234 var args = Array.prototype.slice.call(arguments);
3235 this.context.console.log.apply(this.context.console, args);
3236 };
3237
3238 /**
3239 * Log the current state as error to the console.
3240 */
3241 Terminal.prototype.error = function() {
3242 if (!this.debug) return;
3243 if (!this.context.console || !this.context.console.error) return;
3244 var args = Array.prototype.slice.call(arguments);
3245 this.context.console.error.apply(this.context.console, args);
3246 };
3247
3248 /**
3249 * Resizes the terminal.
3250 *
3251 * @param {number} x The number of columns to resize to.
3252 * @param {number} y The number of rows to resize to.
3253 */
3254 Terminal.prototype.resize = function(x, y) {
3255 var line
3256 , el
3257 , i
3258 , j
3259 , ch
3260 , addToY;
3261
3262 if (x === this.cols && y === this.rows) {
3263 return;
3264 }
3265
3266 if (x < 1) x = 1;
3267 if (y < 1) y = 1;
3268
3269 // resize cols
3270 j = this.cols;
3271 if (j < x) {
3272 ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
3273 i = this.lines.length;
3274 while (i--) {
3275 while (this.lines[i].length < x) {
3276 this.lines[i].push(ch);
3277 }
3278 }
3279 } else { // (j > x)
3280 i = this.lines.length;
3281 while (i--) {
3282 while (this.lines[i].length > x) {
3283 this.lines[i].pop();
3284 }
3285 }
3286 }
3287 this.setupStops(j);
3288 this.cols = x;
3289
3290 // resize rows
3291 j = this.rows;
3292 addToY = 0;
3293 if (j < y) {
3294 el = this.element;
3295 while (j++ < y) {
3296 // y is rows, not this.y
3297 if (this.lines.length < y + this.ybase) {
3298 if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
3299 // There is room above the buffer and there are no empty elements below the line,
3300 // scroll up
3301 this.ybase--;
3302 addToY++
3303 if (this.ydisp > 0) {
3304 // Viewport is at the top of the buffer, must increase downwards
3305 this.ydisp--;
3306 }
3307 } else {
3308 // Add a blank line if there is no buffer left at the top to scroll to, or if there
3309 // are blank lines after the cursor
3310 this.lines.push(this.blankLine());
3311 }
3312 }
3313 if (this.children.length < y) {
3314 this.insertRow();
3315 }
3316 }
3317 } else { // (j > y)
3318 while (j-- > y) {
3319 if (this.lines.length > y + this.ybase) {
3320 if (this.lines.length > this.ybase + this.y + 1) {
3321 // The line is a blank line below the cursor, remove it
3322 this.lines.pop();
3323 } else {
3324 // The line is the cursor, scroll down
3325 this.ybase++;
3326 this.ydisp++;
3327 }
3328 }
3329 if (this.children.length > y) {
3330 el = this.children.shift();
3331 if (!el) continue;
3332 el.parentNode.removeChild(el);
3333 }
3334 }
3335 }
3336 this.rows = y;
3337
3338 /*
3339 * Make sure that the cursor stays on screen
3340 */
3341 if (this.y >= y) {
3342 this.y = y - 1;
3343 }
3344 if (addToY) {
3345 this.y += addToY;
3346 }
3347
3348 if (this.x >= x) {
3349 this.x = x - 1;
3350 }
3351
3352 this.scrollTop = 0;
3353 this.scrollBottom = y - 1;
3354
3355 this.refresh(0, this.rows - 1);
3356
3357 this.normal = null;
3358
3359 this.emit('resize', {terminal: this, cols: x, rows: y});
3360 };
3361
3362 /**
3363 * Updates the range of rows to refresh
3364 * @param {number} y The number of rows to refresh next.
3365 */
3366 Terminal.prototype.updateRange = function(y) {
3367 if (y < this.refreshStart) this.refreshStart = y;
3368 if (y > this.refreshEnd) this.refreshEnd = y;
3369 // if (y > this.refreshEnd) {
3370 // this.refreshEnd = y;
3371 // if (y > this.rows - 1) {
3372 // this.refreshEnd = this.rows - 1;
3373 // }
3374 // }
3375 };
3376
3377 /**
3378 * Set the range of refreshing to the maximyum value
3379 */
3380 Terminal.prototype.maxRange = function() {
3381 this.refreshStart = 0;
3382 this.refreshEnd = this.rows - 1;
3383 };
3384
3385
3386
3387 /**
3388 * Setup the tab stops.
3389 * @param {number} i
3390 */
3391 Terminal.prototype.setupStops = function(i) {
3392 if (i != null) {
3393 if (!this.tabs[i]) {
3394 i = this.prevStop(i);
3395 }
3396 } else {
3397 this.tabs = {};
3398 i = 0;
3399 }
3400
3401 for (; i < this.cols; i += 8) {
3402 this.tabs[i] = true;
3403 }
3404 };
3405
3406
3407 /**
3408 * Move the cursor to the previous tab stop from the given position (default is current).
3409 * @param {number} x The position to move the cursor to the previous tab stop.
3410 */
3411 Terminal.prototype.prevStop = function(x) {
3412 if (x == null) x = this.x;
3413 while (!this.tabs[--x] && x > 0);
3414 return x >= this.cols
3415 ? this.cols - 1
3416 : x < 0 ? 0 : x;
3417 };
3418
3419
3420 /**
3421 * Move the cursor one tab stop forward from the given position (default is current).
3422 * @param {number} x The position to move the cursor one tab stop forward.
3423 */
3424 Terminal.prototype.nextStop = function(x) {
3425 if (x == null) x = this.x;
3426 while (!this.tabs[++x] && x < this.cols);
3427 return x >= this.cols
3428 ? this.cols - 1
3429 : x < 0 ? 0 : x;
3430 };
3431
3432
3433 /**
3434 * Erase in the identified line everything from "x" to the end of the line (right).
3435 * @param {number} x The column from which to start erasing to the end of the line.
3436 * @param {number} y The line in which to operate.
3437 */
3438 Terminal.prototype.eraseRight = function(x, y) {
3439 var line = this.lines[this.ybase + y]
3440 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3441
3442
3443 for (; x < this.cols; x++) {
3444 line[x] = ch;
3445 }
3446
3447 this.updateRange(y);
3448 };
3449
3450
3451
3452 /**
3453 * Erase in the identified line everything from "x" to the start of the line (left).
3454 * @param {number} x The column from which to start erasing to the start of the line.
3455 * @param {number} y The line in which to operate.
3456 */
3457 Terminal.prototype.eraseLeft = function(x, y) {
3458 var line = this.lines[this.ybase + y]
3459 , ch = [this.eraseAttr(), ' ', 1]; // xterm
3460
3461 x++;
3462 while (x--) line[x] = ch;
3463
3464 this.updateRange(y);
3465 };
3466
3467
3468 /**
3469 * Erase all content in the given line
3470 * @param {number} y The line to erase all of its contents.
3471 */
3472 Terminal.prototype.eraseLine = function(y) {
3473 this.eraseRight(0, y);
3474 };
3475
3476
3477 /**
3478 * Return the data array of a blank line/
3479 * @param {number} cur First bunch of data for each "blank" character.
3480 */
3481 Terminal.prototype.blankLine = function(cur) {
3482 var attr = cur
3483 ? this.eraseAttr()
3484 : this.defAttr;
3485
3486 var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
3487 , line = []
3488 , i = 0;
3489
3490 for (; i < this.cols; i++) {
3491 line[i] = ch;
3492 }
3493
3494 return line;
3495 };
3496
3497
3498 /**
3499 * If cur return the back color xterm feature attribute. Else return defAttr.
3500 * @param {object} cur
3501 */
3502 Terminal.prototype.ch = function(cur) {
3503 return cur
3504 ? [this.eraseAttr(), ' ', 1]
3505 : [this.defAttr, ' ', 1];
3506 };
3507
3508
3509 /**
3510 * Evaluate if the current erminal is the given argument.
3511 * @param {object} term The terminal to evaluate
3512 */
3513 Terminal.prototype.is = function(term) {
3514 var name = this.termName;
3515 return (name + '').indexOf(term) === 0;
3516 };
3517
3518
3519 /**
3520 * Emit the 'data' event and populate the given data.
3521 * @param {string} data The data to populate in the event.
3522 */
3523 Terminal.prototype.handler = function(data) {
3524 this.emit('data', data);
3525 };
3526
3527
3528 /**
3529 * Emit the 'title' event and populate the given title.
3530 * @param {string} title The title to populate in the event.
3531 */
3532 Terminal.prototype.handleTitle = function(title) {
3533 this.emit('title', title);
3534 };
3535
3536
3537 /**
3538 * ESC
3539 */
3540
3541 /**
3542 * ESC D Index (IND is 0x84).
3543 */
3544 Terminal.prototype.index = function() {
3545 this.y++;
3546 if (this.y > this.scrollBottom) {
3547 this.y--;
3548 this.scroll();
3549 }
3550 this.state = normal;
3551 };
3552
3553
3554 /**
3555 * ESC M Reverse Index (RI is 0x8d).
3556 */
3557 Terminal.prototype.reverseIndex = function() {
3558 var j;
3559 this.y--;
3560 if (this.y < this.scrollTop) {
3561 this.y++;
3562 // possibly move the code below to term.reverseScroll();
3563 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
3564 // blankLine(true) is xterm/linux behavior
3565 this.lines.splice(this.y + this.ybase, 0, this.blankLine(true));
3566 j = this.rows - 1 - this.scrollBottom;
3567 this.lines.splice(this.rows - 1 + this.ybase - j + 1, 1);
3568 // this.maxRange();
3569 this.updateRange(this.scrollTop);
3570 this.updateRange(this.scrollBottom);
3571 }
3572 this.state = normal;
3573 };
3574
3575
3576 /**
3577 * ESC c Full Reset (RIS).
3578 */
3579 Terminal.prototype.reset = function() {
3580 this.options.rows = this.rows;
3581 this.options.cols = this.cols;
3582 var customKeydownHandler = this.customKeydownHandler;
3583 Terminal.call(this, this.options);
3584 this.customKeydownHandler = customKeydownHandler;
3585 this.refresh(0, this.rows - 1);
3586 };
3587
3588
3589 /**
3590 * ESC H Tab Set (HTS is 0x88).
3591 */
3592 Terminal.prototype.tabSet = function() {
3593 this.tabs[this.x] = true;
3594 this.state = normal;
3595 };
3596
3597
3598 /**
3599 * CSI
3600 */
3601
3602 /**
3603 * CSI Ps A
3604 * Cursor Up Ps Times (default = 1) (CUU).
3605 */
3606 Terminal.prototype.cursorUp = function(params) {
3607 var param = params[0];
3608 if (param < 1) param = 1;
3609 this.y -= param;
3610 if (this.y < 0) this.y = 0;
3611 };
3612
3613
3614 /**
3615 * CSI Ps B
3616 * Cursor Down Ps Times (default = 1) (CUD).
3617 */
3618 Terminal.prototype.cursorDown = function(params) {
3619 var param = params[0];
3620 if (param < 1) param = 1;
3621 this.y += param;
3622 if (this.y >= this.rows) {
3623 this.y = this.rows - 1;
3624 }
3625 };
3626
3627
3628 /**
3629 * CSI Ps C
3630 * Cursor Forward Ps Times (default = 1) (CUF).
3631 */
3632 Terminal.prototype.cursorForward = function(params) {
3633 var param = params[0];
3634 if (param < 1) param = 1;
3635 this.x += param;
3636 if (this.x >= this.cols) {
3637 this.x = this.cols - 1;
3638 }
3639 };
3640
3641
3642 /**
3643 * CSI Ps D
3644 * Cursor Backward Ps Times (default = 1) (CUB).
3645 */
3646 Terminal.prototype.cursorBackward = function(params) {
3647 var param = params[0];
3648 if (param < 1) param = 1;
3649 this.x -= param;
3650 if (this.x < 0) this.x = 0;
3651 };
3652
3653
3654 /**
3655 * CSI Ps ; Ps H
3656 * Cursor Position [row;column] (default = [1,1]) (CUP).
3657 */
3658 Terminal.prototype.cursorPos = function(params) {
3659 var row, col;
3660
3661 row = params[0] - 1;
3662
3663 if (params.length >= 2) {
3664 col = params[1] - 1;
3665 } else {
3666 col = 0;
3667 }
3668
3669 if (row < 0) {
3670 row = 0;
3671 } else if (row >= this.rows) {
3672 row = this.rows - 1;
3673 }
3674
3675 if (col < 0) {
3676 col = 0;
3677 } else if (col >= this.cols) {
3678 col = this.cols - 1;
3679 }
3680
3681 this.x = col;
3682 this.y = row;
3683 };
3684
3685
3686 /**
3687 * CSI Ps J Erase in Display (ED).
3688 * Ps = 0 -> Erase Below (default).
3689 * Ps = 1 -> Erase Above.
3690 * Ps = 2 -> Erase All.
3691 * Ps = 3 -> Erase Saved Lines (xterm).
3692 * CSI ? Ps J
3693 * Erase in Display (DECSED).
3694 * Ps = 0 -> Selective Erase Below (default).
3695 * Ps = 1 -> Selective Erase Above.
3696 * Ps = 2 -> Selective Erase All.
3697 */
3698 Terminal.prototype.eraseInDisplay = function(params) {
3699 var j;
3700 switch (params[0]) {
3701 case 0:
3702 this.eraseRight(this.x, this.y);
3703 j = this.y + 1;
3704 for (; j < this.rows; j++) {
3705 this.eraseLine(j);
3706 }
3707 break;
3708 case 1:
3709 this.eraseLeft(this.x, this.y);
3710 j = this.y;
3711 while (j--) {
3712 this.eraseLine(j);
3713 }
3714 break;
3715 case 2:
3716 j = this.rows;
3717 while (j--) this.eraseLine(j);
3718 break;
3719 case 3:
3720 ; // no saved lines
3721 break;
3722 }
3723 };
3724
3725
3726 /**
3727 * CSI Ps K Erase in Line (EL).
3728 * Ps = 0 -> Erase to Right (default).
3729 * Ps = 1 -> Erase to Left.
3730 * Ps = 2 -> Erase All.
3731 * CSI ? Ps K
3732 * Erase in Line (DECSEL).
3733 * Ps = 0 -> Selective Erase to Right (default).
3734 * Ps = 1 -> Selective Erase to Left.
3735 * Ps = 2 -> Selective Erase All.
3736 */
3737 Terminal.prototype.eraseInLine = function(params) {
3738 switch (params[0]) {
3739 case 0:
3740 this.eraseRight(this.x, this.y);
3741 break;
3742 case 1:
3743 this.eraseLeft(this.x, this.y);
3744 break;
3745 case 2:
3746 this.eraseLine(this.y);
3747 break;
3748 }
3749 };
3750
3751
3752 /**
3753 * CSI Pm m Character Attributes (SGR).
3754 * Ps = 0 -> Normal (default).
3755 * Ps = 1 -> Bold.
3756 * Ps = 4 -> Underlined.
3757 * Ps = 5 -> Blink (appears as Bold).
3758 * Ps = 7 -> Inverse.
3759 * Ps = 8 -> Invisible, i.e., hidden (VT300).
3760 * Ps = 2 2 -> Normal (neither bold nor faint).
3761 * Ps = 2 4 -> Not underlined.
3762 * Ps = 2 5 -> Steady (not blinking).
3763 * Ps = 2 7 -> Positive (not inverse).
3764 * Ps = 2 8 -> Visible, i.e., not hidden (VT300).
3765 * Ps = 3 0 -> Set foreground color to Black.
3766 * Ps = 3 1 -> Set foreground color to Red.
3767 * Ps = 3 2 -> Set foreground color to Green.
3768 * Ps = 3 3 -> Set foreground color to Yellow.
3769 * Ps = 3 4 -> Set foreground color to Blue.
3770 * Ps = 3 5 -> Set foreground color to Magenta.
3771 * Ps = 3 6 -> Set foreground color to Cyan.
3772 * Ps = 3 7 -> Set foreground color to White.
3773 * Ps = 3 9 -> Set foreground color to default (original).
3774 * Ps = 4 0 -> Set background color to Black.
3775 * Ps = 4 1 -> Set background color to Red.
3776 * Ps = 4 2 -> Set background color to Green.
3777 * Ps = 4 3 -> Set background color to Yellow.
3778 * Ps = 4 4 -> Set background color to Blue.
3779 * Ps = 4 5 -> Set background color to Magenta.
3780 * Ps = 4 6 -> Set background color to Cyan.
3781 * Ps = 4 7 -> Set background color to White.
3782 * Ps = 4 9 -> Set background color to default (original).
3783 *
3784 * If 16-color support is compiled, the following apply. Assume
3785 * that xterm's resources are set so that the ISO color codes are
3786 * the first 8 of a set of 16. Then the aixterm colors are the
3787 * bright versions of the ISO colors:
3788 * Ps = 9 0 -> Set foreground color to Black.
3789 * Ps = 9 1 -> Set foreground color to Red.
3790 * Ps = 9 2 -> Set foreground color to Green.
3791 * Ps = 9 3 -> Set foreground color to Yellow.
3792 * Ps = 9 4 -> Set foreground color to Blue.
3793 * Ps = 9 5 -> Set foreground color to Magenta.
3794 * Ps = 9 6 -> Set foreground color to Cyan.
3795 * Ps = 9 7 -> Set foreground color to White.
3796 * Ps = 1 0 0 -> Set background color to Black.
3797 * Ps = 1 0 1 -> Set background color to Red.
3798 * Ps = 1 0 2 -> Set background color to Green.
3799 * Ps = 1 0 3 -> Set background color to Yellow.
3800 * Ps = 1 0 4 -> Set background color to Blue.
3801 * Ps = 1 0 5 -> Set background color to Magenta.
3802 * Ps = 1 0 6 -> Set background color to Cyan.
3803 * Ps = 1 0 7 -> Set background color to White.
3804 *
3805 * If xterm is compiled with the 16-color support disabled, it
3806 * supports the following, from rxvt:
3807 * Ps = 1 0 0 -> Set foreground and background color to
3808 * default.
3809 *
3810 * If 88- or 256-color support is compiled, the following apply.
3811 * Ps = 3 8 ; 5 ; Ps -> Set foreground color to the second
3812 * Ps.
3813 * Ps = 4 8 ; 5 ; Ps -> Set background color to the second
3814 * Ps.
3815 */
3816 Terminal.prototype.charAttributes = function(params) {
3817 // Optimize a single SGR0.
3818 if (params.length === 1 && params[0] === 0) {
3819 this.curAttr = this.defAttr;
3820 return;
3821 }
3822
3823 var l = params.length
3824 , i = 0
3825 , flags = this.curAttr >> 18
3826 , fg = (this.curAttr >> 9) & 0x1ff
3827 , bg = this.curAttr & 0x1ff
3828 , p;
3829
3830 for (; i < l; i++) {
3831 p = params[i];
3832 if (p >= 30 && p <= 37) {
3833 // fg color 8
3834 fg = p - 30;
3835 } else if (p >= 40 && p <= 47) {
3836 // bg color 8
3837 bg = p - 40;
3838 } else if (p >= 90 && p <= 97) {
3839 // fg color 16
3840 p += 8;
3841 fg = p - 90;
3842 } else if (p >= 100 && p <= 107) {
3843 // bg color 16
3844 p += 8;
3845 bg = p - 100;
3846 } else if (p === 0) {
3847 // default
3848 flags = this.defAttr >> 18;
3849 fg = (this.defAttr >> 9) & 0x1ff;
3850 bg = this.defAttr & 0x1ff;
3851 // flags = 0;
3852 // fg = 0x1ff;
3853 // bg = 0x1ff;
3854 } else if (p === 1) {
3855 // bold text
3856 flags |= 1;
3857 } else if (p === 4) {
3858 // underlined text
3859 flags |= 2;
3860 } else if (p === 5) {
3861 // blink
3862 flags |= 4;
3863 } else if (p === 7) {
3864 // inverse and positive
3865 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
3866 flags |= 8;
3867 } else if (p === 8) {
3868 // invisible
3869 flags |= 16;
3870 } else if (p === 22) {
3871 // not bold
3872 flags &= ~1;
3873 } else if (p === 24) {
3874 // not underlined
3875 flags &= ~2;
3876 } else if (p === 25) {
3877 // not blink
3878 flags &= ~4;
3879 } else if (p === 27) {
3880 // not inverse
3881 flags &= ~8;
3882 } else if (p === 28) {
3883 // not invisible
3884 flags &= ~16;
3885 } else if (p === 39) {
3886 // reset fg
3887 fg = (this.defAttr >> 9) & 0x1ff;
3888 } else if (p === 49) {
3889 // reset bg
3890 bg = this.defAttr & 0x1ff;
3891 } else if (p === 38) {
3892 // fg color 256
3893 if (params[i + 1] === 2) {
3894 i += 2;
3895 fg = matchColor(
3896 params[i] & 0xff,
3897 params[i + 1] & 0xff,
3898 params[i + 2] & 0xff);
3899 if (fg === -1) fg = 0x1ff;
3900 i += 2;
3901 } else if (params[i + 1] === 5) {
3902 i += 2;
3903 p = params[i] & 0xff;
3904 fg = p;
3905 }
3906 } else if (p === 48) {
3907 // bg color 256
3908 if (params[i + 1] === 2) {
3909 i += 2;
3910 bg = matchColor(
3911 params[i] & 0xff,
3912 params[i + 1] & 0xff,
3913 params[i + 2] & 0xff);
3914 if (bg === -1) bg = 0x1ff;
3915 i += 2;
3916 } else if (params[i + 1] === 5) {
3917 i += 2;
3918 p = params[i] & 0xff;
3919 bg = p;
3920 }
3921 } else if (p === 100) {
3922 // reset fg/bg
3923 fg = (this.defAttr >> 9) & 0x1ff;
3924 bg = this.defAttr & 0x1ff;
3925 } else {
3926 this.error('Unknown SGR attribute: %d.', p);
3927 }
3928 }
3929
3930 this.curAttr = (flags << 18) | (fg << 9) | bg;
3931 };
3932
3933
3934 /**
3935 * CSI Ps n Device Status Report (DSR).
3936 * Ps = 5 -> Status Report. Result (``OK'') is
3937 * CSI 0 n
3938 * Ps = 6 -> Report Cursor Position (CPR) [row;column].
3939 * Result is
3940 * CSI r ; c R
3941 * CSI ? Ps n
3942 * Device Status Report (DSR, DEC-specific).
3943 * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
3944 * ? r ; c R (assumes page is zero).
3945 * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
3946 * or CSI ? 1 1 n (not ready).
3947 * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
3948 * or CSI ? 2 1 n (locked).
3949 * Ps = 2 6 -> Report Keyboard status as
3950 * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
3951 * The last two parameters apply to VT400 & up, and denote key-
3952 * board ready and LK01 respectively.
3953 * Ps = 5 3 -> Report Locator status as
3954 * CSI ? 5 3 n Locator available, if compiled-in, or
3955 * CSI ? 5 0 n No Locator, if not.
3956 */
3957 Terminal.prototype.deviceStatus = function(params) {
3958 if (!this.prefix) {
3959 switch (params[0]) {
3960 case 5:
3961 // status report
3962 this.send('\x1b[0n');
3963 break;
3964 case 6:
3965 // cursor position
3966 this.send('\x1b['
3967 + (this.y + 1)
3968 + ';'
3969 + (this.x + 1)
3970 + 'R');
3971 break;
3972 }
3973 } else if (this.prefix === '?') {
3974 // modern xterm doesnt seem to
3975 // respond to any of these except ?6, 6, and 5
3976 switch (params[0]) {
3977 case 6:
3978 // cursor position
3979 this.send('\x1b[?'
3980 + (this.y + 1)
3981 + ';'
3982 + (this.x + 1)
3983 + 'R');
3984 break;
3985 case 15:
3986 // no printer
3987 // this.send('\x1b[?11n');
3988 break;
3989 case 25:
3990 // dont support user defined keys
3991 // this.send('\x1b[?21n');
3992 break;
3993 case 26:
3994 // north american keyboard
3995 // this.send('\x1b[?27;1;0;0n');
3996 break;
3997 case 53:
3998 // no dec locator/mouse
3999 // this.send('\x1b[?50n');
4000 break;
4001 }
4002 }
4003 };
4004
4005
4006 /**
4007 * Additions
4008 */
4009
4010 /**
4011 * CSI Ps @
4012 * Insert Ps (Blank) Character(s) (default = 1) (ICH).
4013 */
4014 Terminal.prototype.insertChars = function(params) {
4015 var param, row, j, ch;
4016
4017 param = params[0];
4018 if (param < 1) param = 1;
4019
4020 row = this.y + this.ybase;
4021 j = this.x;
4022 ch = [this.eraseAttr(), ' ', 1]; // xterm
4023
4024 while (param-- && j < this.cols) {
4025 this.lines[row].splice(j++, 0, ch);
4026 this.lines[row].pop();
4027 }
4028 };
4029
4030 /**
4031 * CSI Ps E
4032 * Cursor Next Line Ps Times (default = 1) (CNL).
4033 * same as CSI Ps B ?
4034 */
4035 Terminal.prototype.cursorNextLine = function(params) {
4036 var param = params[0];
4037 if (param < 1) param = 1;
4038 this.y += param;
4039 if (this.y >= this.rows) {
4040 this.y = this.rows - 1;
4041 }
4042 this.x = 0;
4043 };
4044
4045
4046 /**
4047 * CSI Ps F
4048 * Cursor Preceding Line Ps Times (default = 1) (CNL).
4049 * reuse CSI Ps A ?
4050 */
4051 Terminal.prototype.cursorPrecedingLine = function(params) {
4052 var param = params[0];
4053 if (param < 1) param = 1;
4054 this.y -= param;
4055 if (this.y < 0) this.y = 0;
4056 this.x = 0;
4057 };
4058
4059
4060 /**
4061 * CSI Ps G
4062 * Cursor Character Absolute [column] (default = [row,1]) (CHA).
4063 */
4064 Terminal.prototype.cursorCharAbsolute = function(params) {
4065 var param = params[0];
4066 if (param < 1) param = 1;
4067 this.x = param - 1;
4068 };
4069
4070
4071 /**
4072 * CSI Ps L
4073 * Insert Ps Line(s) (default = 1) (IL).
4074 */
4075 Terminal.prototype.insertLines = function(params) {
4076 var param, row, j;
4077
4078 param = params[0];
4079 if (param < 1) param = 1;
4080 row = this.y + this.ybase;
4081
4082 j = this.rows - 1 - this.scrollBottom;
4083 j = this.rows - 1 + this.ybase - j + 1;
4084
4085 while (param--) {
4086 // test: echo -e '\e[44m\e[1L\e[0m'
4087 // blankLine(true) - xterm/linux behavior
4088 this.lines.splice(row, 0, this.blankLine(true));
4089 this.lines.splice(j, 1);
4090 }
4091
4092 // this.maxRange();
4093 this.updateRange(this.y);
4094 this.updateRange(this.scrollBottom);
4095 };
4096
4097
4098 /**
4099 * CSI Ps M
4100 * Delete Ps Line(s) (default = 1) (DL).
4101 */
4102 Terminal.prototype.deleteLines = function(params) {
4103 var param, row, j;
4104
4105 param = params[0];
4106 if (param < 1) param = 1;
4107 row = this.y + this.ybase;
4108
4109 j = this.rows - 1 - this.scrollBottom;
4110 j = this.rows - 1 + this.ybase - j;
4111
4112 while (param--) {
4113 // test: echo -e '\e[44m\e[1M\e[0m'
4114 // blankLine(true) - xterm/linux behavior
4115 this.lines.splice(j + 1, 0, this.blankLine(true));
4116 this.lines.splice(row, 1);
4117 }
4118
4119 // this.maxRange();
4120 this.updateRange(this.y);
4121 this.updateRange(this.scrollBottom);
4122 };
4123
4124
4125 /**
4126 * CSI Ps P
4127 * Delete Ps Character(s) (default = 1) (DCH).
4128 */
4129 Terminal.prototype.deleteChars = function(params) {
4130 var param, row, ch;
4131
4132 param = params[0];
4133 if (param < 1) param = 1;
4134
4135 row = this.y + this.ybase;
4136 ch = [this.eraseAttr(), ' ', 1]; // xterm
4137
4138 while (param--) {
4139 this.lines[row].splice(this.x, 1);
4140 this.lines[row].push(ch);
4141 }
4142 };
4143
4144 /**
4145 * CSI Ps X
4146 * Erase Ps Character(s) (default = 1) (ECH).
4147 */
4148 Terminal.prototype.eraseChars = function(params) {
4149 var param, row, j, ch;
4150
4151 param = params[0];
4152 if (param < 1) param = 1;
4153
4154 row = this.y + this.ybase;
4155 j = this.x;
4156 ch = [this.eraseAttr(), ' ', 1]; // xterm
4157
4158 while (param-- && j < this.cols) {
4159 this.lines[row][j++] = ch;
4160 }
4161 };
4162
4163 /**
4164 * CSI Pm ` Character Position Absolute
4165 * [column] (default = [row,1]) (HPA).
4166 */
4167 Terminal.prototype.charPosAbsolute = function(params) {
4168 var param = params[0];
4169 if (param < 1) param = 1;
4170 this.x = param - 1;
4171 if (this.x >= this.cols) {
4172 this.x = this.cols - 1;
4173 }
4174 };
4175
4176
4177 /**
4178 * 141 61 a * HPR -
4179 * Horizontal Position Relative
4180 * reuse CSI Ps C ?
4181 */
4182 Terminal.prototype.HPositionRelative = function(params) {
4183 var param = params[0];
4184 if (param < 1) param = 1;
4185 this.x += param;
4186 if (this.x >= this.cols) {
4187 this.x = this.cols - 1;
4188 }
4189 };
4190
4191
4192 /**
4193 * CSI Ps c Send Device Attributes (Primary DA).
4194 * Ps = 0 or omitted -> request attributes from terminal. The
4195 * response depends on the decTerminalID resource setting.
4196 * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
4197 * -> CSI ? 1 ; 0 c (``VT101 with No Options'')
4198 * -> CSI ? 6 c (``VT102'')
4199 * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
4200 * The VT100-style response parameters do not mean anything by
4201 * themselves. VT220 parameters do, telling the host what fea-
4202 * tures the terminal supports:
4203 * Ps = 1 -> 132-columns.
4204 * Ps = 2 -> Printer.
4205 * Ps = 6 -> Selective erase.
4206 * Ps = 8 -> User-defined keys.
4207 * Ps = 9 -> National replacement character sets.
4208 * Ps = 1 5 -> Technical characters.
4209 * Ps = 2 2 -> ANSI color, e.g., VT525.
4210 * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
4211 * CSI > Ps c
4212 * Send Device Attributes (Secondary DA).
4213 * Ps = 0 or omitted -> request the terminal's identification
4214 * code. The response depends on the decTerminalID resource set-
4215 * ting. It should apply only to VT220 and up, but xterm extends
4216 * this to VT100.
4217 * -> CSI > Pp ; Pv ; Pc c
4218 * where Pp denotes the terminal type
4219 * Pp = 0 -> ``VT100''.
4220 * Pp = 1 -> ``VT220''.
4221 * and Pv is the firmware version (for xterm, this was originally
4222 * the XFree86 patch number, starting with 95). In a DEC termi-
4223 * nal, Pc indicates the ROM cartridge registration number and is
4224 * always zero.
4225 * More information:
4226 * xterm/charproc.c - line 2012, for more information.
4227 * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
4228 */
4229 Terminal.prototype.sendDeviceAttributes = function(params) {
4230 if (params[0] > 0) return;
4231
4232 if (!this.prefix) {
4233 if (this.is('xterm')
4234 || this.is('rxvt-unicode')
4235 || this.is('screen')) {
4236 this.send('\x1b[?1;2c');
4237 } else if (this.is('linux')) {
4238 this.send('\x1b[?6c');
4239 }
4240 } else if (this.prefix === '>') {
4241 // xterm and urxvt
4242 // seem to spit this
4243 // out around ~370 times (?).
4244 if (this.is('xterm')) {
4245 this.send('\x1b[>0;276;0c');
4246 } else if (this.is('rxvt-unicode')) {
4247 this.send('\x1b[>85;95;0c');
4248 } else if (this.is('linux')) {
4249 // not supported by linux console.
4250 // linux console echoes parameters.
4251 this.send(params[0] + 'c');
4252 } else if (this.is('screen')) {
4253 this.send('\x1b[>83;40003;0c');
4254 }
4255 }
4256 };
4257
4258
4259 /**
4260 * CSI Pm d
4261 * Line Position Absolute [row] (default = [1,column]) (VPA).
4262 */
4263 Terminal.prototype.linePosAbsolute = function(params) {
4264 var param = params[0];
4265 if (param < 1) param = 1;
4266 this.y = param - 1;
4267 if (this.y >= this.rows) {
4268 this.y = this.rows - 1;
4269 }
4270 };
4271
4272
4273 /**
4274 * 145 65 e * VPR - Vertical Position Relative
4275 * reuse CSI Ps B ?
4276 */
4277 Terminal.prototype.VPositionRelative = function(params) {
4278 var param = params[0];
4279 if (param < 1) param = 1;
4280 this.y += param;
4281 if (this.y >= this.rows) {
4282 this.y = this.rows - 1;
4283 }
4284 };
4285
4286
4287 /**
4288 * CSI Ps ; Ps f
4289 * Horizontal and Vertical Position [row;column] (default =
4290 * [1,1]) (HVP).
4291 */
4292 Terminal.prototype.HVPosition = function(params) {
4293 if (params[0] < 1) params[0] = 1;
4294 if (params[1] < 1) params[1] = 1;
4295
4296 this.y = params[0] - 1;
4297 if (this.y >= this.rows) {
4298 this.y = this.rows - 1;
4299 }
4300
4301 this.x = params[1] - 1;
4302 if (this.x >= this.cols) {
4303 this.x = this.cols - 1;
4304 }
4305 };
4306
4307
4308 /**
4309 * CSI Pm h Set Mode (SM).
4310 * Ps = 2 -> Keyboard Action Mode (AM).
4311 * Ps = 4 -> Insert Mode (IRM).
4312 * Ps = 1 2 -> Send/receive (SRM).
4313 * Ps = 2 0 -> Automatic Newline (LNM).
4314 * CSI ? Pm h
4315 * DEC Private Mode Set (DECSET).
4316 * Ps = 1 -> Application Cursor Keys (DECCKM).
4317 * Ps = 2 -> Designate USASCII for character sets G0-G3
4318 * (DECANM), and set VT100 mode.
4319 * Ps = 3 -> 132 Column Mode (DECCOLM).
4320 * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
4321 * Ps = 5 -> Reverse Video (DECSCNM).
4322 * Ps = 6 -> Origin Mode (DECOM).
4323 * Ps = 7 -> Wraparound Mode (DECAWM).
4324 * Ps = 8 -> Auto-repeat Keys (DECARM).
4325 * Ps = 9 -> Send Mouse X & Y on button press. See the sec-
4326 * tion Mouse Tracking.
4327 * Ps = 1 0 -> Show toolbar (rxvt).
4328 * Ps = 1 2 -> Start Blinking Cursor (att610).
4329 * Ps = 1 8 -> Print form feed (DECPFF).
4330 * Ps = 1 9 -> Set print extent to full screen (DECPEX).
4331 * Ps = 2 5 -> Show Cursor (DECTCEM).
4332 * Ps = 3 0 -> Show scrollbar (rxvt).
4333 * Ps = 3 5 -> Enable font-shifting functions (rxvt).
4334 * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
4335 * Ps = 4 0 -> Allow 80 -> 132 Mode.
4336 * Ps = 4 1 -> more(1) fix (see curses resource).
4337 * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
4338 * RCM).
4339 * Ps = 4 4 -> Turn On Margin Bell.
4340 * Ps = 4 5 -> Reverse-wraparound Mode.
4341 * Ps = 4 6 -> Start Logging. This is normally disabled by a
4342 * compile-time option.
4343 * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
4344 * abled by the titeInhibit resource).
4345 * Ps = 6 6 -> Application keypad (DECNKM).
4346 * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
4347 * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
4348 * release. See the section Mouse Tracking.
4349 * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
4350 * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
4351 * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
4352 * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
4353 * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
4354 * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
4355 * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
4356 * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
4357 * (enables the eightBitInput resource).
4358 * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
4359 * Lock keys. (This enables the numLock resource).
4360 * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
4361 * enables the metaSendsEscape resource).
4362 * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
4363 * key.
4364 * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
4365 * enables the altSendsEscape resource).
4366 * Ps = 1 0 4 0 -> Keep selection even if not highlighted.
4367 * (This enables the keepSelection resource).
4368 * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
4369 * the selectToClipboard resource).
4370 * Ps = 1 0 4 2 -> Enable Urgency window manager hint when
4371 * Control-G is received. (This enables the bellIsUrgent
4372 * resource).
4373 * Ps = 1 0 4 3 -> Enable raising of the window when Control-G
4374 * is received. (enables the popOnBell resource).
4375 * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
4376 * disabled by the titeInhibit resource).
4377 * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
4378 * abled by the titeInhibit resource).
4379 * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
4380 * Screen Buffer, clearing it first. (This may be disabled by
4381 * the titeInhibit resource). This combines the effects of the 1
4382 * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
4383 * applications rather than the 4 7 mode.
4384 * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
4385 * Ps = 1 0 5 1 -> Set Sun function-key mode.
4386 * Ps = 1 0 5 2 -> Set HP function-key mode.
4387 * Ps = 1 0 5 3 -> Set SCO function-key mode.
4388 * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
4389 * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
4390 * Ps = 2 0 0 4 -> Set bracketed paste mode.
4391 * Modes:
4392 * http: *vt100.net/docs/vt220-rm/chapter4.html
4393 */
4394 Terminal.prototype.setMode = function(params) {
4395 if (typeof params === 'object') {
4396 var l = params.length
4397 , i = 0;
4398
4399 for (; i < l; i++) {
4400 this.setMode(params[i]);
4401 }
4402
4403 return;
4404 }
4405
4406 if (!this.prefix) {
4407 switch (params) {
4408 case 4:
4409 this.insertMode = true;
4410 break;
4411 case 20:
4412 //this.convertEol = true;
4413 break;
4414 }
4415 } else if (this.prefix === '?') {
4416 switch (params) {
4417 case 1:
4418 this.applicationCursor = true;
4419 break;
4420 case 2:
4421 this.setgCharset(0, Terminal.charsets.US);
4422 this.setgCharset(1, Terminal.charsets.US);
4423 this.setgCharset(2, Terminal.charsets.US);
4424 this.setgCharset(3, Terminal.charsets.US);
4425 // set VT100 mode here
4426 break;
4427 case 3: // 132 col mode
4428 this.savedCols = this.cols;
4429 this.resize(132, this.rows);
4430 break;
4431 case 6:
4432 this.originMode = true;
4433 break;
4434 case 7:
4435 this.wraparoundMode = true;
4436 break;
4437 case 12:
4438 // this.cursorBlink = true;
4439 break;
4440 case 66:
4441 this.log('Serial port requested application keypad.');
4442 this.applicationKeypad = true;
4443 this.viewport.setApplicationMode(true);
4444 break;
4445 case 9: // X10 Mouse
4446 // no release, no motion, no wheel, no modifiers.
4447 case 1000: // vt200 mouse
4448 // no motion.
4449 // no modifiers, except control on the wheel.
4450 case 1002: // button event mouse
4451 case 1003: // any event mouse
4452 // any event - sends motion events,
4453 // even if there is no button held down.
4454 this.x10Mouse = params === 9;
4455 this.vt200Mouse = params === 1000;
4456 this.normalMouse = params > 1000;
4457 this.mouseEvents = true;
4458 this.element.style.cursor = 'default';
4459 this.log('Binding to mouse events.');
4460 break;
4461 case 1004: // send focusin/focusout events
4462 // focusin: ^[[I
4463 // focusout: ^[[O
4464 this.sendFocus = true;
4465 break;
4466 case 1005: // utf8 ext mode mouse
4467 this.utfMouse = true;
4468 // for wide terminals
4469 // simply encodes large values as utf8 characters
4470 break;
4471 case 1006: // sgr ext mode mouse
4472 this.sgrMouse = true;
4473 // for wide terminals
4474 // does not add 32 to fields
4475 // press: ^[[<b;x;yM
4476 // release: ^[[<b;x;ym
4477 break;
4478 case 1015: // urxvt ext mode mouse
4479 this.urxvtMouse = true;
4480 // for wide terminals
4481 // numbers for fields
4482 // press: ^[[b;x;yM
4483 // motion: ^[[b;x;yT
4484 break;
4485 case 25: // show cursor
4486 this.cursorHidden = false;
4487 break;
4488 case 1049: // alt screen buffer cursor
4489 //this.saveCursor();
4490 ; // FALL-THROUGH
4491 case 47: // alt screen buffer
4492 case 1047: // alt screen buffer
4493 if (!this.normal) {
4494 var normal = {
4495 lines: this.lines,
4496 ybase: this.ybase,
4497 ydisp: this.ydisp,
4498 x: this.x,
4499 y: this.y,
4500 scrollTop: this.scrollTop,
4501 scrollBottom: this.scrollBottom,
4502 tabs: this.tabs
4503 // XXX save charset(s) here?
4504 // charset: this.charset,
4505 // glevel: this.glevel,
4506 // charsets: this.charsets
4507 };
4508 this.reset();
4509 this.normal = normal;
4510 this.showCursor();
4511 }
4512 break;
4513 }
4514 }
4515 };
4516
4517 /**
4518 * CSI Pm l Reset Mode (RM).
4519 * Ps = 2 -> Keyboard Action Mode (AM).
4520 * Ps = 4 -> Replace Mode (IRM).
4521 * Ps = 1 2 -> Send/receive (SRM).
4522 * Ps = 2 0 -> Normal Linefeed (LNM).
4523 * CSI ? Pm l
4524 * DEC Private Mode Reset (DECRST).
4525 * Ps = 1 -> Normal Cursor Keys (DECCKM).
4526 * Ps = 2 -> Designate VT52 mode (DECANM).
4527 * Ps = 3 -> 80 Column Mode (DECCOLM).
4528 * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
4529 * Ps = 5 -> Normal Video (DECSCNM).
4530 * Ps = 6 -> Normal Cursor Mode (DECOM).
4531 * Ps = 7 -> No Wraparound Mode (DECAWM).
4532 * Ps = 8 -> No Auto-repeat Keys (DECARM).
4533 * Ps = 9 -> Don't send Mouse X & Y on button press.
4534 * Ps = 1 0 -> Hide toolbar (rxvt).
4535 * Ps = 1 2 -> Stop Blinking Cursor (att610).
4536 * Ps = 1 8 -> Don't print form feed (DECPFF).
4537 * Ps = 1 9 -> Limit print to scrolling region (DECPEX).
4538 * Ps = 2 5 -> Hide Cursor (DECTCEM).
4539 * Ps = 3 0 -> Don't show scrollbar (rxvt).
4540 * Ps = 3 5 -> Disable font-shifting functions (rxvt).
4541 * Ps = 4 0 -> Disallow 80 -> 132 Mode.
4542 * Ps = 4 1 -> No more(1) fix (see curses resource).
4543 * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
4544 * NRCM).
4545 * Ps = 4 4 -> Turn Off Margin Bell.
4546 * Ps = 4 5 -> No Reverse-wraparound Mode.
4547 * Ps = 4 6 -> Stop Logging. (This is normally disabled by a
4548 * compile-time option).
4549 * Ps = 4 7 -> Use Normal Screen Buffer.
4550 * Ps = 6 6 -> Numeric keypad (DECNKM).
4551 * Ps = 6 7 -> Backarrow key sends delete (DECBKM).
4552 * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
4553 * release. See the section Mouse Tracking.
4554 * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
4555 * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
4556 * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
4557 * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
4558 * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
4559 * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
4560 * (rxvt).
4561 * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
4562 * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
4563 * the eightBitInput resource).
4564 * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
4565 * Lock keys. (This disables the numLock resource).
4566 * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
4567 * (This disables the metaSendsEscape resource).
4568 * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
4569 * Delete key.
4570 * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
4571 * (This disables the altSendsEscape resource).
4572 * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
4573 * (This disables the keepSelection resource).
4574 * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
4575 * the selectToClipboard resource).
4576 * Ps = 1 0 4 2 -> Disable Urgency window manager hint when
4577 * Control-G is received. (This disables the bellIsUrgent
4578 * resource).
4579 * Ps = 1 0 4 3 -> Disable raising of the window when Control-
4580 * G is received. (This disables the popOnBell resource).
4581 * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
4582 * first if in the Alternate Screen. (This may be disabled by
4583 * the titeInhibit resource).
4584 * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
4585 * disabled by the titeInhibit resource).
4586 * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
4587 * as in DECRC. (This may be disabled by the titeInhibit
4588 * resource). This combines the effects of the 1 0 4 7 and 1 0
4589 * 4 8 modes. Use this with terminfo-based applications rather
4590 * than the 4 7 mode.
4591 * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
4592 * Ps = 1 0 5 1 -> Reset Sun function-key mode.
4593 * Ps = 1 0 5 2 -> Reset HP function-key mode.
4594 * Ps = 1 0 5 3 -> Reset SCO function-key mode.
4595 * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
4596 * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
4597 * Ps = 2 0 0 4 -> Reset bracketed paste mode.
4598 */
4599 Terminal.prototype.resetMode = function(params) {
4600 if (typeof params === 'object') {
4601 var l = params.length
4602 , i = 0;
4603
4604 for (; i < l; i++) {
4605 this.resetMode(params[i]);
4606 }
4607
4608 return;
4609 }
4610
4611 if (!this.prefix) {
4612 switch (params) {
4613 case 4:
4614 this.insertMode = false;
4615 break;
4616 case 20:
4617 //this.convertEol = false;
4618 break;
4619 }
4620 } else if (this.prefix === '?') {
4621 switch (params) {
4622 case 1:
4623 this.applicationCursor = false;
4624 break;
4625 case 3:
4626 if (this.cols === 132 && this.savedCols) {
4627 this.resize(this.savedCols, this.rows);
4628 }
4629 delete this.savedCols;
4630 break;
4631 case 6:
4632 this.originMode = false;
4633 break;
4634 case 7:
4635 this.wraparoundMode = false;
4636 break;
4637 case 12:
4638 // this.cursorBlink = false;
4639 break;
4640 case 66:
4641 this.log('Switching back to normal keypad.');
4642 this.viewport.setApplicationMode(false);
4643 this.applicationKeypad = false;
4644 break;
4645 case 9: // X10 Mouse
4646 case 1000: // vt200 mouse
4647 case 1002: // button event mouse
4648 case 1003: // any event mouse
4649 this.x10Mouse = false;
4650 this.vt200Mouse = false;
4651 this.normalMouse = false;
4652 this.mouseEvents = false;
4653 this.element.style.cursor = '';
4654 break;
4655 case 1004: // send focusin/focusout events
4656 this.sendFocus = false;
4657 break;
4658 case 1005: // utf8 ext mode mouse
4659 this.utfMouse = false;
4660 break;
4661 case 1006: // sgr ext mode mouse
4662 this.sgrMouse = false;
4663 break;
4664 case 1015: // urxvt ext mode mouse
4665 this.urxvtMouse = false;
4666 break;
4667 case 25: // hide cursor
4668 this.cursorHidden = true;
4669 break;
4670 case 1049: // alt screen buffer cursor
4671 ; // FALL-THROUGH
4672 case 47: // normal screen buffer
4673 case 1047: // normal screen buffer - clearing it first
4674 if (this.normal) {
4675 this.lines = this.normal.lines;
4676 this.ybase = this.normal.ybase;
4677 this.ydisp = this.normal.ydisp;
4678 this.x = this.normal.x;
4679 this.y = this.normal.y;
4680 this.scrollTop = this.normal.scrollTop;
4681 this.scrollBottom = this.normal.scrollBottom;
4682 this.tabs = this.normal.tabs;
4683 this.normal = null;
4684 // if (params === 1049) {
4685 // this.x = this.savedX;
4686 // this.y = this.savedY;
4687 // }
4688 this.refresh(0, this.rows - 1);
4689 this.showCursor();
4690 }
4691 break;
4692 }
4693 }
4694 };
4695
4696
4697 /**
4698 * CSI Ps ; Ps r
4699 * Set Scrolling Region [top;bottom] (default = full size of win-
4700 * dow) (DECSTBM).
4701 * CSI ? Pm r
4702 */
4703 Terminal.prototype.setScrollRegion = function(params) {
4704 if (this.prefix) return;
4705 this.scrollTop = (params[0] || 1) - 1;
4706 this.scrollBottom = (params[1] || this.rows) - 1;
4707 this.x = 0;
4708 this.y = 0;
4709 };
4710
4711
4712 /**
4713 * CSI s
4714 * Save cursor (ANSI.SYS).
4715 */
4716 Terminal.prototype.saveCursor = function(params) {
4717 this.savedX = this.x;
4718 this.savedY = this.y;
4719 };
4720
4721
4722 /**
4723 * CSI u
4724 * Restore cursor (ANSI.SYS).
4725 */
4726 Terminal.prototype.restoreCursor = function(params) {
4727 this.x = this.savedX || 0;
4728 this.y = this.savedY || 0;
4729 };
4730
4731
4732 /**
4733 * Lesser Used
4734 */
4735
4736 /**
4737 * CSI Ps I
4738 * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
4739 */
4740 Terminal.prototype.cursorForwardTab = function(params) {
4741 var param = params[0] || 1;
4742 while (param--) {
4743 this.x = this.nextStop();
4744 }
4745 };
4746
4747
4748 /**
4749 * CSI Ps S Scroll up Ps lines (default = 1) (SU).
4750 */
4751 Terminal.prototype.scrollUp = function(params) {
4752 var param = params[0] || 1;
4753 while (param--) {
4754 this.lines.splice(this.ybase + this.scrollTop, 1);
4755 this.lines.splice(this.ybase + this.scrollBottom, 0, this.blankLine());
4756 }
4757 // this.maxRange();
4758 this.updateRange(this.scrollTop);
4759 this.updateRange(this.scrollBottom);
4760 };
4761
4762
4763 /**
4764 * CSI Ps T Scroll down Ps lines (default = 1) (SD).
4765 */
4766 Terminal.prototype.scrollDown = function(params) {
4767 var param = params[0] || 1;
4768 while (param--) {
4769 this.lines.splice(this.ybase + this.scrollBottom, 1);
4770 this.lines.splice(this.ybase + this.scrollTop, 0, this.blankLine());
4771 }
4772 // this.maxRange();
4773 this.updateRange(this.scrollTop);
4774 this.updateRange(this.scrollBottom);
4775 };
4776
4777
4778 /**
4779 * CSI Ps ; Ps ; Ps ; Ps ; Ps T
4780 * Initiate highlight mouse tracking. Parameters are
4781 * [func;startx;starty;firstrow;lastrow]. See the section Mouse
4782 * Tracking.
4783 */
4784 Terminal.prototype.initMouseTracking = function(params) {
4785 // Relevant: DECSET 1001
4786 };
4787
4788
4789 /**
4790 * CSI > Ps; Ps T
4791 * Reset one or more features of the title modes to the default
4792 * value. Normally, "reset" disables the feature. It is possi-
4793 * ble to disable the ability to reset features by compiling a
4794 * different default for the title modes into xterm.
4795 * Ps = 0 -> Do not set window/icon labels using hexadecimal.
4796 * Ps = 1 -> Do not query window/icon labels using hexadeci-
4797 * mal.
4798 * Ps = 2 -> Do not set window/icon labels using UTF-8.
4799 * Ps = 3 -> Do not query window/icon labels using UTF-8.
4800 * (See discussion of "Title Modes").
4801 */
4802 Terminal.prototype.resetTitleModes = function(params) {
4803 ;
4804 };
4805
4806
4807 /**
4808 * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
4809 */
4810 Terminal.prototype.cursorBackwardTab = function(params) {
4811 var param = params[0] || 1;
4812 while (param--) {
4813 this.x = this.prevStop();
4814 }
4815 };
4816
4817
4818 /**
4819 * CSI Ps b Repeat the preceding graphic character Ps times (REP).
4820 */
4821 Terminal.prototype.repeatPrecedingCharacter = function(params) {
4822 var param = params[0] || 1
4823 , line = this.lines[this.ybase + this.y]
4824 , ch = line[this.x - 1] || [this.defAttr, ' ', 1];
4825
4826 while (param--) line[this.x++] = ch;
4827 };
4828
4829
4830 /**
4831 * CSI Ps g Tab Clear (TBC).
4832 * Ps = 0 -> Clear Current Column (default).
4833 * Ps = 3 -> Clear All.
4834 * Potentially:
4835 * Ps = 2 -> Clear Stops on Line.
4836 * http://vt100.net/annarbor/aaa-ug/section6.html
4837 */
4838 Terminal.prototype.tabClear = function(params) {
4839 var param = params[0];
4840 if (param <= 0) {
4841 delete this.tabs[this.x];
4842 } else if (param === 3) {
4843 this.tabs = {};
4844 }
4845 };
4846
4847
4848 /**
4849 * CSI Pm i Media Copy (MC).
4850 * Ps = 0 -> Print screen (default).
4851 * Ps = 4 -> Turn off printer controller mode.
4852 * Ps = 5 -> Turn on printer controller mode.
4853 * CSI ? Pm i
4854 * Media Copy (MC, DEC-specific).
4855 * Ps = 1 -> Print line containing cursor.
4856 * Ps = 4 -> Turn off autoprint mode.
4857 * Ps = 5 -> Turn on autoprint mode.
4858 * Ps = 1 0 -> Print composed display, ignores DECPEX.
4859 * Ps = 1 1 -> Print all pages.
4860 */
4861 Terminal.prototype.mediaCopy = function(params) {
4862 ;
4863 };
4864
4865
4866 /**
4867 * CSI > Ps; Ps m
4868 * Set or reset resource-values used by xterm to decide whether
4869 * to construct escape sequences holding information about the
4870 * modifiers pressed with a given key. The first parameter iden-
4871 * tifies the resource to set/reset. The second parameter is the
4872 * value to assign to the resource. If the second parameter is
4873 * omitted, the resource is reset to its initial value.
4874 * Ps = 1 -> modifyCursorKeys.
4875 * Ps = 2 -> modifyFunctionKeys.
4876 * Ps = 4 -> modifyOtherKeys.
4877 * If no parameters are given, all resources are reset to their
4878 * initial values.
4879 */
4880 Terminal.prototype.setResources = function(params) {
4881 ;
4882 };
4883
4884
4885 /**
4886 * CSI > Ps n
4887 * Disable modifiers which may be enabled via the CSI > Ps; Ps m
4888 * sequence. This corresponds to a resource value of "-1", which
4889 * cannot be set with the other sequence. The parameter identi-
4890 * fies the resource to be disabled:
4891 * Ps = 1 -> modifyCursorKeys.
4892 * Ps = 2 -> modifyFunctionKeys.
4893 * Ps = 4 -> modifyOtherKeys.
4894 * If the parameter is omitted, modifyFunctionKeys is disabled.
4895 * When modifyFunctionKeys is disabled, xterm uses the modifier
4896 * keys to make an extended sequence of functions rather than
4897 * adding a parameter to each function key to denote the modi-
4898 * fiers.
4899 */
4900 Terminal.prototype.disableModifiers = function(params) {
4901 ;
4902 };
4903
4904
4905 /**
4906 * CSI > Ps p
4907 * Set resource value pointerMode. This is used by xterm to
4908 * decide whether to hide the pointer cursor as the user types.
4909 * Valid values for the parameter:
4910 * Ps = 0 -> never hide the pointer.
4911 * Ps = 1 -> hide if the mouse tracking mode is not enabled.
4912 * Ps = 2 -> always hide the pointer. If no parameter is
4913 * given, xterm uses the default, which is 1 .
4914 */
4915 Terminal.prototype.setPointerMode = function(params) {
4916 ;
4917 };
4918
4919
4920 /**
4921 * CSI ! p Soft terminal reset (DECSTR).
4922 * http://vt100.net/docs/vt220-rm/table4-10.html
4923 */
4924 Terminal.prototype.softReset = function(params) {
4925 this.cursorHidden = false;
4926 this.insertMode = false;
4927 this.originMode = false;
4928 this.wraparoundMode = false; // autowrap
4929 this.applicationKeypad = false; // ?
4930 this.applicationCursor = false;
4931 this.scrollTop = 0;
4932 this.scrollBottom = this.rows - 1;
4933 this.curAttr = this.defAttr;
4934 this.x = this.y = 0; // ?
4935 this.charset = null;
4936 this.glevel = 0; // ??
4937 this.charsets = [null]; // ??
4938 };
4939
4940
4941 /**
4942 * CSI Ps$ p
4943 * Request ANSI mode (DECRQM). For VT300 and up, reply is
4944 * CSI Ps; Pm$ y
4945 * where Ps is the mode number as in RM, and Pm is the mode
4946 * value:
4947 * 0 - not recognized
4948 * 1 - set
4949 * 2 - reset
4950 * 3 - permanently set
4951 * 4 - permanently reset
4952 */
4953 Terminal.prototype.requestAnsiMode = function(params) {
4954 ;
4955 };
4956
4957
4958 /**
4959 * CSI ? Ps$ p
4960 * Request DEC private mode (DECRQM). For VT300 and up, reply is
4961 * CSI ? Ps; Pm$ p
4962 * where Ps is the mode number as in DECSET, Pm is the mode value
4963 * as in the ANSI DECRQM.
4964 */
4965 Terminal.prototype.requestPrivateMode = function(params) {
4966 ;
4967 };
4968
4969
4970 /**
4971 * CSI Ps ; Ps " p
4972 * Set conformance level (DECSCL). Valid values for the first
4973 * parameter:
4974 * Ps = 6 1 -> VT100.
4975 * Ps = 6 2 -> VT200.
4976 * Ps = 6 3 -> VT300.
4977 * Valid values for the second parameter:
4978 * Ps = 0 -> 8-bit controls.
4979 * Ps = 1 -> 7-bit controls (always set for VT100).
4980 * Ps = 2 -> 8-bit controls.
4981 */
4982 Terminal.prototype.setConformanceLevel = function(params) {
4983 ;
4984 };
4985
4986
4987 /**
4988 * CSI Ps q Load LEDs (DECLL).
4989 * Ps = 0 -> Clear all LEDS (default).
4990 * Ps = 1 -> Light Num Lock.
4991 * Ps = 2 -> Light Caps Lock.
4992 * Ps = 3 -> Light Scroll Lock.
4993 * Ps = 2 1 -> Extinguish Num Lock.
4994 * Ps = 2 2 -> Extinguish Caps Lock.
4995 * Ps = 2 3 -> Extinguish Scroll Lock.
4996 */
4997 Terminal.prototype.loadLEDs = function(params) {
4998 ;
4999 };
5000
5001
5002 /**
5003 * CSI Ps SP q
5004 * Set cursor style (DECSCUSR, VT520).
5005 * Ps = 0 -> blinking block.
5006 * Ps = 1 -> blinking block (default).
5007 * Ps = 2 -> steady block.
5008 * Ps = 3 -> blinking underline.
5009 * Ps = 4 -> steady underline.
5010 */
5011 Terminal.prototype.setCursorStyle = function(params) {
5012 ;
5013 };
5014
5015
5016 /**
5017 * CSI Ps " q
5018 * Select character protection attribute (DECSCA). Valid values
5019 * for the parameter:
5020 * Ps = 0 -> DECSED and DECSEL can erase (default).
5021 * Ps = 1 -> DECSED and DECSEL cannot erase.
5022 * Ps = 2 -> DECSED and DECSEL can erase.
5023 */
5024 Terminal.prototype.setCharProtectionAttr = function(params) {
5025 ;
5026 };
5027
5028
5029 /**
5030 * CSI ? Pm r
5031 * Restore DEC Private Mode Values. The value of Ps previously
5032 * saved is restored. Ps values are the same as for DECSET.
5033 */
5034 Terminal.prototype.restorePrivateValues = function(params) {
5035 ;
5036 };
5037
5038
5039 /**
5040 * CSI Pt; Pl; Pb; Pr; Ps$ r
5041 * Change Attributes in Rectangular Area (DECCARA), VT400 and up.
5042 * Pt; Pl; Pb; Pr denotes the rectangle.
5043 * Ps denotes the SGR attributes to change: 0, 1, 4, 5, 7.
5044 * NOTE: xterm doesn't enable this code by default.
5045 */
5046 Terminal.prototype.setAttrInRectangle = function(params) {
5047 var t = params[0]
5048 , l = params[1]
5049 , b = params[2]
5050 , r = params[3]
5051 , attr = params[4];
5052
5053 var line
5054 , i;
5055
5056 for (; t < b + 1; t++) {
5057 line = this.lines[this.ybase + t];
5058 for (i = l; i < r; i++) {
5059 line[i] = [attr, line[i][1]];
5060 }
5061 }
5062
5063 // this.maxRange();
5064 this.updateRange(params[0]);
5065 this.updateRange(params[2]);
5066 };
5067
5068
5069 /**
5070 * CSI Pc; Pt; Pl; Pb; Pr$ x
5071 * Fill Rectangular Area (DECFRA), VT420 and up.
5072 * Pc is the character to use.
5073 * Pt; Pl; Pb; Pr denotes the rectangle.
5074 * NOTE: xterm doesn't enable this code by default.
5075 */
5076 Terminal.prototype.fillRectangle = function(params) {
5077 var ch = params[0]
5078 , t = params[1]
5079 , l = params[2]
5080 , b = params[3]
5081 , r = params[4];
5082
5083 var line
5084 , i;
5085
5086 for (; t < b + 1; t++) {
5087 line = this.lines[this.ybase + t];
5088 for (i = l; i < r; i++) {
5089 line[i] = [line[i][0], String.fromCharCode(ch)];
5090 }
5091 }
5092
5093 // this.maxRange();
5094 this.updateRange(params[1]);
5095 this.updateRange(params[3]);
5096 };
5097
5098
5099 /**
5100 * CSI Ps ; Pu ' z
5101 * Enable Locator Reporting (DECELR).
5102 * Valid values for the first parameter:
5103 * Ps = 0 -> Locator disabled (default).
5104 * Ps = 1 -> Locator enabled.
5105 * Ps = 2 -> Locator enabled for one report, then disabled.
5106 * The second parameter specifies the coordinate unit for locator
5107 * reports.
5108 * Valid values for the second parameter:
5109 * Pu = 0 <- or omitted -> default to character cells.
5110 * Pu = 1 <- device physical pixels.
5111 * Pu = 2 <- character cells.
5112 */
5113 Terminal.prototype.enableLocatorReporting = function(params) {
5114 var val = params[0] > 0;
5115 //this.mouseEvents = val;
5116 //this.decLocator = val;
5117 };
5118
5119
5120 /**
5121 * CSI Pt; Pl; Pb; Pr$ z
5122 * Erase Rectangular Area (DECERA), VT400 and up.
5123 * Pt; Pl; Pb; Pr denotes the rectangle.
5124 * NOTE: xterm doesn't enable this code by default.
5125 */
5126 Terminal.prototype.eraseRectangle = function(params) {
5127 var t = params[0]
5128 , l = params[1]
5129 , b = params[2]
5130 , r = params[3];
5131
5132 var line
5133 , i
5134 , ch;
5135
5136 ch = [this.eraseAttr(), ' ', 1]; // xterm?
5137
5138 for (; t < b + 1; t++) {
5139 line = this.lines[this.ybase + t];
5140 for (i = l; i < r; i++) {
5141 line[i] = ch;
5142 }
5143 }
5144
5145 // this.maxRange();
5146 this.updateRange(params[0]);
5147 this.updateRange(params[2]);
5148 };
5149
5150
5151 /**
5152 * CSI P m SP }
5153 * Insert P s Column(s) (default = 1) (DECIC), VT420 and up.
5154 * NOTE: xterm doesn't enable this code by default.
5155 */
5156 Terminal.prototype.insertColumns = function() {
5157 var param = params[0]
5158 , l = this.ybase + this.rows
5159 , ch = [this.eraseAttr(), ' ', 1] // xterm?
5160 , i;
5161
5162 while (param--) {
5163 for (i = this.ybase; i < l; i++) {
5164 this.lines[i].splice(this.x + 1, 0, ch);
5165 this.lines[i].pop();
5166 }
5167 }
5168
5169 this.maxRange();
5170 };
5171
5172
5173 /**
5174 * CSI P m SP ~
5175 * Delete P s Column(s) (default = 1) (DECDC), VT420 and up
5176 * NOTE: xterm doesn't enable this code by default.
5177 */
5178 Terminal.prototype.deleteColumns = function() {
5179 var param = params[0]
5180 , l = this.ybase + this.rows
5181 , ch = [this.eraseAttr(), ' ', 1] // xterm?
5182 , i;
5183
5184 while (param--) {
5185 for (i = this.ybase; i < l; i++) {
5186 this.lines[i].splice(this.x, 1);
5187 this.lines[i].push(ch);
5188 }
5189 }
5190
5191 this.maxRange();
5192 };
5193
5194 /**
5195 * Character Sets
5196 */
5197
5198 Terminal.charsets = {};
5199
5200 // DEC Special Character and Line Drawing Set.
5201 // http://vt100.net/docs/vt102-ug/table5-13.html
5202 // A lot of curses apps use this if they see TERM=xterm.
5203 // testing: echo -e '\e(0a\e(B'
5204 // The xterm output sometimes seems to conflict with the
5205 // reference above. xterm seems in line with the reference
5206 // when running vttest however.
5207 // The table below now uses xterm's output from vttest.
5208 Terminal.charsets.SCLD = { // (0
5209 '`': '\u25c6', // '◆'
5210 'a': '\u2592', // '▒'
5211 'b': '\u0009', // '\t'
5212 'c': '\u000c', // '\f'
5213 'd': '\u000d', // '\r'
5214 'e': '\u000a', // '\n'
5215 'f': '\u00b0', // '°'
5216 'g': '\u00b1', // '±'
5217 'h': '\u2424', // '\u2424' (NL)
5218 'i': '\u000b', // '\v'
5219 'j': '\u2518', // '┘'
5220 'k': '\u2510', // '┐'
5221 'l': '\u250c', // '┌'
5222 'm': '\u2514', // '└'
5223 'n': '\u253c', // '┼'
5224 'o': '\u23ba', // '⎺'
5225 'p': '\u23bb', // '⎻'
5226 'q': '\u2500', // '─'
5227 'r': '\u23bc', // '⎼'
5228 's': '\u23bd', // '⎽'
5229 't': '\u251c', // '├'
5230 'u': '\u2524', // '┤'
5231 'v': '\u2534', // '┴'
5232 'w': '\u252c', // '┬'
5233 'x': '\u2502', // '│'
5234 'y': '\u2264', // '≤'
5235 'z': '\u2265', // '≥'
5236 '{': '\u03c0', // 'π'
5237 '|': '\u2260', // '≠'
5238 '}': '\u00a3', // '£'
5239 '~': '\u00b7' // '·'
5240 };
5241
5242 Terminal.charsets.UK = null; // (A
5243 Terminal.charsets.US = null; // (B (USASCII)
5244 Terminal.charsets.Dutch = null; // (4
5245 Terminal.charsets.Finnish = null; // (C or (5
5246 Terminal.charsets.French = null; // (R
5247 Terminal.charsets.FrenchCanadian = null; // (Q
5248 Terminal.charsets.German = null; // (K
5249 Terminal.charsets.Italian = null; // (Y
5250 Terminal.charsets.NorwegianDanish = null; // (E or (6
5251 Terminal.charsets.Spanish = null; // (Z
5252 Terminal.charsets.Swedish = null; // (H or (7
5253 Terminal.charsets.Swiss = null; // (=
5254 Terminal.charsets.ISOLatin = null; // /A
5255
5256 /**
5257 * Helpers
5258 */
5259
5260 function contains(el, arr) {
5261 for (var i = 0; i < arr.length; i += 1) {
5262 if (el === arr[i]) {
5263 return true;
5264 }
5265 }
5266 return false;
5267 }
5268
5269 function on(el, type, handler, capture) {
5270 if (!Array.isArray(el)) {
5271 el = [el];
5272 }
5273 el.forEach(function (element) {
5274 element.addEventListener(type, handler, capture || false);
5275 });
5276 }
5277
5278 function off(el, type, handler, capture) {
5279 el.removeEventListener(type, handler, capture || false);
5280 }
5281
5282 function cancel(ev, force) {
5283 if (!this.cancelEvents && !force) {
5284 return;
5285 }
5286 ev.preventDefault();
5287 ev.stopPropagation();
5288 return false;
5289 }
5290
5291 function inherits(child, parent) {
5292 function f() {
5293 this.constructor = child;
5294 }
5295 f.prototype = parent.prototype;
5296 child.prototype = new f;
5297 }
5298
5299 // if bold is broken, we can't
5300 // use it in the terminal.
5301 function isBoldBroken(document) {
5302 var body = document.getElementsByTagName('body')[0];
5303 var el = document.createElement('span');
5304 el.innerHTML = 'hello world';
5305 body.appendChild(el);
5306 var w1 = el.scrollWidth;
5307 el.style.fontWeight = 'bold';
5308 var w2 = el.scrollWidth;
5309 body.removeChild(el);
5310 return w1 !== w2;
5311 }
5312
5313 var String = this.String;
5314 var setTimeout = this.setTimeout;
5315 var setInterval = this.setInterval;
5316
5317 function indexOf(obj, el) {
5318 var i = obj.length;
5319 while (i--) {
5320 if (obj[i] === el) return i;
5321 }
5322 return -1;
5323 }
5324
5325 function isThirdLevelShift(term, ev) {
5326 var thirdLevelKey =
5327 (term.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
5328 (term.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
5329
5330 if (ev.type == 'keypress') {
5331 return thirdLevelKey;
5332 }
5333
5334 // Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
5335 return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
5336 }
5337
5338 function matchColor(r1, g1, b1) {
5339 var hash = (r1 << 16) | (g1 << 8) | b1;
5340
5341 if (matchColor._cache[hash] != null) {
5342 return matchColor._cache[hash];
5343 }
5344
5345 var ldiff = Infinity
5346 , li = -1
5347 , i = 0
5348 , c
5349 , r2
5350 , g2
5351 , b2
5352 , diff;
5353
5354 for (; i < Terminal.vcolors.length; i++) {
5355 c = Terminal.vcolors[i];
5356 r2 = c[0];
5357 g2 = c[1];
5358 b2 = c[2];
5359
5360 diff = matchColor.distance(r1, g1, b1, r2, g2, b2);
5361
5362 if (diff === 0) {
5363 li = i;
5364 break;
5365 }
5366
5367 if (diff < ldiff) {
5368 ldiff = diff;
5369 li = i;
5370 }
5371 }
5372
5373 return matchColor._cache[hash] = li;
5374 }
5375
5376 matchColor._cache = {};
5377
5378 // http://stackoverflow.com/questions/1633828
5379 matchColor.distance = function(r1, g1, b1, r2, g2, b2) {
5380 return Math.pow(30 * (r1 - r2), 2)
5381 + Math.pow(59 * (g1 - g2), 2)
5382 + Math.pow(11 * (b1 - b2), 2);
5383 };
5384
5385 function each(obj, iter, con) {
5386 if (obj.forEach) return obj.forEach(iter, con);
5387 for (var i = 0; i < obj.length; i++) {
5388 iter.call(con, obj[i], i, obj);
5389 }
5390 }
5391
5392 function keys(obj) {
5393 if (Object.keys) return Object.keys(obj);
5394 var key, keys = [];
5395 for (key in obj) {
5396 if (Object.prototype.hasOwnProperty.call(obj, key)) {
5397 keys.push(key);
5398 }
5399 }
5400 return keys;
5401 }
5402
5403 var wcwidth = (function(opts) {
5404 // extracted from https://www.cl.cam.ac.uk/%7Emgk25/ucs/wcwidth.c
5405 // combining characters
5406 var COMBINING = [
5407 [0x0300, 0x036F], [0x0483, 0x0486], [0x0488, 0x0489],
5408 [0x0591, 0x05BD], [0x05BF, 0x05BF], [0x05C1, 0x05C2],
5409 [0x05C4, 0x05C5], [0x05C7, 0x05C7], [0x0600, 0x0603],
5410 [0x0610, 0x0615], [0x064B, 0x065E], [0x0670, 0x0670],
5411 [0x06D6, 0x06E4], [0x06E7, 0x06E8], [0x06EA, 0x06ED],
5412 [0x070F, 0x070F], [0x0711, 0x0711], [0x0730, 0x074A],
5413 [0x07A6, 0x07B0], [0x07EB, 0x07F3], [0x0901, 0x0902],
5414 [0x093C, 0x093C], [0x0941, 0x0948], [0x094D, 0x094D],
5415 [0x0951, 0x0954], [0x0962, 0x0963], [0x0981, 0x0981],
5416 [0x09BC, 0x09BC], [0x09C1, 0x09C4], [0x09CD, 0x09CD],
5417 [0x09E2, 0x09E3], [0x0A01, 0x0A02], [0x0A3C, 0x0A3C],
5418 [0x0A41, 0x0A42], [0x0A47, 0x0A48], [0x0A4B, 0x0A4D],
5419 [0x0A70, 0x0A71], [0x0A81, 0x0A82], [0x0ABC, 0x0ABC],
5420 [0x0AC1, 0x0AC5], [0x0AC7, 0x0AC8], [0x0ACD, 0x0ACD],
5421 [0x0AE2, 0x0AE3], [0x0B01, 0x0B01], [0x0B3C, 0x0B3C],
5422 [0x0B3F, 0x0B3F], [0x0B41, 0x0B43], [0x0B4D, 0x0B4D],
5423 [0x0B56, 0x0B56], [0x0B82, 0x0B82], [0x0BC0, 0x0BC0],
5424 [0x0BCD, 0x0BCD], [0x0C3E, 0x0C40], [0x0C46, 0x0C48],
5425 [0x0C4A, 0x0C4D], [0x0C55, 0x0C56], [0x0CBC, 0x0CBC],
5426 [0x0CBF, 0x0CBF], [0x0CC6, 0x0CC6], [0x0CCC, 0x0CCD],
5427 [0x0CE2, 0x0CE3], [0x0D41, 0x0D43], [0x0D4D, 0x0D4D],
5428 [0x0DCA, 0x0DCA], [0x0DD2, 0x0DD4], [0x0DD6, 0x0DD6],
5429 [0x0E31, 0x0E31], [0x0E34, 0x0E3A], [0x0E47, 0x0E4E],
5430 [0x0EB1, 0x0EB1], [0x0EB4, 0x0EB9], [0x0EBB, 0x0EBC],
5431 [0x0EC8, 0x0ECD], [0x0F18, 0x0F19], [0x0F35, 0x0F35],
5432 [0x0F37, 0x0F37], [0x0F39, 0x0F39], [0x0F71, 0x0F7E],
5433 [0x0F80, 0x0F84], [0x0F86, 0x0F87], [0x0F90, 0x0F97],
5434 [0x0F99, 0x0FBC], [0x0FC6, 0x0FC6], [0x102D, 0x1030],
5435 [0x1032, 0x1032], [0x1036, 0x1037], [0x1039, 0x1039],
5436 [0x1058, 0x1059], [0x1160, 0x11FF], [0x135F, 0x135F],
5437 [0x1712, 0x1714], [0x1732, 0x1734], [0x1752, 0x1753],
5438 [0x1772, 0x1773], [0x17B4, 0x17B5], [0x17B7, 0x17BD],
5439 [0x17C6, 0x17C6], [0x17C9, 0x17D3], [0x17DD, 0x17DD],
5440 [0x180B, 0x180D], [0x18A9, 0x18A9], [0x1920, 0x1922],
5441 [0x1927, 0x1928], [0x1932, 0x1932], [0x1939, 0x193B],
5442 [0x1A17, 0x1A18], [0x1B00, 0x1B03], [0x1B34, 0x1B34],
5443 [0x1B36, 0x1B3A], [0x1B3C, 0x1B3C], [0x1B42, 0x1B42],
5444 [0x1B6B, 0x1B73], [0x1DC0, 0x1DCA], [0x1DFE, 0x1DFF],
5445 [0x200B, 0x200F], [0x202A, 0x202E], [0x2060, 0x2063],
5446 [0x206A, 0x206F], [0x20D0, 0x20EF], [0x302A, 0x302F],
5447 [0x3099, 0x309A], [0xA806, 0xA806], [0xA80B, 0xA80B],
5448 [0xA825, 0xA826], [0xFB1E, 0xFB1E], [0xFE00, 0xFE0F],
5449 [0xFE20, 0xFE23], [0xFEFF, 0xFEFF], [0xFFF9, 0xFFFB],
5450 [0x10A01, 0x10A03], [0x10A05, 0x10A06], [0x10A0C, 0x10A0F],
5451 [0x10A38, 0x10A3A], [0x10A3F, 0x10A3F], [0x1D167, 0x1D169],
5452 [0x1D173, 0x1D182], [0x1D185, 0x1D18B], [0x1D1AA, 0x1D1AD],
5453 [0x1D242, 0x1D244], [0xE0001, 0xE0001], [0xE0020, 0xE007F],
5454 [0xE0100, 0xE01EF]
5455 ];
5456 // binary search
5457 function bisearch(ucs) {
5458 var min = 0;
5459 var max = COMBINING.length - 1;
5460 var mid;
5461 if (ucs < COMBINING[0][0] || ucs > COMBINING[max][1])
5462 return false;
5463 while (max >= min) {
5464 mid = Math.floor((min + max) / 2);
5465 if (ucs > COMBINING[mid][1])
5466 min = mid + 1;
5467 else if (ucs < COMBINING[mid][0])
5468 max = mid - 1;
5469 else
5470 return true;
5471 }
5472 return false;
5473 }
5474 function wcwidth(ucs) {
5475 // test for 8-bit control characters
5476 if (ucs === 0)
5477 return opts.nul;
5478 if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0))
5479 return opts.control;
5480 // binary search in table of non-spacing characters
5481 if (bisearch(ucs))
5482 return 0;
5483 // if we arrive here, ucs is not a combining or C0/C1 control character
5484 return 1 +
5485 (
5486 ucs >= 0x1100 &&
5487 (
5488 ucs <= 0x115f || // Hangul Jamo init. consonants
5489 ucs == 0x2329 ||
5490 ucs == 0x232a ||
5491 (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) || // CJK..Yi
5492 (ucs >= 0xac00 && ucs <= 0xd7a3) || // Hangul Syllables
5493 (ucs >= 0xf900 && ucs <= 0xfaff) || // CJK Compat Ideographs
5494 (ucs >= 0xfe10 && ucs <= 0xfe19) || // Vertical forms
5495 (ucs >= 0xfe30 && ucs <= 0xfe6f) || // CJK Compat Forms
5496 (ucs >= 0xff00 && ucs <= 0xff60) || // Fullwidth Forms
5497 (ucs >= 0xffe0 && ucs <= 0xffe6) ||
5498 (ucs >= 0x20000 && ucs <= 0x2fffd) ||
5499 (ucs >= 0x30000 && ucs <= 0x3fffd)
5500 )
5501 );
5502 }
5503 return wcwidth;
5504 })({nul: 0, control: 0}); // configurable options
5505
5506 /**
5507 * Expose
5508 */
5509
5510 Terminal.EventEmitter = EventEmitter;
5511 Terminal.CompositionHelper = CompositionHelper;
5512 Terminal.Viewport = Viewport;
5513 Terminal.inherits = inherits;
5514
5515 /**
5516 * Adds an event listener to the terminal.
5517 *
5518 * @param {string} event The name of the event. TODO: Document all event types
5519 * @param {function} callback The function to call when the event is triggered.
5520 */
5521 Terminal.on = on;
5522 Terminal.off = off;
5523 Terminal.cancel = cancel;
5524
5525
5526 return Terminal;
5527 });