Debian Codegraph @

node/@xterm/xterm/src/common/InputHandler.ts

raw
1 /**
2 * Copyright (c) 2014 The xterm.js authors. All rights reserved.
3 * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
4 * @license MIT
5 */
6
7 import { IInputHandler, IAttributeData, IDisposable, IWindowOptions, IColorEvent, IParseStack, ColorIndex, ColorRequestType, SpecialColorIndex } from 'common/Types';
8 import { C0, C1 } from 'common/data/EscapeSequences';
9 import { CHARSETS, DEFAULT_CHARSET } from 'common/data/Charsets';
10 import { EscapeSequenceParser } from 'common/parser/EscapeSequenceParser';
11 import { Disposable } from 'vs/base/common/lifecycle';
12 import { StringToUtf32, stringFromCodePoint, Utf8ToUtf32 } from 'common/input/TextDecoder';
13 import { BufferLine, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
14 import { IParsingState, IEscapeSequenceParser, IParams, IFunctionIdentifier } from 'common/parser/Types';
15 import { NULL_CELL_CODE, NULL_CELL_WIDTH, Attributes, FgFlags, BgFlags, Content, UnderlineStyle } from 'common/buffer/Constants';
16 import { CellData } from 'common/buffer/CellData';
17 import { AttributeData } from 'common/buffer/AttributeData';
18 import { ICoreService, IBufferService, IOptionsService, ILogService, ICoreMouseService, ICharsetService, IUnicodeService, LogLevelEnum, IOscLinkService } from 'common/services/Services';
19 import { UnicodeService } from 'common/services/UnicodeService';
20 import { OscHandler } from 'common/parser/OscParser';
21 import { DcsHandler } from 'common/parser/DcsParser';
22 import { IBuffer } from 'common/buffer/Types';
23 import { parseColor } from 'common/input/XParseColor';
24 import { Emitter } from 'vs/base/common/event';
25
26 /**
27 * Map collect to glevel. Used in `selectCharset`.
28 */
29 const GLEVEL: { [key: string]: number } = { '(': 0, ')': 1, '*': 2, '+': 3, '-': 1, '.': 2 };
30
31 /**
32 * VT commands done by the parser - FIXME: move this to the parser?
33 */
34 // @vt: #Y ESC CSI "Control Sequence Introducer" "ESC [" "Start of a CSI sequence."
35 // @vt: #Y ESC OSC "Operating System Command" "ESC ]" "Start of an OSC sequence."
36 // @vt: #Y ESC DCS "Device Control String" "ESC P" "Start of a DCS sequence."
37 // @vt: #Y ESC ST "String Terminator" "ESC \" "Terminator used for string type sequences."
38 // @vt: #Y ESC PM "Privacy Message" "ESC ^" "Start of a privacy message."
39 // @vt: #Y ESC APC "Application Program Command" "ESC _" "Start of an APC sequence."
40 // @vt: #Y C1 CSI "Control Sequence Introducer" "\x9B" "Start of a CSI sequence."
41 // @vt: #Y C1 OSC "Operating System Command" "\x9D" "Start of an OSC sequence."
42 // @vt: #Y C1 DCS "Device Control String" "\x90" "Start of a DCS sequence."
43 // @vt: #Y C1 ST "String Terminator" "\x9C" "Terminator used for string type sequences."
44 // @vt: #Y C1 PM "Privacy Message" "\x9E" "Start of a privacy message."
45 // @vt: #Y C1 APC "Application Program Command" "\x9F" "Start of an APC sequence."
46 // @vt: #Y C0 NUL "Null" "\0, \x00" "NUL is ignored."
47 // @vt: #Y C0 ESC "Escape" "\e, \x1B" "Start of a sequence. Cancels any other sequence."
48
49 /**
50 * Document xterm VT features here that are currently unsupported
51 */
52 // @vt: #E[Supported via @xterm/addon-image.] DCS SIXEL "SIXEL Graphics" "DCS Ps ; Ps ; Ps ; q Pt ST" "Draw SIXEL image."
53 // @vt: #N DCS DECUDK "User Defined Keys" "DCS Ps ; Ps \| Pt ST" "Definitions for user-defined keys."
54 // @vt: #N DCS XTGETTCAP "Request Terminfo String" "DCS + q Pt ST" "Request Terminfo String."
55 // @vt: #N DCS XTSETTCAP "Set Terminfo Data" "DCS + p Pt ST" "Set Terminfo Data."
56 // @vt: #N OSC 1 "Set Icon Name" "OSC 1 ; Pt BEL" "Set icon name."
57
58 /**
59 * Max length of the UTF32 input buffer. Real memory consumption is 4 times higher.
60 */
61 const MAX_PARSEBUFFER_LENGTH = 131072;
62
63 /**
64 * Limit length of title and icon name stacks.
65 */
66 const STACK_LIMIT = 10;
67
68 // map params to window option
69 function paramToWindowOption(n: number, opts: IWindowOptions): boolean {
70 if (n > 24) {
71 return opts.setWinLines || false;
72 }
73 switch (n) {
74 case 1: return !!opts.restoreWin;
75 case 2: return !!opts.minimizeWin;
76 case 3: return !!opts.setWinPosition;
77 case 4: return !!opts.setWinSizePixels;
78 case 5: return !!opts.raiseWin;
79 case 6: return !!opts.lowerWin;
80 case 7: return !!opts.refreshWin;
81 case 8: return !!opts.setWinSizeChars;
82 case 9: return !!opts.maximizeWin;
83 case 10: return !!opts.fullscreenWin;
84 case 11: return !!opts.getWinState;
85 case 13: return !!opts.getWinPosition;
86 case 14: return !!opts.getWinSizePixels;
87 case 15: return !!opts.getScreenSizePixels;
88 case 16: return !!opts.getCellSizePixels;
89 case 18: return !!opts.getWinSizeChars;
90 case 19: return !!opts.getScreenSizeChars;
91 case 20: return !!opts.getIconTitle;
92 case 21: return !!opts.getWinTitle;
93 case 22: return !!opts.pushTitle;
94 case 23: return !!opts.popTitle;
95 case 24: return !!opts.setWinLines;
96 }
97 return false;
98 }
99
100 export enum WindowsOptionsReportType {
101 GET_WIN_SIZE_PIXELS = 0,
102 GET_CELL_SIZE_PIXELS = 1
103 }
104
105 // create a warning log if an async handler takes longer than the limit (in ms)
106 const SLOW_ASYNC_LIMIT = 5000;
107
108 // Work variables to avoid garbage collection
109 let $temp = 0;
110
111 /**
112 * The terminal's standard implementation of IInputHandler, this handles all
113 * input from the Parser.
114 *
115 * Refer to http://invisible-island.net/xterm/ctlseqs/ctlseqs.html to understand
116 * each function's header comment.
117 */
118 export class InputHandler extends Disposable implements IInputHandler {
119 private _parseBuffer: Uint32Array = new Uint32Array(4096);
120 private _stringDecoder: StringToUtf32 = new StringToUtf32();
121 private _utf8Decoder: Utf8ToUtf32 = new Utf8ToUtf32();
122 private _windowTitle = '';
123 private _iconName = '';
124 private _dirtyRowTracker: IDirtyRowTracker;
125 protected _windowTitleStack: string[] = [];
126 protected _iconNameStack: string[] = [];
127
128 private _curAttrData: IAttributeData = DEFAULT_ATTR_DATA.clone();
129 public getAttrData(): IAttributeData { return this._curAttrData; }
130 private _eraseAttrDataInternal: IAttributeData = DEFAULT_ATTR_DATA.clone();
131
132 private _activeBuffer: IBuffer;
133
134 private readonly _onRequestBell = this._register(new Emitter<void>());
135 public readonly onRequestBell = this._onRequestBell.event;
136 private readonly _onRequestRefreshRows = this._register(new Emitter<{ start: number, end: number } | undefined>());
137 public readonly onRequestRefreshRows = this._onRequestRefreshRows.event;
138 private readonly _onRequestReset = this._register(new Emitter<void>());
139 public readonly onRequestReset = this._onRequestReset.event;
140 private readonly _onRequestSendFocus = this._register(new Emitter<void>());
141 public readonly onRequestSendFocus = this._onRequestSendFocus.event;
142 private readonly _onRequestSyncScrollBar = this._register(new Emitter<void>());
143 public readonly onRequestSyncScrollBar = this._onRequestSyncScrollBar.event;
144 private readonly _onRequestWindowsOptionsReport = this._register(new Emitter<WindowsOptionsReportType>());
145 public readonly onRequestWindowsOptionsReport = this._onRequestWindowsOptionsReport.event;
146
147 private readonly _onA11yChar = this._register(new Emitter<string>());
148 public readonly onA11yChar = this._onA11yChar.event;
149 private readonly _onA11yTab = this._register(new Emitter<number>());
150 public readonly onA11yTab = this._onA11yTab.event;
151 private readonly _onCursorMove = this._register(new Emitter<void>());
152 public readonly onCursorMove = this._onCursorMove.event;
153 private readonly _onLineFeed = this._register(new Emitter<void>());
154 public readonly onLineFeed = this._onLineFeed.event;
155 private readonly _onScroll = this._register(new Emitter<number>());
156 public readonly onScroll = this._onScroll.event;
157 private readonly _onTitleChange = this._register(new Emitter<string>());
158 public readonly onTitleChange = this._onTitleChange.event;
159 private readonly _onColor = this._register(new Emitter<IColorEvent>());
160 public readonly onColor = this._onColor.event;
161
162 private _parseStack: IParseStack = {
163 paused: false,
164 cursorStartX: 0,
165 cursorStartY: 0,
166 decodedLength: 0,
167 position: 0
168 };
169
170 constructor(
171 private readonly _bufferService: IBufferService,
172 private readonly _charsetService: ICharsetService,
173 private readonly _coreService: ICoreService,
174 private readonly _logService: ILogService,
175 private readonly _optionsService: IOptionsService,
176 private readonly _oscLinkService: IOscLinkService,
177 private readonly _coreMouseService: ICoreMouseService,
178 private readonly _unicodeService: IUnicodeService,
179 private readonly _parser: IEscapeSequenceParser = new EscapeSequenceParser()
180 ) {
181 super();
182 this._register(this._parser);
183 this._dirtyRowTracker = new DirtyRowTracker(this._bufferService);
184
185 // Track properties used in performance critical code manually to avoid using slow getters
186 this._activeBuffer = this._bufferService.buffer;
187 this._register(this._bufferService.buffers.onBufferActivate(e => this._activeBuffer = e.activeBuffer));
188
189 /**
190 * custom fallback handlers
191 */
192 this._parser.setCsiHandlerFallback((ident, params) => {
193 this._logService.debug('Unknown CSI code: ', { identifier: this._parser.identToString(ident), params: params.toArray() });
194 });
195 this._parser.setEscHandlerFallback(ident => {
196 this._logService.debug('Unknown ESC code: ', { identifier: this._parser.identToString(ident) });
197 });
198 this._parser.setExecuteHandlerFallback(code => {
199 this._logService.debug('Unknown EXECUTE code: ', { code });
200 });
201 this._parser.setOscHandlerFallback((identifier, action, data) => {
202 this._logService.debug('Unknown OSC code: ', { identifier, action, data });
203 });
204 this._parser.setDcsHandlerFallback((ident, action, payload) => {
205 if (action === 'HOOK') {
206 payload = payload.toArray();
207 }
208 this._logService.debug('Unknown DCS code: ', { identifier: this._parser.identToString(ident), action, payload });
209 });
210
211 /**
212 * print handler
213 */
214 this._parser.setPrintHandler((data, start, end) => this.print(data, start, end));
215
216 /**
217 * CSI handler
218 */
219 this._parser.registerCsiHandler({ final: '@' }, params => this.insertChars(params));
220 this._parser.registerCsiHandler({ intermediates: ' ', final: '@' }, params => this.scrollLeft(params));
221 this._parser.registerCsiHandler({ final: 'A' }, params => this.cursorUp(params));
222 this._parser.registerCsiHandler({ intermediates: ' ', final: 'A' }, params => this.scrollRight(params));
223 this._parser.registerCsiHandler({ final: 'B' }, params => this.cursorDown(params));
224 this._parser.registerCsiHandler({ final: 'C' }, params => this.cursorForward(params));
225 this._parser.registerCsiHandler({ final: 'D' }, params => this.cursorBackward(params));
226 this._parser.registerCsiHandler({ final: 'E' }, params => this.cursorNextLine(params));
227 this._parser.registerCsiHandler({ final: 'F' }, params => this.cursorPrecedingLine(params));
228 this._parser.registerCsiHandler({ final: 'G' }, params => this.cursorCharAbsolute(params));
229 this._parser.registerCsiHandler({ final: 'H' }, params => this.cursorPosition(params));
230 this._parser.registerCsiHandler({ final: 'I' }, params => this.cursorForwardTab(params));
231 this._parser.registerCsiHandler({ final: 'J' }, params => this.eraseInDisplay(params, false));
232 this._parser.registerCsiHandler({ prefix: '?', final: 'J' }, params => this.eraseInDisplay(params, true));
233 this._parser.registerCsiHandler({ final: 'K' }, params => this.eraseInLine(params, false));
234 this._parser.registerCsiHandler({ prefix: '?', final: 'K' }, params => this.eraseInLine(params, true));
235 this._parser.registerCsiHandler({ final: 'L' }, params => this.insertLines(params));
236 this._parser.registerCsiHandler({ final: 'M' }, params => this.deleteLines(params));
237 this._parser.registerCsiHandler({ final: 'P' }, params => this.deleteChars(params));
238 this._parser.registerCsiHandler({ final: 'S' }, params => this.scrollUp(params));
239 this._parser.registerCsiHandler({ final: 'T' }, params => this.scrollDown(params));
240 this._parser.registerCsiHandler({ final: 'X' }, params => this.eraseChars(params));
241 this._parser.registerCsiHandler({ final: 'Z' }, params => this.cursorBackwardTab(params));
242 this._parser.registerCsiHandler({ final: '`' }, params => this.charPosAbsolute(params));
243 this._parser.registerCsiHandler({ final: 'a' }, params => this.hPositionRelative(params));
244 this._parser.registerCsiHandler({ final: 'b' }, params => this.repeatPrecedingCharacter(params));
245 this._parser.registerCsiHandler({ final: 'c' }, params => this.sendDeviceAttributesPrimary(params));
246 this._parser.registerCsiHandler({ prefix: '>', final: 'c' }, params => this.sendDeviceAttributesSecondary(params));
247 this._parser.registerCsiHandler({ final: 'd' }, params => this.linePosAbsolute(params));
248 this._parser.registerCsiHandler({ final: 'e' }, params => this.vPositionRelative(params));
249 this._parser.registerCsiHandler({ final: 'f' }, params => this.hVPosition(params));
250 this._parser.registerCsiHandler({ final: 'g' }, params => this.tabClear(params));
251 this._parser.registerCsiHandler({ final: 'h' }, params => this.setMode(params));
252 this._parser.registerCsiHandler({ prefix: '?', final: 'h' }, params => this.setModePrivate(params));
253 this._parser.registerCsiHandler({ final: 'l' }, params => this.resetMode(params));
254 this._parser.registerCsiHandler({ prefix: '?', final: 'l' }, params => this.resetModePrivate(params));
255 this._parser.registerCsiHandler({ final: 'm' }, params => this.charAttributes(params));
256 this._parser.registerCsiHandler({ final: 'n' }, params => this.deviceStatus(params));
257 this._parser.registerCsiHandler({ prefix: '?', final: 'n' }, params => this.deviceStatusPrivate(params));
258 this._parser.registerCsiHandler({ intermediates: '!', final: 'p' }, params => this.softReset(params));
259 this._parser.registerCsiHandler({ intermediates: ' ', final: 'q' }, params => this.setCursorStyle(params));
260 this._parser.registerCsiHandler({ final: 'r' }, params => this.setScrollRegion(params));
261 this._parser.registerCsiHandler({ final: 's' }, params => this.saveCursor(params));
262 this._parser.registerCsiHandler({ final: 't' }, params => this.windowOptions(params));
263 this._parser.registerCsiHandler({ final: 'u' }, params => this.restoreCursor(params));
264 this._parser.registerCsiHandler({ intermediates: '\'', final: '}' }, params => this.insertColumns(params));
265 this._parser.registerCsiHandler({ intermediates: '\'', final: '~' }, params => this.deleteColumns(params));
266 this._parser.registerCsiHandler({ intermediates: '"', final: 'q' }, params => this.selectProtected(params));
267 this._parser.registerCsiHandler({ intermediates: '$', final: 'p' }, params => this.requestMode(params, true));
268 this._parser.registerCsiHandler({ prefix: '?', intermediates: '$', final: 'p' }, params => this.requestMode(params, false));
269
270 /**
271 * execute handler
272 */
273 this._parser.setExecuteHandler(C0.BEL, () => this.bell());
274 this._parser.setExecuteHandler(C0.LF, () => this.lineFeed());
275 this._parser.setExecuteHandler(C0.VT, () => this.lineFeed());
276 this._parser.setExecuteHandler(C0.FF, () => this.lineFeed());
277 this._parser.setExecuteHandler(C0.CR, () => this.carriageReturn());
278 this._parser.setExecuteHandler(C0.BS, () => this.backspace());
279 this._parser.setExecuteHandler(C0.HT, () => this.tab());
280 this._parser.setExecuteHandler(C0.SO, () => this.shiftOut());
281 this._parser.setExecuteHandler(C0.SI, () => this.shiftIn());
282 // FIXME: What do to with missing? Old code just added those to print.
283
284 this._parser.setExecuteHandler(C1.IND, () => this.index());
285 this._parser.setExecuteHandler(C1.NEL, () => this.nextLine());
286 this._parser.setExecuteHandler(C1.HTS, () => this.tabSet());
287
288 /**
289 * OSC handler
290 */
291 // 0 - icon name + title
292 this._parser.registerOscHandler(0, new OscHandler(data => { this.setTitle(data); this.setIconName(data); return true; }));
293 // 1 - icon name
294 this._parser.registerOscHandler(1, new OscHandler(data => this.setIconName(data)));
295 // 2 - title
296 this._parser.registerOscHandler(2, new OscHandler(data => this.setTitle(data)));
297 // 3 - set property X in the form "prop=value"
298 // 4 - Change Color Number
299 this._parser.registerOscHandler(4, new OscHandler(data => this.setOrReportIndexedColor(data)));
300 // 5 - Change Special Color Number
301 // 6 - Enable/disable Special Color Number c
302 // 7 - current directory? (not in xterm spec, see https://gitlab.com/gnachman/iterm2/issues/3939)
303 // 8 - create hyperlink (not in xterm spec, see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)
304 this._parser.registerOscHandler(8, new OscHandler(data => this.setHyperlink(data)));
305 // 10 - Change VT100 text foreground color to Pt.
306 this._parser.registerOscHandler(10, new OscHandler(data => this.setOrReportFgColor(data)));
307 // 11 - Change VT100 text background color to Pt.
308 this._parser.registerOscHandler(11, new OscHandler(data => this.setOrReportBgColor(data)));
309 // 12 - Change text cursor color to Pt.
310 this._parser.registerOscHandler(12, new OscHandler(data => this.setOrReportCursorColor(data)));
311 // 13 - Change mouse foreground color to Pt.
312 // 14 - Change mouse background color to Pt.
313 // 15 - Change Tektronix foreground color to Pt.
314 // 16 - Change Tektronix background color to Pt.
315 // 17 - Change highlight background color to Pt.
316 // 18 - Change Tektronix cursor color to Pt.
317 // 19 - Change highlight foreground color to Pt.
318 // 46 - Change Log File to Pt.
319 // 50 - Set Font to Pt.
320 // 51 - reserved for Emacs shell.
321 // 52 - Manipulate Selection Data.
322 // 104 ; c - Reset Color Number c.
323 this._parser.registerOscHandler(104, new OscHandler(data => this.restoreIndexedColor(data)));
324 // 105 ; c - Reset Special Color Number c.
325 // 106 ; c; f - Enable/disable Special Color Number c.
326 // 110 - Reset VT100 text foreground color.
327 this._parser.registerOscHandler(110, new OscHandler(data => this.restoreFgColor(data)));
328 // 111 - Reset VT100 text background color.
329 this._parser.registerOscHandler(111, new OscHandler(data => this.restoreBgColor(data)));
330 // 112 - Reset text cursor color.
331 this._parser.registerOscHandler(112, new OscHandler(data => this.restoreCursorColor(data)));
332 // 113 - Reset mouse foreground color.
333 // 114 - Reset mouse background color.
334 // 115 - Reset Tektronix foreground color.
335 // 116 - Reset Tektronix background color.
336 // 117 - Reset highlight color.
337 // 118 - Reset Tektronix cursor color.
338 // 119 - Reset highlight foreground color.
339
340 /**
341 * ESC handlers
342 */
343 this._parser.registerEscHandler({ final: '7' }, () => this.saveCursor());
344 this._parser.registerEscHandler({ final: '8' }, () => this.restoreCursor());
345 this._parser.registerEscHandler({ final: 'D' }, () => this.index());
346 this._parser.registerEscHandler({ final: 'E' }, () => this.nextLine());
347 this._parser.registerEscHandler({ final: 'H' }, () => this.tabSet());
348 this._parser.registerEscHandler({ final: 'M' }, () => this.reverseIndex());
349 this._parser.registerEscHandler({ final: '=' }, () => this.keypadApplicationMode());
350 this._parser.registerEscHandler({ final: '>' }, () => this.keypadNumericMode());
351 this._parser.registerEscHandler({ final: 'c' }, () => this.fullReset());
352 this._parser.registerEscHandler({ final: 'n' }, () => this.setgLevel(2));
353 this._parser.registerEscHandler({ final: 'o' }, () => this.setgLevel(3));
354 this._parser.registerEscHandler({ final: '|' }, () => this.setgLevel(3));
355 this._parser.registerEscHandler({ final: '}' }, () => this.setgLevel(2));
356 this._parser.registerEscHandler({ final: '~' }, () => this.setgLevel(1));
357 this._parser.registerEscHandler({ intermediates: '%', final: '@' }, () => this.selectDefaultCharset());
358 this._parser.registerEscHandler({ intermediates: '%', final: 'G' }, () => this.selectDefaultCharset());
359 for (const flag in CHARSETS) {
360 this._parser.registerEscHandler({ intermediates: '(', final: flag }, () => this.selectCharset('(' + flag));
361 this._parser.registerEscHandler({ intermediates: ')', final: flag }, () => this.selectCharset(')' + flag));
362 this._parser.registerEscHandler({ intermediates: '*', final: flag }, () => this.selectCharset('*' + flag));
363 this._parser.registerEscHandler({ intermediates: '+', final: flag }, () => this.selectCharset('+' + flag));
364 this._parser.registerEscHandler({ intermediates: '-', final: flag }, () => this.selectCharset('-' + flag));
365 this._parser.registerEscHandler({ intermediates: '.', final: flag }, () => this.selectCharset('.' + flag));
366 this._parser.registerEscHandler({ intermediates: '/', final: flag }, () => this.selectCharset('/' + flag)); // TODO: supported?
367 }
368 this._parser.registerEscHandler({ intermediates: '#', final: '8' }, () => this.screenAlignmentPattern());
369
370 /**
371 * error handler
372 */
373 this._parser.setErrorHandler((state: IParsingState) => {
374 this._logService.error('Parsing error: ', state);
375 return state;
376 });
377
378 /**
379 * DCS handler
380 */
381 this._parser.registerDcsHandler({ intermediates: '$', final: 'q' }, new DcsHandler((data, params) => this.requestStatusString(data, params)));
382 }
383
384 /**
385 * Async parse support.
386 */
387 private _preserveStack(cursorStartX: number, cursorStartY: number, decodedLength: number, position: number): void {
388 this._parseStack.paused = true;
389 this._parseStack.cursorStartX = cursorStartX;
390 this._parseStack.cursorStartY = cursorStartY;
391 this._parseStack.decodedLength = decodedLength;
392 this._parseStack.position = position;
393 }
394
395 private _logSlowResolvingAsync(p: Promise<boolean>): void {
396 // log a limited warning about an async handler taking too long
397 if (this._logService.logLevel <= LogLevelEnum.WARN) {
398 Promise.race([p, new Promise((res, rej) => setTimeout(() => rej('#SLOW_TIMEOUT'), SLOW_ASYNC_LIMIT))])
399 .catch(err => {
400 if (err !== '#SLOW_TIMEOUT') {
401 throw err;
402 }
403 console.warn(`async parser handler taking longer than ${SLOW_ASYNC_LIMIT} ms`);
404 });
405 }
406 }
407
408 private _getCurrentLinkId(): number {
409 return this._curAttrData.extended.urlId;
410 }
411
412 /**
413 * Parse call with async handler support.
414 *
415 * Whether the stack state got preserved for the next call, is indicated by the return value:
416 * - undefined (void):
417 * all handlers were sync, no stack save, continue normally with next chunk
418 * - Promise\<boolean\>:
419 * execution stopped at async handler, stack saved, continue with same chunk and the promise
420 * resolve value as `promiseResult` until the method returns `undefined`
421 *
422 * Note: This method should only be called by `Terminal.write` to ensure correct execution order
423 * and proper continuation of async parser handlers.
424 */
425 public parse(data: string | Uint8Array, promiseResult?: boolean): void | Promise<boolean> {
426 let result: void | Promise<boolean>;
427 let cursorStartX = this._activeBuffer.x;
428 let cursorStartY = this._activeBuffer.y;
429 let start = 0;
430 const wasPaused = this._parseStack.paused;
431
432 if (wasPaused) {
433 // assumption: _parseBuffer never mutates between async calls
434 if (result = this._parser.parse(this._parseBuffer, this._parseStack.decodedLength, promiseResult)) {
435 this._logSlowResolvingAsync(result);
436 return result;
437 }
438 cursorStartX = this._parseStack.cursorStartX;
439 cursorStartY = this._parseStack.cursorStartY;
440 this._parseStack.paused = false;
441 if (data.length > MAX_PARSEBUFFER_LENGTH) {
442 start = this._parseStack.position + MAX_PARSEBUFFER_LENGTH;
443 }
444 }
445
446 // Log debug data, the log level gate is to prevent extra work in this hot path
447 if (this._logService.logLevel <= LogLevelEnum.DEBUG) {
448 this._logService.debug(`parsing data ${typeof data === 'string' ? ` "${data}"` : ` "${Array.prototype.map.call(data, e => String.fromCharCode(e)).join('')}"`}`);
449 }
450 if (this._logService.logLevel === LogLevelEnum.TRACE) {
451 this._logService.trace(`parsing data (codes)`, typeof data === 'string'
452 ? data.split('').map(e => e.charCodeAt(0))
453 : data
454 );
455 }
456
457 // resize input buffer if needed
458 if (this._parseBuffer.length < data.length) {
459 if (this._parseBuffer.length < MAX_PARSEBUFFER_LENGTH) {
460 this._parseBuffer = new Uint32Array(Math.min(data.length, MAX_PARSEBUFFER_LENGTH));
461 }
462 }
463
464 // Clear the dirty row service so we know which lines changed as a result of parsing
465 // Important: do not clear between async calls, otherwise we lost pending update information.
466 if (!wasPaused) {
467 this._dirtyRowTracker.clearRange();
468 }
469
470 // process big data in smaller chunks
471 if (data.length > MAX_PARSEBUFFER_LENGTH) {
472 for (let i = start; i < data.length; i += MAX_PARSEBUFFER_LENGTH) {
473 const end = i + MAX_PARSEBUFFER_LENGTH < data.length ? i + MAX_PARSEBUFFER_LENGTH : data.length;
474 const len = (typeof data === 'string')
475 ? this._stringDecoder.decode(data.substring(i, end), this._parseBuffer)
476 : this._utf8Decoder.decode(data.subarray(i, end), this._parseBuffer);
477 if (result = this._parser.parse(this._parseBuffer, len)) {
478 this._preserveStack(cursorStartX, cursorStartY, len, i);
479 this._logSlowResolvingAsync(result);
480 return result;
481 }
482 }
483 } else {
484 if (!wasPaused) {
485 const len = (typeof data === 'string')
486 ? this._stringDecoder.decode(data, this._parseBuffer)
487 : this._utf8Decoder.decode(data, this._parseBuffer);
488 if (result = this._parser.parse(this._parseBuffer, len)) {
489 this._preserveStack(cursorStartX, cursorStartY, len, 0);
490 this._logSlowResolvingAsync(result);
491 return result;
492 }
493 }
494 }
495
496 if (this._activeBuffer.x !== cursorStartX || this._activeBuffer.y !== cursorStartY) {
497 this._onCursorMove.fire();
498 }
499
500 // Refresh any dirty rows accumulated as part of parsing, fire only for rows within the
501 // _viewport_ which is relative to ydisp, not relative to ybase.
502 const viewportEnd = this._dirtyRowTracker.end + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
503 const viewportStart = this._dirtyRowTracker.start + (this._bufferService.buffer.ybase - this._bufferService.buffer.ydisp);
504 if (viewportStart < this._bufferService.rows) {
505 this._onRequestRefreshRows.fire({
506 start: Math.min(viewportStart, this._bufferService.rows - 1),
507 end: Math.min(viewportEnd, this._bufferService.rows - 1)
508 });
509 }
510 }
511
512 public print(data: Uint32Array, start: number, end: number): void {
513 let code: number;
514 let chWidth: number;
515 const charset = this._charsetService.charset;
516 const screenReaderMode = this._optionsService.rawOptions.screenReaderMode;
517 const cols = this._bufferService.cols;
518 const wraparoundMode = this._coreService.decPrivateModes.wraparound;
519 const insertMode = this._coreService.modes.insertMode;
520 const curAttr = this._curAttrData;
521 let bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;
522
523 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
524
525 // handle wide chars: reset start_cell-1 if we would overwrite the second cell of a wide char
526 if (this._activeBuffer.x && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x - 1) === 2) {
527 bufferRow.setCellFromCodepoint(this._activeBuffer.x - 1, 0, 1, curAttr);
528 }
529
530 let precedingJoinState = this._parser.precedingJoinState;
531 for (let pos = start; pos < end; ++pos) {
532 code = data[pos];
533
534 // get charset replacement character
535 // charset is only defined for ASCII, therefore we only
536 // search for an replacement char if code < 127
537 if (code < 127 && charset) {
538 const ch = charset[String.fromCharCode(code)];
539 if (ch) {
540 code = ch.charCodeAt(0);
541 }
542 }
543
544 const currentInfo = this._unicodeService.charProperties(code, precedingJoinState);
545 chWidth = UnicodeService.extractWidth(currentInfo);
546 const shouldJoin = UnicodeService.extractShouldJoin(currentInfo);
547 const oldWidth = shouldJoin ? UnicodeService.extractWidth(precedingJoinState) : 0;
548 precedingJoinState = currentInfo;
549
550 if (screenReaderMode) {
551 this._onA11yChar.fire(stringFromCodePoint(code));
552 }
553 if (this._getCurrentLinkId()) {
554 this._oscLinkService.addLineToLink(this._getCurrentLinkId(), this._activeBuffer.ybase + this._activeBuffer.y);
555 }
556
557 // goto next line if ch would overflow
558 // NOTE: To avoid costly width checks here,
559 // the terminal does not allow a cols < 2.
560 if (this._activeBuffer.x + chWidth - oldWidth > cols) {
561 // autowrap - DECAWM
562 // automatically wraps to the beginning of the next line
563 if (wraparoundMode) {
564 const oldRow = bufferRow;
565 let oldCol = this._activeBuffer.x - oldWidth;
566 this._activeBuffer.x = oldWidth;
567 this._activeBuffer.y++;
568 if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {
569 this._activeBuffer.y--;
570 this._bufferService.scroll(this._eraseAttrData(), true);
571 } else {
572 if (this._activeBuffer.y >= this._bufferService.rows) {
573 this._activeBuffer.y = this._bufferService.rows - 1;
574 }
575 // The line already exists (eg. the initial viewport), mark it as a
576 // wrapped line
577 this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = true;
578 }
579 // row changed, get it again
580 bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;
581 if (oldWidth > 0 && bufferRow instanceof BufferLine) {
582 // Combining character widens 1 column to 2.
583 // Move old character to next line.
584 bufferRow.copyCellsFrom(oldRow as BufferLine,
585 oldCol, 0, oldWidth, false);
586 }
587 // clear left over cells to the right
588 while (oldCol < cols) {
589 oldRow.setCellFromCodepoint(oldCol++, 0, 1, curAttr);
590 }
591 } else {
592 this._activeBuffer.x = cols - 1;
593 if (chWidth === 2) {
594 // FIXME: check for xterm behavior
595 // What to do here? We got a wide char that does not fit into last cell
596 continue;
597 }
598 }
599 }
600
601 // insert combining char at last cursor position
602 // this._activeBuffer.x should never be 0 for a combining char
603 // since they always follow a cell consuming char
604 // therefore we can test for this._activeBuffer.x to avoid overflow left
605 if (shouldJoin && this._activeBuffer.x) {
606 const offset = bufferRow.getWidth(this._activeBuffer.x - 1) ? 1 : 2;
607 // if empty cell after fullwidth, need to go 2 cells back
608 // it is save to step 2 cells back here
609 // since an empty cell is only set by fullwidth chars
610 bufferRow.addCodepointToCell(this._activeBuffer.x - offset,
611 code, chWidth);
612 for (let delta = chWidth - oldWidth; --delta >= 0;) {
613 bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);
614 }
615 continue;
616 }
617
618 // insert mode: move characters to right
619 if (insertMode) {
620 // right shift cells according to the width
621 bufferRow.insertCells(this._activeBuffer.x, chWidth - oldWidth, this._activeBuffer.getNullCell(curAttr));
622 // test last cell - since the last cell has only room for
623 // a halfwidth char any fullwidth shifted there is lost
624 // and will be set to empty cell
625 if (bufferRow.getWidth(cols - 1) === 2) {
626 bufferRow.setCellFromCodepoint(cols - 1, NULL_CELL_CODE, NULL_CELL_WIDTH, curAttr);
627 }
628 }
629
630 // write current char to buffer and advance cursor
631 bufferRow.setCellFromCodepoint(this._activeBuffer.x++, code, chWidth, curAttr);
632
633 // fullwidth char - also set next cell to placeholder stub and advance cursor
634 // for graphemes bigger than fullwidth we can simply loop to zero
635 // we already made sure above, that this._activeBuffer.x + chWidth will not overflow right
636 if (chWidth > 0) {
637 while (--chWidth) {
638 // other than a regular empty cell a cell following a wide char has no width
639 bufferRow.setCellFromCodepoint(this._activeBuffer.x++, 0, 0, curAttr);
640 }
641 }
642 }
643
644 this._parser.precedingJoinState = precedingJoinState;
645
646 // handle wide chars: reset cell to the right if it is second cell of a wide char
647 if (this._activeBuffer.x < cols && end - start > 0 && bufferRow.getWidth(this._activeBuffer.x) === 0 && !bufferRow.hasContent(this._activeBuffer.x)) {
648 bufferRow.setCellFromCodepoint(this._activeBuffer.x, 0, 1, curAttr);
649 }
650
651 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
652 }
653
654 /**
655 * Forward registerCsiHandler from parser.
656 */
657 public registerCsiHandler(id: IFunctionIdentifier, callback: (params: IParams) => boolean | Promise<boolean>): IDisposable {
658 if (id.final === 't' && !id.prefix && !id.intermediates) {
659 // security: always check whether window option is allowed
660 return this._parser.registerCsiHandler(id, params => {
661 if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {
662 return true;
663 }
664 return callback(params);
665 });
666 }
667 return this._parser.registerCsiHandler(id, callback);
668 }
669
670 /**
671 * Forward registerDcsHandler from parser.
672 */
673 public registerDcsHandler(id: IFunctionIdentifier, callback: (data: string, param: IParams) => boolean | Promise<boolean>): IDisposable {
674 return this._parser.registerDcsHandler(id, new DcsHandler(callback));
675 }
676
677 /**
678 * Forward registerEscHandler from parser.
679 */
680 public registerEscHandler(id: IFunctionIdentifier, callback: () => boolean | Promise<boolean>): IDisposable {
681 return this._parser.registerEscHandler(id, callback);
682 }
683
684 /**
685 * Forward registerOscHandler from parser.
686 */
687 public registerOscHandler(ident: number, callback: (data: string) => boolean | Promise<boolean>): IDisposable {
688 return this._parser.registerOscHandler(ident, new OscHandler(callback));
689 }
690
691 /**
692 * BEL
693 * Bell (Ctrl-G).
694 *
695 * @vt: #Y C0 BEL "Bell" "\a, \x07" "Ring the bell."
696 * The behavior of the bell is further customizable with `ITerminalOptions.bellStyle`
697 * and `ITerminalOptions.bellSound`.
698 */
699 public bell(): boolean {
700 this._onRequestBell.fire();
701 return true;
702 }
703
704 /**
705 * LF
706 * Line Feed or New Line (NL). (LF is Ctrl-J).
707 *
708 * @vt: #Y C0 LF "Line Feed" "\n, \x0A" "Move the cursor one row down, scrolling if needed."
709 * Scrolling is restricted to scroll margins and will only happen on the bottom line.
710 *
711 * @vt: #Y C0 VT "Vertical Tabulation" "\v, \x0B" "Treated as LF."
712 * @vt: #Y C0 FF "Form Feed" "\f, \x0C" "Treated as LF."
713 */
714 public lineFeed(): boolean {
715 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
716 if (this._optionsService.rawOptions.convertEol) {
717 this._activeBuffer.x = 0;
718 }
719 this._activeBuffer.y++;
720 if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {
721 this._activeBuffer.y--;
722 this._bufferService.scroll(this._eraseAttrData());
723 } else if (this._activeBuffer.y >= this._bufferService.rows) {
724 this._activeBuffer.y = this._bufferService.rows - 1;
725 } else {
726 // There was an explicit line feed (not just a carriage return), so clear the wrapped state of
727 // the line. This is particularly important on conpty/Windows where revisiting lines to
728 // reprint is common, especially on resize. Note that the windowsMode wrapped line heuristics
729 // can mess with this so windowsMode should be disabled, which is recommended on Windows build
730 // 21376 and above.
731 this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;
732 }
733 // If the end of the line is hit, prevent this action from wrapping around to the next line.
734 if (this._activeBuffer.x >= this._bufferService.cols) {
735 this._activeBuffer.x--;
736 }
737 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
738
739 this._onLineFeed.fire();
740 return true;
741 }
742
743 /**
744 * CR
745 * Carriage Return (Ctrl-M).
746 *
747 * @vt: #Y C0 CR "Carriage Return" "\r, \x0D" "Move the cursor to the beginning of the row."
748 */
749 public carriageReturn(): boolean {
750 this._activeBuffer.x = 0;
751 return true;
752 }
753
754 /**
755 * BS
756 * Backspace (Ctrl-H).
757 *
758 * @vt: #Y C0 BS "Backspace" "\b, \x08" "Move the cursor one position to the left."
759 * By default it is not possible to move the cursor past the leftmost position.
760 * If `reverse wrap-around` (`CSI ? 45 h`) is set, a previous soft line wrap (DECAWM)
761 * can be undone with BS within the scroll margins. In that case the cursor will wrap back
762 * to the end of the previous row. Note that it is not possible to peek back into the scrollbuffer
763 * with the cursor, thus at the home position (top-leftmost cell) this has no effect.
764 */
765 public backspace(): boolean {
766 // reverse wrap-around is disabled
767 if (!this._coreService.decPrivateModes.reverseWraparound) {
768 this._restrictCursor();
769 if (this._activeBuffer.x > 0) {
770 this._activeBuffer.x--;
771 }
772 return true;
773 }
774
775 // reverse wrap-around is enabled
776 // other than for normal operation mode, reverse wrap-around allows the cursor
777 // to be at x=cols to be able to address the last cell of a row by BS
778 this._restrictCursor(this._bufferService.cols);
779
780 if (this._activeBuffer.x > 0) {
781 this._activeBuffer.x--;
782 } else {
783 /**
784 * reverse wrap-around handling:
785 * Our implementation deviates from xterm on purpose. Details:
786 * - only previous soft NLs can be reversed (isWrapped=true)
787 * - only works within scrollborders (top/bottom, left/right not yet supported)
788 * - cannot peek into scrollbuffer
789 * - any cursor movement sequence keeps working as expected
790 */
791 if (this._activeBuffer.x === 0
792 && this._activeBuffer.y > this._activeBuffer.scrollTop
793 && this._activeBuffer.y <= this._activeBuffer.scrollBottom
794 && this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)?.isWrapped) {
795 this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!.isWrapped = false;
796 this._activeBuffer.y--;
797 this._activeBuffer.x = this._bufferService.cols - 1;
798 // find last taken cell - last cell can have 3 different states:
799 // - hasContent(true) + hasWidth(1): narrow char - we are done
800 // - hasWidth(0): second part of wide char - we are done
801 // - hasContent(false) + hasWidth(1): empty cell due to early wrapping wide char, go one
802 // cell further back
803 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;
804 if (line.hasWidth(this._activeBuffer.x) && !line.hasContent(this._activeBuffer.x)) {
805 this._activeBuffer.x--;
806 // We do this only once, since width=1 + hasContent=false currently happens only once
807 // before early wrapping of a wide char.
808 // This needs to be fixed once we support graphemes taking more than 2 cells.
809 }
810 }
811 }
812 this._restrictCursor();
813 return true;
814 }
815
816 /**
817 * TAB
818 * Horizontal Tab (HT) (Ctrl-I).
819 *
820 * @vt: #Y C0 HT "Horizontal Tabulation" "\t, \x09" "Move the cursor to the next character tab stop."
821 */
822 public tab(): boolean {
823 if (this._activeBuffer.x >= this._bufferService.cols) {
824 return true;
825 }
826 const originalX = this._activeBuffer.x;
827 this._activeBuffer.x = this._activeBuffer.nextStop();
828 if (this._optionsService.rawOptions.screenReaderMode) {
829 this._onA11yTab.fire(this._activeBuffer.x - originalX);
830 }
831 return true;
832 }
833
834 /**
835 * SO
836 * Shift Out (Ctrl-N) -> Switch to Alternate Character Set. This invokes the
837 * G1 character set.
838 *
839 * @vt: #P[Only limited ISO-2022 charset support.] C0 SO "Shift Out" "\x0E" "Switch to an alternative character set."
840 */
841 public shiftOut(): boolean {
842 this._charsetService.setgLevel(1);
843 return true;
844 }
845
846 /**
847 * SI
848 * Shift In (Ctrl-O) -> Switch to Standard Character Set. This invokes the G0
849 * character set (the default).
850 *
851 * @vt: #Y C0 SI "Shift In" "\x0F" "Return to regular character set after Shift Out."
852 */
853 public shiftIn(): boolean {
854 this._charsetService.setgLevel(0);
855 return true;
856 }
857
858 /**
859 * Restrict cursor to viewport size / scroll margin (origin mode).
860 */
861 private _restrictCursor(maxCol: number = this._bufferService.cols - 1): void {
862 this._activeBuffer.x = Math.min(maxCol, Math.max(0, this._activeBuffer.x));
863 this._activeBuffer.y = this._coreService.decPrivateModes.origin
864 ? Math.min(this._activeBuffer.scrollBottom, Math.max(this._activeBuffer.scrollTop, this._activeBuffer.y))
865 : Math.min(this._bufferService.rows - 1, Math.max(0, this._activeBuffer.y));
866 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
867 }
868
869 /**
870 * Set absolute cursor position.
871 */
872 private _setCursor(x: number, y: number): void {
873 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
874 if (this._coreService.decPrivateModes.origin) {
875 this._activeBuffer.x = x;
876 this._activeBuffer.y = this._activeBuffer.scrollTop + y;
877 } else {
878 this._activeBuffer.x = x;
879 this._activeBuffer.y = y;
880 }
881 this._restrictCursor();
882 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
883 }
884
885 /**
886 * Set relative cursor position.
887 */
888 private _moveCursor(x: number, y: number): void {
889 // for relative changes we have to make sure we are within 0 .. cols/rows - 1
890 // before calculating the new position
891 this._restrictCursor();
892 this._setCursor(this._activeBuffer.x + x, this._activeBuffer.y + y);
893 }
894
895 /**
896 * CSI Ps A
897 * Cursor Up Ps Times (default = 1) (CUU).
898 *
899 * @vt: #Y CSI CUU "Cursor Up" "CSI Ps A" "Move cursor `Ps` times up (default=1)."
900 * If the cursor would pass the top scroll margin, it will stop there.
901 */
902 public cursorUp(params: IParams): boolean {
903 // stop at scrollTop
904 const diffToTop = this._activeBuffer.y - this._activeBuffer.scrollTop;
905 if (diffToTop >= 0) {
906 this._moveCursor(0, -Math.min(diffToTop, params.params[0] || 1));
907 } else {
908 this._moveCursor(0, -(params.params[0] || 1));
909 }
910 return true;
911 }
912
913 /**
914 * CSI Ps B
915 * Cursor Down Ps Times (default = 1) (CUD).
916 *
917 * @vt: #Y CSI CUD "Cursor Down" "CSI Ps B" "Move cursor `Ps` times down (default=1)."
918 * If the cursor would pass the bottom scroll margin, it will stop there.
919 */
920 public cursorDown(params: IParams): boolean {
921 // stop at scrollBottom
922 const diffToBottom = this._activeBuffer.scrollBottom - this._activeBuffer.y;
923 if (diffToBottom >= 0) {
924 this._moveCursor(0, Math.min(diffToBottom, params.params[0] || 1));
925 } else {
926 this._moveCursor(0, params.params[0] || 1);
927 }
928 return true;
929 }
930
931 /**
932 * CSI Ps C
933 * Cursor Forward Ps Times (default = 1) (CUF).
934 *
935 * @vt: #Y CSI CUF "Cursor Forward" "CSI Ps C" "Move cursor `Ps` times forward (default=1)."
936 */
937 public cursorForward(params: IParams): boolean {
938 this._moveCursor(params.params[0] || 1, 0);
939 return true;
940 }
941
942 /**
943 * CSI Ps D
944 * Cursor Backward Ps Times (default = 1) (CUB).
945 *
946 * @vt: #Y CSI CUB "Cursor Backward" "CSI Ps D" "Move cursor `Ps` times backward (default=1)."
947 */
948 public cursorBackward(params: IParams): boolean {
949 this._moveCursor(-(params.params[0] || 1), 0);
950 return true;
951 }
952
953 /**
954 * CSI Ps E
955 * Cursor Next Line Ps Times (default = 1) (CNL).
956 * Other than cursorDown (CUD) also set the cursor to first column.
957 *
958 * @vt: #Y CSI CNL "Cursor Next Line" "CSI Ps E" "Move cursor `Ps` times down (default=1) and to the first column."
959 * Same as CUD, additionally places the cursor at the first column.
960 */
961 public cursorNextLine(params: IParams): boolean {
962 this.cursorDown(params);
963 this._activeBuffer.x = 0;
964 return true;
965 }
966
967 /**
968 * CSI Ps F
969 * Cursor Previous Line Ps Times (default = 1) (CPL).
970 * Other than cursorUp (CUU) also set the cursor to first column.
971 *
972 * @vt: #Y CSI CPL "Cursor Backward" "CSI Ps F" "Move cursor `Ps` times up (default=1) and to the first column."
973 * Same as CUU, additionally places the cursor at the first column.
974 */
975 public cursorPrecedingLine(params: IParams): boolean {
976 this.cursorUp(params);
977 this._activeBuffer.x = 0;
978 return true;
979 }
980
981 /**
982 * CSI Ps G
983 * Cursor Character Absolute [column] (default = [row,1]) (CHA).
984 *
985 * @vt: #Y CSI CHA "Cursor Horizontal Absolute" "CSI Ps G" "Move cursor to `Ps`-th column of the active row (default=1)."
986 */
987 public cursorCharAbsolute(params: IParams): boolean {
988 this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);
989 return true;
990 }
991
992 /**
993 * CSI Ps ; Ps H
994 * Cursor Position [row;column] (default = [1,1]) (CUP).
995 *
996 * @vt: #Y CSI CUP "Cursor Position" "CSI Ps ; Ps H" "Set cursor to position [`Ps`, `Ps`] (default = [1, 1])."
997 * If ORIGIN mode is set, places the cursor to the absolute position within the scroll margins.
998 * If ORIGIN mode is not set, places the cursor to the absolute position within the viewport.
999 * Note that the coordinates are 1-based, thus the top left position starts at `1 ; 1`.
1000 */
1001 public cursorPosition(params: IParams): boolean {
1002 this._setCursor(
1003 // col
1004 (params.length >= 2) ? (params.params[1] || 1) - 1 : 0,
1005 // row
1006 (params.params[0] || 1) - 1
1007 );
1008 return true;
1009 }
1010
1011 /**
1012 * CSI Pm ` Character Position Absolute
1013 * [column] (default = [row,1]) (HPA).
1014 * Currently same functionality as CHA.
1015 *
1016 * @vt: #Y CSI HPA "Horizontal Position Absolute" "CSI Ps ` " "Same as CHA."
1017 */
1018 public charPosAbsolute(params: IParams): boolean {
1019 this._setCursor((params.params[0] || 1) - 1, this._activeBuffer.y);
1020 return true;
1021 }
1022
1023 /**
1024 * CSI Pm a Character Position Relative
1025 * [columns] (default = [row,col+1]) (HPR)
1026 *
1027 * @vt: #Y CSI HPR "Horizontal Position Relative" "CSI Ps a" "Same as CUF."
1028 */
1029 public hPositionRelative(params: IParams): boolean {
1030 this._moveCursor(params.params[0] || 1, 0);
1031 return true;
1032 }
1033
1034 /**
1035 * CSI Pm d Vertical Position Absolute (VPA)
1036 * [row] (default = [1,column])
1037 *
1038 * @vt: #Y CSI VPA "Vertical Position Absolute" "CSI Ps d" "Move cursor to `Ps`-th row (default=1)."
1039 */
1040 public linePosAbsolute(params: IParams): boolean {
1041 this._setCursor(this._activeBuffer.x, (params.params[0] || 1) - 1);
1042 return true;
1043 }
1044
1045 /**
1046 * CSI Pm e Vertical Position Relative (VPR)
1047 * [rows] (default = [row+1,column])
1048 * reuse CSI Ps B ?
1049 *
1050 * @vt: #Y CSI VPR "Vertical Position Relative" "CSI Ps e" "Move cursor `Ps` times down (default=1)."
1051 */
1052 public vPositionRelative(params: IParams): boolean {
1053 this._moveCursor(0, params.params[0] || 1);
1054 return true;
1055 }
1056
1057 /**
1058 * CSI Ps ; Ps f
1059 * Horizontal and Vertical Position [row;column] (default =
1060 * [1,1]) (HVP).
1061 * Same as CUP.
1062 *
1063 * @vt: #Y CSI HVP "Horizontal and Vertical Position" "CSI Ps ; Ps f" "Same as CUP."
1064 */
1065 public hVPosition(params: IParams): boolean {
1066 this.cursorPosition(params);
1067 return true;
1068 }
1069
1070 /**
1071 * CSI Ps g Tab Clear (TBC).
1072 * Ps = 0 -> Clear Current Column (default).
1073 * Ps = 3 -> Clear All.
1074 * Potentially:
1075 * Ps = 2 -> Clear Stops on Line.
1076 * http://vt100.net/annarbor/aaa-ug/section6.html
1077 *
1078 * @vt: #Y CSI TBC "Tab Clear" "CSI Ps g" "Clear tab stops at current position (0) or all (3) (default=0)."
1079 * Clearing tabstops off the active row (Ps = 2, VT100) is currently not supported.
1080 */
1081 public tabClear(params: IParams): boolean {
1082 const param = params.params[0];
1083 if (param === 0) {
1084 delete this._activeBuffer.tabs[this._activeBuffer.x];
1085 } else if (param === 3) {
1086 this._activeBuffer.tabs = {};
1087 }
1088 return true;
1089 }
1090
1091 /**
1092 * CSI Ps I
1093 * Cursor Forward Tabulation Ps tab stops (default = 1) (CHT).
1094 *
1095 * @vt: #Y CSI CHT "Cursor Horizontal Tabulation" "CSI Ps I" "Move cursor `Ps` times tabs forward (default=1)."
1096 */
1097 public cursorForwardTab(params: IParams): boolean {
1098 if (this._activeBuffer.x >= this._bufferService.cols) {
1099 return true;
1100 }
1101 let param = params.params[0] || 1;
1102 while (param--) {
1103 this._activeBuffer.x = this._activeBuffer.nextStop();
1104 }
1105 return true;
1106 }
1107
1108 /**
1109 * CSI Ps Z Cursor Backward Tabulation Ps tab stops (default = 1) (CBT).
1110 *
1111 * @vt: #Y CSI CBT "Cursor Backward Tabulation" "CSI Ps Z" "Move cursor `Ps` tabs backward (default=1)."
1112 */
1113 public cursorBackwardTab(params: IParams): boolean {
1114 if (this._activeBuffer.x >= this._bufferService.cols) {
1115 return true;
1116 }
1117 let param = params.params[0] || 1;
1118
1119 while (param--) {
1120 this._activeBuffer.x = this._activeBuffer.prevStop();
1121 }
1122 return true;
1123 }
1124
1125 /**
1126 * CSI Ps " q Select Character Protection Attribute (DECSCA).
1127 *
1128 * @vt: #Y CSI DECSCA "Select Character Protection Attribute" "CSI Ps " q" "Whether DECSED and DECSEL can erase (0=default, 2) or not (1)."
1129 */
1130 public selectProtected(params: IParams): boolean {
1131 const p = params.params[0];
1132 if (p === 1) this._curAttrData.bg |= BgFlags.PROTECTED;
1133 if (p === 2 || p === 0) this._curAttrData.bg &= ~BgFlags.PROTECTED;
1134 return true;
1135 }
1136
1137
1138 /**
1139 * Helper method to erase cells in a terminal row.
1140 * The cell gets replaced with the eraseChar of the terminal.
1141 * @param y The row index relative to the viewport.
1142 * @param start The start x index of the range to be erased.
1143 * @param end The end x index of the range to be erased (exclusive).
1144 * @param clearWrap clear the isWrapped flag
1145 * @param respectProtect Whether to respect the protection attribute (DECSCA).
1146 */
1147 private _eraseInBufferLine(y: number, start: number, end: number, clearWrap: boolean = false, respectProtect: boolean = false): void {
1148 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;
1149 line.replaceCells(
1150 start,
1151 end,
1152 this._activeBuffer.getNullCell(this._eraseAttrData()),
1153 respectProtect
1154 );
1155 if (clearWrap) {
1156 line.isWrapped = false;
1157 }
1158 }
1159
1160 /**
1161 * Helper method to reset cells in a terminal row. The cell gets replaced with the eraseChar of
1162 * the terminal and the isWrapped property is set to false.
1163 * @param y row index
1164 */
1165 private _resetBufferLine(y: number, respectProtect: boolean = false): void {
1166 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y);
1167 if (line) {
1168 line.fill(this._activeBuffer.getNullCell(this._eraseAttrData()), respectProtect);
1169 this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase + y);
1170 line.isWrapped = false;
1171 }
1172 }
1173
1174 /**
1175 * CSI Ps J Erase in Display (ED).
1176 * Ps = 0 -> Erase Below (default).
1177 * Ps = 1 -> Erase Above.
1178 * Ps = 2 -> Erase All.
1179 * Ps = 3 -> Erase Saved Lines (xterm).
1180 * CSI ? Ps J
1181 * Erase in Display (DECSED).
1182 * Ps = 0 -> Selective Erase Below (default).
1183 * Ps = 1 -> Selective Erase Above.
1184 * Ps = 2 -> Selective Erase All.
1185 *
1186 * @vt: #Y CSI ED "Erase In Display" "CSI Ps J" "Erase various parts of the viewport."
1187 * Supported param values:
1188 *
1189 * | Ps | Effect |
1190 * | -- | ------------------------------------------------------------ |
1191 * | 0 | Erase from the cursor through the end of the viewport. |
1192 * | 1 | Erase from the beginning of the viewport through the cursor. |
1193 * | 2 | Erase complete viewport. |
1194 * | 3 | Erase scrollback. |
1195 *
1196 * @vt: #Y CSI DECSED "Selective Erase In Display" "CSI ? Ps J" "Same as ED with respecting protection flag."
1197 */
1198 public eraseInDisplay(params: IParams, respectProtect: boolean = false): boolean {
1199 this._restrictCursor(this._bufferService.cols);
1200 let j;
1201 switch (params.params[0]) {
1202 case 0:
1203 j = this._activeBuffer.y;
1204 this._dirtyRowTracker.markDirty(j);
1205 this._eraseInBufferLine(j++, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);
1206 for (; j < this._bufferService.rows; j++) {
1207 this._resetBufferLine(j, respectProtect);
1208 }
1209 this._dirtyRowTracker.markDirty(j);
1210 break;
1211 case 1:
1212 j = this._activeBuffer.y;
1213 this._dirtyRowTracker.markDirty(j);
1214 // Deleted front part of line and everything before. This line will no longer be wrapped.
1215 this._eraseInBufferLine(j, 0, this._activeBuffer.x + 1, true, respectProtect);
1216 if (this._activeBuffer.x + 1 >= this._bufferService.cols) {
1217 // Deleted entire previous line. This next line can no longer be wrapped.
1218 this._activeBuffer.lines.get(j + 1)!.isWrapped = false;
1219 }
1220 while (j--) {
1221 this._resetBufferLine(j, respectProtect);
1222 }
1223 this._dirtyRowTracker.markDirty(0);
1224 break;
1225 case 2:
1226 if (this._optionsService.rawOptions.scrollOnEraseInDisplay) {
1227 j = this._bufferService.rows;
1228 this._dirtyRowTracker.markRangeDirty(0, j - 1);
1229 while (j--) {
1230 const currentLine = this._activeBuffer.lines.get(this._activeBuffer.ybase + j);
1231 if (currentLine?.getTrimmedLength()) {
1232 break;
1233 }
1234 }
1235 for (; j >= 0; j--) {
1236 this._bufferService.scroll(this._eraseAttrData());
1237 }
1238 }
1239 else {
1240 j = this._bufferService.rows;
1241 this._dirtyRowTracker.markDirty(j - 1);
1242 while (j--) {
1243 this._resetBufferLine(j, respectProtect);
1244 }
1245 this._dirtyRowTracker.markDirty(0);
1246 }
1247 break;
1248 case 3:
1249 // Clear scrollback (everything not in viewport)
1250 const scrollBackSize = this._activeBuffer.lines.length - this._bufferService.rows;
1251 if (scrollBackSize > 0) {
1252 this._activeBuffer.lines.trimStart(scrollBackSize);
1253 this._activeBuffer.ybase = Math.max(this._activeBuffer.ybase - scrollBackSize, 0);
1254 this._activeBuffer.ydisp = Math.max(this._activeBuffer.ydisp - scrollBackSize, 0);
1255 // Force a scroll event to refresh viewport
1256 this._onScroll.fire(0);
1257 }
1258 break;
1259 }
1260 return true;
1261 }
1262
1263 /**
1264 * CSI Ps K Erase in Line (EL).
1265 * Ps = 0 -> Erase to Right (default).
1266 * Ps = 1 -> Erase to Left.
1267 * Ps = 2 -> Erase All.
1268 * CSI ? Ps K
1269 * Erase in Line (DECSEL).
1270 * Ps = 0 -> Selective Erase to Right (default).
1271 * Ps = 1 -> Selective Erase to Left.
1272 * Ps = 2 -> Selective Erase All.
1273 *
1274 * @vt: #Y CSI EL "Erase In Line" "CSI Ps K" "Erase various parts of the active row."
1275 * Supported param values:
1276 *
1277 * | Ps | Effect |
1278 * | -- | -------------------------------------------------------- |
1279 * | 0 | Erase from the cursor through the end of the row. |
1280 * | 1 | Erase from the beginning of the line through the cursor. |
1281 * | 2 | Erase complete line. |
1282 *
1283 * @vt: #Y CSI DECSEL "Selective Erase In Line" "CSI ? Ps K" "Same as EL with respecting protecting flag."
1284 */
1285 public eraseInLine(params: IParams, respectProtect: boolean = false): boolean {
1286 this._restrictCursor(this._bufferService.cols);
1287 switch (params.params[0]) {
1288 case 0:
1289 this._eraseInBufferLine(this._activeBuffer.y, this._activeBuffer.x, this._bufferService.cols, this._activeBuffer.x === 0, respectProtect);
1290 break;
1291 case 1:
1292 this._eraseInBufferLine(this._activeBuffer.y, 0, this._activeBuffer.x + 1, false, respectProtect);
1293 break;
1294 case 2:
1295 this._eraseInBufferLine(this._activeBuffer.y, 0, this._bufferService.cols, true, respectProtect);
1296 break;
1297 }
1298 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
1299 return true;
1300 }
1301
1302 /**
1303 * CSI Ps L
1304 * Insert Ps Line(s) (default = 1) (IL).
1305 *
1306 * @vt: #Y CSI IL "Insert Line" "CSI Ps L" "Insert `Ps` blank lines at active row (default=1)."
1307 * For every inserted line at the scroll top one line at the scroll bottom gets removed.
1308 * The cursor is set to the first column.
1309 * IL has no effect if the cursor is outside the scroll margins.
1310 */
1311 public insertLines(params: IParams): boolean {
1312 this._restrictCursor();
1313 let param = params.params[0] || 1;
1314
1315 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1316 return true;
1317 }
1318
1319 const row: number = this._activeBuffer.ybase + this._activeBuffer.y;
1320
1321 const scrollBottomRowsOffset = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;
1322 const scrollBottomAbsolute = this._bufferService.rows - 1 + this._activeBuffer.ybase - scrollBottomRowsOffset + 1;
1323 while (param--) {
1324 // test: echo -e '\e[44m\e[1L\e[0m'
1325 // blankLine(true) - xterm/linux behavior
1326 this._activeBuffer.lines.splice(scrollBottomAbsolute - 1, 1);
1327 this._activeBuffer.lines.splice(row, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
1328 }
1329
1330 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);
1331 this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
1332 return true;
1333 }
1334
1335 /**
1336 * CSI Ps M
1337 * Delete Ps Line(s) (default = 1) (DL).
1338 *
1339 * @vt: #Y CSI DL "Delete Line" "CSI Ps M" "Delete `Ps` lines at active row (default=1)."
1340 * For every deleted line at the scroll top one blank line at the scroll bottom gets appended.
1341 * The cursor is set to the first column.
1342 * DL has no effect if the cursor is outside the scroll margins.
1343 */
1344 public deleteLines(params: IParams): boolean {
1345 this._restrictCursor();
1346 let param = params.params[0] || 1;
1347
1348 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1349 return true;
1350 }
1351
1352 const row: number = this._activeBuffer.ybase + this._activeBuffer.y;
1353
1354 let j: number;
1355 j = this._bufferService.rows - 1 - this._activeBuffer.scrollBottom;
1356 j = this._bufferService.rows - 1 + this._activeBuffer.ybase - j;
1357 while (param--) {
1358 // test: echo -e '\e[44m\e[1M\e[0m'
1359 // blankLine(true) - xterm/linux behavior
1360 this._activeBuffer.lines.splice(row, 1);
1361 this._activeBuffer.lines.splice(j, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
1362 }
1363
1364 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y, this._activeBuffer.scrollBottom);
1365 this._activeBuffer.x = 0; // see https://vt100.net/docs/vt220-rm/chapter4.html - vt220 only?
1366 return true;
1367 }
1368
1369 /**
1370 * CSI Ps @
1371 * Insert Ps (Blank) Character(s) (default = 1) (ICH).
1372 *
1373 * @vt: #Y CSI ICH "Insert Characters" "CSI Ps @" "Insert `Ps` (blank) characters (default = 1)."
1374 * The ICH sequence inserts `Ps` blank characters. The cursor remains at the beginning of the
1375 * blank characters. Text between the cursor and right margin moves to the right. Characters moved
1376 * past the right margin are lost.
1377 *
1378 *
1379 * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)
1380 */
1381 public insertChars(params: IParams): boolean {
1382 this._restrictCursor();
1383 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
1384 if (line) {
1385 line.insertCells(
1386 this._activeBuffer.x,
1387 params.params[0] || 1,
1388 this._activeBuffer.getNullCell(this._eraseAttrData())
1389 );
1390 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
1391 }
1392 return true;
1393 }
1394
1395 /**
1396 * CSI Ps P
1397 * Delete Ps Character(s) (default = 1) (DCH).
1398 *
1399 * @vt: #Y CSI DCH "Delete Character" "CSI Ps P" "Delete `Ps` characters (default=1)."
1400 * As characters are deleted, the remaining characters between the cursor and right margin move to
1401 * the left. Character attributes move with the characters. The terminal adds blank characters at
1402 * the right margin.
1403 *
1404 *
1405 * FIXME: check against xterm - should not work outside of scroll margins (see VT520 manual)
1406 */
1407 public deleteChars(params: IParams): boolean {
1408 this._restrictCursor();
1409 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
1410 if (line) {
1411 line.deleteCells(
1412 this._activeBuffer.x,
1413 params.params[0] || 1,
1414 this._activeBuffer.getNullCell(this._eraseAttrData())
1415 );
1416 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
1417 }
1418 return true;
1419 }
1420
1421 /**
1422 * CSI Ps S Scroll up Ps lines (default = 1) (SU).
1423 *
1424 * @vt: #Y CSI SU "Scroll Up" "CSI Ps S" "Scroll `Ps` lines up (default=1)."
1425 *
1426 *
1427 * FIXME: scrolled out lines at top = 1 should add to scrollback (xterm)
1428 */
1429 public scrollUp(params: IParams): boolean {
1430 let param = params.params[0] || 1;
1431
1432 while (param--) {
1433 this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 1);
1434 this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 0, this._activeBuffer.getBlankLine(this._eraseAttrData()));
1435 }
1436 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1437 return true;
1438 }
1439
1440 /**
1441 * CSI Ps T Scroll down Ps lines (default = 1) (SD).
1442 *
1443 * @vt: #Y CSI SD "Scroll Down" "CSI Ps T" "Scroll `Ps` lines down (default=1)."
1444 */
1445 public scrollDown(params: IParams): boolean {
1446 let param = params.params[0] || 1;
1447
1448 while (param--) {
1449 this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollBottom, 1);
1450 this._activeBuffer.lines.splice(this._activeBuffer.ybase + this._activeBuffer.scrollTop, 0, this._activeBuffer.getBlankLine(DEFAULT_ATTR_DATA));
1451 }
1452 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1453 return true;
1454 }
1455
1456 /**
1457 * CSI Ps SP @ Scroll left Ps columns (default = 1) (SL) ECMA-48
1458 *
1459 * Notation: (Pn)
1460 * Representation: CSI Pn 02/00 04/00
1461 * Parameter default value: Pn = 1
1462 * SL causes the data in the presentation component to be moved by n character positions
1463 * if the line orientation is horizontal, or by n line positions if the line orientation
1464 * is vertical, such that the data appear to move to the left; where n equals the value of Pn.
1465 * The active presentation position is not affected by this control function.
1466 *
1467 * Supported:
1468 * - always left shift (no line orientation setting respected)
1469 *
1470 * @vt: #Y CSI SL "Scroll Left" "CSI Ps SP @" "Scroll viewport `Ps` times to the left."
1471 * SL moves the content of all lines within the scroll margins `Ps` times to the left.
1472 * SL has no effect outside of the scroll margins.
1473 */
1474 public scrollLeft(params: IParams): boolean {
1475 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1476 return true;
1477 }
1478 const param = params.params[0] || 1;
1479 for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {
1480 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;
1481 line.deleteCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));
1482 line.isWrapped = false;
1483 }
1484 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1485 return true;
1486 }
1487
1488 /**
1489 * CSI Ps SP A Scroll right Ps columns (default = 1) (SR) ECMA-48
1490 *
1491 * Notation: (Pn)
1492 * Representation: CSI Pn 02/00 04/01
1493 * Parameter default value: Pn = 1
1494 * SR causes the data in the presentation component to be moved by n character positions
1495 * if the line orientation is horizontal, or by n line positions if the line orientation
1496 * is vertical, such that the data appear to move to the right; where n equals the value of Pn.
1497 * The active presentation position is not affected by this control function.
1498 *
1499 * Supported:
1500 * - always right shift (no line orientation setting respected)
1501 *
1502 * @vt: #Y CSI SR "Scroll Right" "CSI Ps SP A" "Scroll viewport `Ps` times to the right."
1503 * SL moves the content of all lines within the scroll margins `Ps` times to the right.
1504 * Content at the right margin is lost.
1505 * SL has no effect outside of the scroll margins.
1506 */
1507 public scrollRight(params: IParams): boolean {
1508 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1509 return true;
1510 }
1511 const param = params.params[0] || 1;
1512 for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {
1513 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;
1514 line.insertCells(0, param, this._activeBuffer.getNullCell(this._eraseAttrData()));
1515 line.isWrapped = false;
1516 }
1517 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1518 return true;
1519 }
1520
1521 /**
1522 * CSI Pm ' }
1523 * Insert Ps Column(s) (default = 1) (DECIC), VT420 and up.
1524 *
1525 * @vt: #Y CSI DECIC "Insert Columns" "CSI Ps ' }" "Insert `Ps` columns at cursor position."
1526 * DECIC inserts `Ps` times blank columns at the cursor position for all lines with the scroll
1527 * margins, moving content to the right. Content at the right margin is lost. DECIC has no effect
1528 * outside the scrolling margins.
1529 */
1530 public insertColumns(params: IParams): boolean {
1531 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1532 return true;
1533 }
1534 const param = params.params[0] || 1;
1535 for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {
1536 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;
1537 line.insertCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));
1538 line.isWrapped = false;
1539 }
1540 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1541 return true;
1542 }
1543
1544 /**
1545 * CSI Pm ' ~
1546 * Delete Ps Column(s) (default = 1) (DECDC), VT420 and up.
1547 *
1548 * @vt: #Y CSI DECDC "Delete Columns" "CSI Ps ' ~" "Delete `Ps` columns at cursor position."
1549 * DECDC deletes `Ps` times columns at the cursor position for all lines with the scroll margins,
1550 * moving content to the left. Blank columns are added at the right margin.
1551 * DECDC has no effect outside the scrolling margins.
1552 */
1553 public deleteColumns(params: IParams): boolean {
1554 if (this._activeBuffer.y > this._activeBuffer.scrollBottom || this._activeBuffer.y < this._activeBuffer.scrollTop) {
1555 return true;
1556 }
1557 const param = params.params[0] || 1;
1558 for (let y = this._activeBuffer.scrollTop; y <= this._activeBuffer.scrollBottom; ++y) {
1559 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + y)!;
1560 line.deleteCells(this._activeBuffer.x, param, this._activeBuffer.getNullCell(this._eraseAttrData()));
1561 line.isWrapped = false;
1562 }
1563 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
1564 return true;
1565 }
1566
1567 /**
1568 * CSI Ps X
1569 * Erase Ps Character(s) (default = 1) (ECH).
1570 *
1571 * @vt: #Y CSI ECH "Erase Character" "CSI Ps X" "Erase `Ps` characters from current cursor position to the right (default=1)."
1572 * ED erases `Ps` characters from current cursor position to the right.
1573 * ED works inside or outside the scrolling margins.
1574 */
1575 public eraseChars(params: IParams): boolean {
1576 this._restrictCursor();
1577 const line = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y);
1578 if (line) {
1579 line.replaceCells(
1580 this._activeBuffer.x,
1581 this._activeBuffer.x + (params.params[0] || 1),
1582 this._activeBuffer.getNullCell(this._eraseAttrData())
1583 );
1584 this._dirtyRowTracker.markDirty(this._activeBuffer.y);
1585 }
1586 return true;
1587 }
1588
1589 /**
1590 * CSI Ps b Repeat the preceding graphic character Ps times (REP).
1591 * From ECMA 48 (@see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf)
1592 * Notation: (Pn)
1593 * Representation: CSI Pn 06/02
1594 * Parameter default value: Pn = 1
1595 * REP is used to indicate that the preceding character in the data stream,
1596 * if it is a graphic character (represented by one or more bit combinations) including SPACE,
1597 * is to be repeated n times, where n equals the value of Pn.
1598 * If the character preceding REP is a control function or part of a control function,
1599 * the effect of REP is not defined by this Standard.
1600 *
1601 * We extend xterm's behavior to allow repeating entire grapheme clusters.
1602 * This isn't 100% xterm-compatible, but it seems saner and more useful.
1603 * - text attrs are applied normally
1604 * - wrap around is respected
1605 * - any valid sequence resets the carried forward char
1606 *
1607 * Note: To get reset on a valid sequence working correctly without much runtime penalty, the
1608 * preceding codepoint is stored on the parser in `this.print` and reset during `parser.parse`.
1609 *
1610 * @vt: #Y CSI REP "Repeat Preceding Character" "CSI Ps b" "Repeat preceding character `Ps` times (default=1)."
1611 * REP repeats the previous character `Ps` times advancing the cursor, also wrapping if DECAWM is
1612 * set. REP has no effect if the sequence does not follow a printable ASCII character
1613 * (NOOP for any other sequence in between or NON ASCII characters).
1614 */
1615 public repeatPrecedingCharacter(params: IParams): boolean {
1616 const joinState = this._parser.precedingJoinState;
1617 if (!joinState) {
1618 return true;
1619 }
1620 // call print to insert the chars and handle correct wrapping
1621 const length = params.params[0] || 1;
1622 const chWidth = UnicodeService.extractWidth(joinState);
1623 const x = this._activeBuffer.x - chWidth;
1624 const bufferRow = this._activeBuffer.lines.get(this._activeBuffer.ybase + this._activeBuffer.y)!;
1625 const text = bufferRow.getString(x);
1626 const data = new Uint32Array(text.length * length);
1627 let idata = 0;
1628 for (let itext = 0; itext < text.length;) {
1629 const ch = text.codePointAt(itext) || 0;
1630 data[idata++] = ch;
1631 itext += ch > 0xffff ? 2 : 1;
1632 }
1633 let tlength = idata;
1634 for (let i = 1; i < length; ++i) {
1635 data.copyWithin(tlength, 0, idata);
1636 tlength += idata;
1637 }
1638 this.print(data, 0, tlength);
1639 return true;
1640 }
1641
1642 /**
1643 * CSI Ps c Send Device Attributes (Primary DA).
1644 * Ps = 0 or omitted -> request attributes from terminal. The
1645 * response depends on the decTerminalID resource setting.
1646 * -> CSI ? 1 ; 2 c (``VT100 with Advanced Video Option'')
1647 * -> CSI ? 1 ; 0 c (``VT101 with No Options'')
1648 * -> CSI ? 6 c (``VT102'')
1649 * -> CSI ? 6 0 ; 1 ; 2 ; 6 ; 8 ; 9 ; 1 5 ; c (``VT220'')
1650 * The VT100-style response parameters do not mean anything by
1651 * themselves. VT220 parameters do, telling the host what fea-
1652 * tures the terminal supports:
1653 * Ps = 1 -> 132-columns.
1654 * Ps = 2 -> Printer.
1655 * Ps = 6 -> Selective erase.
1656 * Ps = 8 -> User-defined keys.
1657 * Ps = 9 -> National replacement character sets.
1658 * Ps = 1 5 -> Technical characters.
1659 * Ps = 2 2 -> ANSI color, e.g., VT525.
1660 * Ps = 2 9 -> ANSI text locator (i.e., DEC Locator mode).
1661 *
1662 * @vt: #Y CSI DA1 "Primary Device Attributes" "CSI c" "Send primary device attributes."
1663 *
1664 *
1665 * TODO: fix and cleanup response
1666 */
1667 public sendDeviceAttributesPrimary(params: IParams): boolean {
1668 if (params.params[0] > 0) {
1669 return true;
1670 }
1671 if (this._is('xterm') || this._is('rxvt-unicode') || this._is('screen')) {
1672 this._coreService.triggerDataEvent(C0.ESC + '[?1;2c');
1673 } else if (this._is('linux')) {
1674 this._coreService.triggerDataEvent(C0.ESC + '[?6c');
1675 }
1676 return true;
1677 }
1678
1679 /**
1680 * CSI > Ps c
1681 * Send Device Attributes (Secondary DA).
1682 * Ps = 0 or omitted -> request the terminal's identification
1683 * code. The response depends on the decTerminalID resource set-
1684 * ting. It should apply only to VT220 and up, but xterm extends
1685 * this to VT100.
1686 * -> CSI > Pp ; Pv ; Pc c
1687 * where Pp denotes the terminal type
1688 * Pp = 0 -> ``VT100''.
1689 * Pp = 1 -> ``VT220''.
1690 * and Pv is the firmware version (for xterm, this was originally
1691 * the XFree86 patch number, starting with 95). In a DEC termi-
1692 * nal, Pc indicates the ROM cartridge registration number and is
1693 * always zero.
1694 * More information:
1695 * xterm/charproc.c - line 2012, for more information.
1696 * vim responds with ^[[?0c or ^[[?1c after the terminal's response (?)
1697 *
1698 * @vt: #Y CSI DA2 "Secondary Device Attributes" "CSI > c" "Send primary device attributes."
1699 *
1700 *
1701 * TODO: fix and cleanup response
1702 */
1703 public sendDeviceAttributesSecondary(params: IParams): boolean {
1704 if (params.params[0] > 0) {
1705 return true;
1706 }
1707 // xterm and urxvt
1708 // seem to spit this
1709 // out around ~370 times (?).
1710 if (this._is('xterm')) {
1711 this._coreService.triggerDataEvent(C0.ESC + '[>0;276;0c');
1712 } else if (this._is('rxvt-unicode')) {
1713 this._coreService.triggerDataEvent(C0.ESC + '[>85;95;0c');
1714 } else if (this._is('linux')) {
1715 // not supported by linux console.
1716 // linux console echoes parameters.
1717 this._coreService.triggerDataEvent(params.params[0] + 'c');
1718 } else if (this._is('screen')) {
1719 this._coreService.triggerDataEvent(C0.ESC + '[>83;40003;0c');
1720 }
1721 return true;
1722 }
1723
1724 /**
1725 * Evaluate if the current terminal is the given argument.
1726 * @param term The terminal name to evaluate
1727 */
1728 private _is(term: string): boolean {
1729 return (this._optionsService.rawOptions.termName + '').indexOf(term) === 0;
1730 }
1731
1732 /**
1733 * CSI Pm h Set Mode (SM).
1734 * Ps = 2 -> Keyboard Action Mode (AM).
1735 * Ps = 4 -> Insert Mode (IRM).
1736 * Ps = 1 2 -> Send/receive (SRM).
1737 * Ps = 2 0 -> Automatic Newline (LNM).
1738 *
1739 * @vt: #P[Only IRM is supported.] CSI SM "Set Mode" "CSI Pm h" "Set various terminal modes."
1740 * Supported param values by SM:
1741 *
1742 * | Param | Action | Support |
1743 * | ----- | -------------------------------------- | ------- |
1744 * | 2 | Keyboard Action Mode (KAM). Always on. | #N |
1745 * | 4 | Insert Mode (IRM). | #Y |
1746 * | 12 | Send/receive (SRM). Always off. | #N |
1747 * | 20 | Automatic Newline (LNM). | #Y |
1748 */
1749 public setMode(params: IParams): boolean {
1750 for (let i = 0; i < params.length; i++) {
1751 switch (params.params[i]) {
1752 case 4:
1753 this._coreService.modes.insertMode = true;
1754 break;
1755 case 20:
1756 this._optionsService.options.convertEol = true;
1757 break;
1758 }
1759 }
1760 return true;
1761 }
1762
1763 /**
1764 * CSI ? Pm h
1765 * DEC Private Mode Set (DECSET).
1766 * Ps = 1 -> Application Cursor Keys (DECCKM).
1767 * Ps = 2 -> Designate USASCII for character sets G0-G3
1768 * (DECANM), and set VT100 mode.
1769 * Ps = 3 -> 132 Column Mode (DECCOLM).
1770 * Ps = 4 -> Smooth (Slow) Scroll (DECSCLM).
1771 * Ps = 5 -> Reverse Video (DECSCNM).
1772 * Ps = 6 -> Origin Mode (DECOM).
1773 * Ps = 7 -> Wraparound Mode (DECAWM).
1774 * Ps = 8 -> Auto-repeat Keys (DECARM).
1775 * Ps = 9 -> Send Mouse X & Y on button press. See the sec-
1776 * tion Mouse Tracking.
1777 * Ps = 1 0 -> Show toolbar (rxvt).
1778 * Ps = 1 2 -> Start Blinking Cursor (att610).
1779 * Ps = 1 8 -> Print form feed (DECPFF).
1780 * Ps = 1 9 -> Set print extent to full screen (DECPEX).
1781 * Ps = 2 5 -> Show Cursor (DECTCEM).
1782 * Ps = 3 0 -> Show scrollbar (rxvt).
1783 * Ps = 3 5 -> Enable font-shifting functions (rxvt).
1784 * Ps = 3 8 -> Enter Tektronix Mode (DECTEK).
1785 * Ps = 4 0 -> Allow 80 -> 132 Mode.
1786 * Ps = 4 1 -> more(1) fix (see curses resource).
1787 * Ps = 4 2 -> Enable Nation Replacement Character sets (DECN-
1788 * RCM).
1789 * Ps = 4 4 -> Turn On Margin Bell.
1790 * Ps = 4 5 -> Reverse-wraparound Mode.
1791 * Ps = 4 6 -> Start Logging. This is normally disabled by a
1792 * compile-time option.
1793 * Ps = 4 7 -> Use Alternate Screen Buffer. (This may be dis-
1794 * abled by the titeInhibit resource).
1795 * Ps = 6 6 -> Application keypad (DECNKM).
1796 * Ps = 6 7 -> Backarrow key sends backspace (DECBKM).
1797 * Ps = 1 0 0 0 -> Send Mouse X & Y on button press and
1798 * release. See the section Mouse Tracking.
1799 * Ps = 1 0 0 1 -> Use Hilite Mouse Tracking.
1800 * Ps = 1 0 0 2 -> Use Cell Motion Mouse Tracking.
1801 * Ps = 1 0 0 3 -> Use All Motion Mouse Tracking.
1802 * Ps = 1 0 0 4 -> Send FocusIn/FocusOut events.
1803 * Ps = 1 0 0 5 -> Enable Extended Mouse Mode.
1804 * Ps = 1 0 1 0 -> Scroll to bottom on tty output (rxvt).
1805 * Ps = 1 0 1 1 -> Scroll to bottom on key press (rxvt).
1806 * Ps = 1 0 3 4 -> Interpret "meta" key, sets eighth bit.
1807 * (enables the eightBitInput resource).
1808 * Ps = 1 0 3 5 -> Enable special modifiers for Alt and Num-
1809 * Lock keys. (This enables the numLock resource).
1810 * Ps = 1 0 3 6 -> Send ESC when Meta modifies a key. (This
1811 * enables the metaSendsEscape resource).
1812 * Ps = 1 0 3 7 -> Send DEL from the editing-keypad Delete
1813 * key.
1814 * Ps = 1 0 3 9 -> Send ESC when Alt modifies a key. (This
1815 * enables the altSendsEscape resource).
1816 * Ps = 1 0 4 0 -> Keep selection even if not highlighted.
1817 * (This enables the keepSelection resource).
1818 * Ps = 1 0 4 1 -> Use the CLIPBOARD selection. (This enables
1819 * the selectToClipboard resource).
1820 * Ps = 1 0 4 2 -> Enable Urgency window manager hint when
1821 * Control-G is received. (This enables the bellIsUrgent
1822 * resource).
1823 * Ps = 1 0 4 3 -> Enable raising of the window when Control-G
1824 * is received. (enables the popOnBell resource).
1825 * Ps = 1 0 4 7 -> Use Alternate Screen Buffer. (This may be
1826 * disabled by the titeInhibit resource).
1827 * Ps = 1 0 4 8 -> Save cursor as in DECSC. (This may be dis-
1828 * abled by the titeInhibit resource).
1829 * Ps = 1 0 4 9 -> Save cursor as in DECSC and use Alternate
1830 * Screen Buffer, clearing it first. (This may be disabled by
1831 * the titeInhibit resource). This combines the effects of the 1
1832 * 0 4 7 and 1 0 4 8 modes. Use this with terminfo-based
1833 * applications rather than the 4 7 mode.
1834 * Ps = 1 0 5 0 -> Set terminfo/termcap function-key mode.
1835 * Ps = 1 0 5 1 -> Set Sun function-key mode.
1836 * Ps = 1 0 5 2 -> Set HP function-key mode.
1837 * Ps = 1 0 5 3 -> Set SCO function-key mode.
1838 * Ps = 1 0 6 0 -> Set legacy keyboard emulation (X11R6).
1839 * Ps = 1 0 6 1 -> Set VT220 keyboard emulation.
1840 * Ps = 2 0 0 4 -> Set bracketed paste mode.
1841 * Modes:
1842 * http: *vt100.net/docs/vt220-rm/chapter4.html
1843 *
1844 * @vt: #P[See below for supported modes.] CSI DECSET "DEC Private Set Mode" "CSI ? Pm h" "Set various terminal attributes."
1845 * Supported param values by DECSET:
1846 *
1847 * | param | Action | Support |
1848 * | ----- | ------------------------------------------------------- | --------|
1849 * | 1 | Application Cursor Keys (DECCKM). | #Y |
1850 * | 2 | Designate US-ASCII for character sets G0-G3 (DECANM). | #Y |
1851 * | 3 | 132 Column Mode (DECCOLM). | #Y |
1852 * | 6 | Origin Mode (DECOM). | #Y |
1853 * | 7 | Auto-wrap Mode (DECAWM). | #Y |
1854 * | 8 | Auto-repeat Keys (DECARM). Always on. | #N |
1855 * | 9 | X10 xterm mouse protocol. | #Y |
1856 * | 12 | Start Blinking Cursor. | #Y |
1857 * | 25 | Show Cursor (DECTCEM). | #Y |
1858 * | 45 | Reverse wrap-around. | #Y |
1859 * | 47 | Use Alternate Screen Buffer. | #Y |
1860 * | 66 | Application keypad (DECNKM). | #Y |
1861 * | 1000 | X11 xterm mouse protocol. | #Y |
1862 * | 1002 | Use Cell Motion Mouse Tracking. | #Y |
1863 * | 1003 | Use All Motion Mouse Tracking. | #Y |
1864 * | 1004 | Send FocusIn/FocusOut events | #Y |
1865 * | 1005 | Enable UTF-8 Mouse Mode. | #N |
1866 * | 1006 | Enable SGR Mouse Mode. | #Y |
1867 * | 1015 | Enable urxvt Mouse Mode. | #N |
1868 * | 1016 | Enable SGR-Pixels Mouse Mode. | #Y |
1869 * | 1047 | Use Alternate Screen Buffer. | #Y |
1870 * | 1048 | Save cursor as in DECSC. | #Y |
1871 * | 1049 | Save cursor and switch to alternate buffer clearing it. | #P[Does not clear the alternate buffer.] |
1872 * | 2004 | Set bracketed paste mode. | #Y |
1873 *
1874 *
1875 * FIXME: implement DECSCNM, 1049 should clear altbuffer
1876 */
1877 public setModePrivate(params: IParams): boolean {
1878 for (let i = 0; i < params.length; i++) {
1879 switch (params.params[i]) {
1880 case 1:
1881 this._coreService.decPrivateModes.applicationCursorKeys = true;
1882 break;
1883 case 2:
1884 this._charsetService.setgCharset(0, DEFAULT_CHARSET);
1885 this._charsetService.setgCharset(1, DEFAULT_CHARSET);
1886 this._charsetService.setgCharset(2, DEFAULT_CHARSET);
1887 this._charsetService.setgCharset(3, DEFAULT_CHARSET);
1888 // set VT100 mode here
1889 break;
1890 case 3:
1891 /**
1892 * DECCOLM - 132 column mode.
1893 * This is only active if 'SetWinLines' (24) is enabled
1894 * through `options.windowsOptions`.
1895 */
1896 if (this._optionsService.rawOptions.windowOptions.setWinLines) {
1897 this._bufferService.resize(132, this._bufferService.rows);
1898 this._onRequestReset.fire();
1899 }
1900 break;
1901 case 6:
1902 this._coreService.decPrivateModes.origin = true;
1903 this._setCursor(0, 0);
1904 break;
1905 case 7:
1906 this._coreService.decPrivateModes.wraparound = true;
1907 break;
1908 case 12:
1909 this._optionsService.options.cursorBlink = true;
1910 break;
1911 case 45:
1912 this._coreService.decPrivateModes.reverseWraparound = true;
1913 break;
1914 case 66:
1915 this._logService.debug('Serial port requested application keypad.');
1916 this._coreService.decPrivateModes.applicationKeypad = true;
1917 this._onRequestSyncScrollBar.fire();
1918 break;
1919 case 9: // X10 Mouse
1920 // no release, no motion, no wheel, no modifiers.
1921 this._coreMouseService.activeProtocol = 'X10';
1922 break;
1923 case 1000: // vt200 mouse
1924 // no motion.
1925 this._coreMouseService.activeProtocol = 'VT200';
1926 break;
1927 case 1002: // button event mouse
1928 this._coreMouseService.activeProtocol = 'DRAG';
1929 break;
1930 case 1003: // any event mouse
1931 // any event - sends motion events,
1932 // even if there is no button held down.
1933 this._coreMouseService.activeProtocol = 'ANY';
1934 break;
1935 case 1004: // send focusin/focusout events
1936 // focusin: ^[[I
1937 // focusout: ^[[O
1938 this._coreService.decPrivateModes.sendFocus = true;
1939 this._onRequestSendFocus.fire();
1940 break;
1941 case 1005: // utf8 ext mode mouse - removed in #2507
1942 this._logService.debug('DECSET 1005 not supported (see #2507)');
1943 break;
1944 case 1006: // sgr ext mode mouse
1945 this._coreMouseService.activeEncoding = 'SGR';
1946 break;
1947 case 1015: // urxvt ext mode mouse - removed in #2507
1948 this._logService.debug('DECSET 1015 not supported (see #2507)');
1949 break;
1950 case 1016: // sgr pixels mode mouse
1951 this._coreMouseService.activeEncoding = 'SGR_PIXELS';
1952 break;
1953 case 25: // show cursor
1954 this._coreService.isCursorHidden = false;
1955 break;
1956 case 1048: // alt screen cursor
1957 this.saveCursor();
1958 break;
1959 case 1049: // alt screen buffer cursor
1960 this.saveCursor();
1961 // FALL-THROUGH
1962 case 47: // alt screen buffer
1963 case 1047: // alt screen buffer
1964 this._bufferService.buffers.activateAltBuffer(this._eraseAttrData());
1965 this._coreService.isCursorInitialized = true;
1966 this._onRequestRefreshRows.fire(undefined);
1967 this._onRequestSyncScrollBar.fire();
1968 break;
1969 case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
1970 this._coreService.decPrivateModes.bracketedPasteMode = true;
1971 break;
1972 case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)
1973 this._coreService.decPrivateModes.synchronizedOutput = true;
1974 break;
1975 }
1976 }
1977 return true;
1978 }
1979
1980
1981 /**
1982 * CSI Pm l Reset Mode (RM).
1983 * Ps = 2 -> Keyboard Action Mode (AM).
1984 * Ps = 4 -> Replace Mode (IRM).
1985 * Ps = 1 2 -> Send/receive (SRM).
1986 * Ps = 2 0 -> Normal Linefeed (LNM).
1987 *
1988 * @vt: #P[Only IRM is supported.] CSI RM "Reset Mode" "CSI Pm l" "Set various terminal attributes."
1989 * Supported param values by RM:
1990 *
1991 * | Param | Action | Support |
1992 * | ----- | -------------------------------------- | ------- |
1993 * | 2 | Keyboard Action Mode (KAM). Always on. | #N |
1994 * | 4 | Replace Mode (IRM). (default) | #Y |
1995 * | 12 | Send/receive (SRM). Always off. | #N |
1996 * | 20 | Normal Linefeed (LNM). | #Y |
1997 *
1998 *
1999 * FIXME: why is LNM commented out?
2000 */
2001 public resetMode(params: IParams): boolean {
2002 for (let i = 0; i < params.length; i++) {
2003 switch (params.params[i]) {
2004 case 4:
2005 this._coreService.modes.insertMode = false;
2006 break;
2007 case 20:
2008 this._optionsService.options.convertEol = false;
2009 break;
2010 }
2011 }
2012 return true;
2013 }
2014
2015 /**
2016 * CSI ? Pm l
2017 * DEC Private Mode Reset (DECRST).
2018 * Ps = 1 -> Normal Cursor Keys (DECCKM).
2019 * Ps = 2 -> Designate VT52 mode (DECANM).
2020 * Ps = 3 -> 80 Column Mode (DECCOLM).
2021 * Ps = 4 -> Jump (Fast) Scroll (DECSCLM).
2022 * Ps = 5 -> Normal Video (DECSCNM).
2023 * Ps = 6 -> Normal Cursor Mode (DECOM).
2024 * Ps = 7 -> No Wraparound Mode (DECAWM).
2025 * Ps = 8 -> No Auto-repeat Keys (DECARM).
2026 * Ps = 9 -> Don't send Mouse X & Y on button press.
2027 * Ps = 1 0 -> Hide toolbar (rxvt).
2028 * Ps = 1 2 -> Stop Blinking Cursor (att610).
2029 * Ps = 1 8 -> Don't print form feed (DECPFF).
2030 * Ps = 1 9 -> Limit print to scrolling region (DECPEX).
2031 * Ps = 2 5 -> Hide Cursor (DECTCEM).
2032 * Ps = 3 0 -> Don't show scrollbar (rxvt).
2033 * Ps = 3 5 -> Disable font-shifting functions (rxvt).
2034 * Ps = 4 0 -> Disallow 80 -> 132 Mode.
2035 * Ps = 4 1 -> No more(1) fix (see curses resource).
2036 * Ps = 4 2 -> Disable Nation Replacement Character sets (DEC-
2037 * NRCM).
2038 * Ps = 4 4 -> Turn Off Margin Bell.
2039 * Ps = 4 5 -> No Reverse-wraparound Mode.
2040 * Ps = 4 6 -> Stop Logging. (This is normally disabled by a
2041 * compile-time option).
2042 * Ps = 4 7 -> Use Normal Screen Buffer.
2043 * Ps = 6 6 -> Numeric keypad (DECNKM).
2044 * Ps = 6 7 -> Backarrow key sends delete (DECBKM).
2045 * Ps = 1 0 0 0 -> Don't send Mouse X & Y on button press and
2046 * release. See the section Mouse Tracking.
2047 * Ps = 1 0 0 1 -> Don't use Hilite Mouse Tracking.
2048 * Ps = 1 0 0 2 -> Don't use Cell Motion Mouse Tracking.
2049 * Ps = 1 0 0 3 -> Don't use All Motion Mouse Tracking.
2050 * Ps = 1 0 0 4 -> Don't send FocusIn/FocusOut events.
2051 * Ps = 1 0 0 5 -> Disable Extended Mouse Mode.
2052 * Ps = 1 0 1 0 -> Don't scroll to bottom on tty output
2053 * (rxvt).
2054 * Ps = 1 0 1 1 -> Don't scroll to bottom on key press (rxvt).
2055 * Ps = 1 0 3 4 -> Don't interpret "meta" key. (This disables
2056 * the eightBitInput resource).
2057 * Ps = 1 0 3 5 -> Disable special modifiers for Alt and Num-
2058 * Lock keys. (This disables the numLock resource).
2059 * Ps = 1 0 3 6 -> Don't send ESC when Meta modifies a key.
2060 * (This disables the metaSendsEscape resource).
2061 * Ps = 1 0 3 7 -> Send VT220 Remove from the editing-keypad
2062 * Delete key.
2063 * Ps = 1 0 3 9 -> Don't send ESC when Alt modifies a key.
2064 * (This disables the altSendsEscape resource).
2065 * Ps = 1 0 4 0 -> Do not keep selection when not highlighted.
2066 * (This disables the keepSelection resource).
2067 * Ps = 1 0 4 1 -> Use the PRIMARY selection. (This disables
2068 * the selectToClipboard resource).
2069 * Ps = 1 0 4 2 -> Disable Urgency window manager hint when
2070 * Control-G is received. (This disables the bellIsUrgent
2071 * resource).
2072 * Ps = 1 0 4 3 -> Disable raising of the window when Control-
2073 * G is received. (This disables the popOnBell resource).
2074 * Ps = 1 0 4 7 -> Use Normal Screen Buffer, clearing screen
2075 * first if in the Alternate Screen. (This may be disabled by
2076 * the titeInhibit resource).
2077 * Ps = 1 0 4 8 -> Restore cursor as in DECRC. (This may be
2078 * disabled by the titeInhibit resource).
2079 * Ps = 1 0 4 9 -> Use Normal Screen Buffer and restore cursor
2080 * as in DECRC. (This may be disabled by the titeInhibit
2081 * resource). This combines the effects of the 1 0 4 7 and 1 0
2082 * 4 8 modes. Use this with terminfo-based applications rather
2083 * than the 4 7 mode.
2084 * Ps = 1 0 5 0 -> Reset terminfo/termcap function-key mode.
2085 * Ps = 1 0 5 1 -> Reset Sun function-key mode.
2086 * Ps = 1 0 5 2 -> Reset HP function-key mode.
2087 * Ps = 1 0 5 3 -> Reset SCO function-key mode.
2088 * Ps = 1 0 6 0 -> Reset legacy keyboard emulation (X11R6).
2089 * Ps = 1 0 6 1 -> Reset keyboard emulation to Sun/PC style.
2090 * Ps = 2 0 0 4 -> Reset bracketed paste mode.
2091 *
2092 * @vt: #P[See below for supported modes.] CSI DECRST "DEC Private Reset Mode" "CSI ? Pm l" "Reset various terminal attributes."
2093 * Supported param values by DECRST:
2094 *
2095 * | param | Action | Support |
2096 * | ----- | ------------------------------------------------------- | ------- |
2097 * | 1 | Normal Cursor Keys (DECCKM). | #Y |
2098 * | 2 | Designate VT52 mode (DECANM). | #N |
2099 * | 3 | 80 Column Mode (DECCOLM). | #B[Switches to old column width instead of 80.] |
2100 * | 6 | Normal Cursor Mode (DECOM). | #Y |
2101 * | 7 | No Wraparound Mode (DECAWM). | #Y |
2102 * | 8 | No Auto-repeat Keys (DECARM). | #N |
2103 * | 9 | Don't send Mouse X & Y on button press. | #Y |
2104 * | 12 | Stop Blinking Cursor. | #Y |
2105 * | 25 | Hide Cursor (DECTCEM). | #Y |
2106 * | 45 | No reverse wrap-around. | #Y |
2107 * | 47 | Use Normal Screen Buffer. | #Y |
2108 * | 66 | Numeric keypad (DECNKM). | #Y |
2109 * | 1000 | Don't send Mouse reports. | #Y |
2110 * | 1002 | Don't use Cell Motion Mouse Tracking. | #Y |
2111 * | 1003 | Don't use All Motion Mouse Tracking. | #Y |
2112 * | 1004 | Don't send FocusIn/FocusOut events. | #Y |
2113 * | 1005 | Disable UTF-8 Mouse Mode. | #N |
2114 * | 1006 | Disable SGR Mouse Mode. | #Y |
2115 * | 1015 | Disable urxvt Mouse Mode. | #N |
2116 * | 1016 | Disable SGR-Pixels Mouse Mode. | #Y |
2117 * | 1047 | Use Normal Screen Buffer (clearing screen if in alt). | #Y |
2118 * | 1048 | Restore cursor as in DECRC. | #Y |
2119 * | 1049 | Use Normal Screen Buffer and restore cursor. | #Y |
2120 * | 2004 | Reset bracketed paste mode. | #Y |
2121 *
2122 *
2123 * FIXME: DECCOLM is currently broken (already fixed in window options PR)
2124 */
2125 public resetModePrivate(params: IParams): boolean {
2126 for (let i = 0; i < params.length; i++) {
2127 switch (params.params[i]) {
2128 case 1:
2129 this._coreService.decPrivateModes.applicationCursorKeys = false;
2130 break;
2131 case 3:
2132 /**
2133 * DECCOLM - 80 column mode.
2134 * This is only active if 'SetWinLines' (24) is enabled
2135 * through `options.windowsOptions`.
2136 */
2137 if (this._optionsService.rawOptions.windowOptions.setWinLines) {
2138 this._bufferService.resize(80, this._bufferService.rows);
2139 this._onRequestReset.fire();
2140 }
2141 break;
2142 case 6:
2143 this._coreService.decPrivateModes.origin = false;
2144 this._setCursor(0, 0);
2145 break;
2146 case 7:
2147 this._coreService.decPrivateModes.wraparound = false;
2148 break;
2149 case 12:
2150 this._optionsService.options.cursorBlink = false;
2151 break;
2152 case 45:
2153 this._coreService.decPrivateModes.reverseWraparound = false;
2154 break;
2155 case 66:
2156 this._logService.debug('Switching back to normal keypad.');
2157 this._coreService.decPrivateModes.applicationKeypad = false;
2158 this._onRequestSyncScrollBar.fire();
2159 break;
2160 case 9: // X10 Mouse
2161 case 1000: // vt200 mouse
2162 case 1002: // button event mouse
2163 case 1003: // any event mouse
2164 this._coreMouseService.activeProtocol = 'NONE';
2165 break;
2166 case 1004: // send focusin/focusout events
2167 this._coreService.decPrivateModes.sendFocus = false;
2168 break;
2169 case 1005: // utf8 ext mode mouse - removed in #2507
2170 this._logService.debug('DECRST 1005 not supported (see #2507)');
2171 break;
2172 case 1006: // sgr ext mode mouse
2173 this._coreMouseService.activeEncoding = 'DEFAULT';
2174 break;
2175 case 1015: // urxvt ext mode mouse - removed in #2507
2176 this._logService.debug('DECRST 1015 not supported (see #2507)');
2177 break;
2178 case 1016: // sgr pixels mode mouse
2179 this._coreMouseService.activeEncoding = 'DEFAULT';
2180 break;
2181 case 25: // hide cursor
2182 this._coreService.isCursorHidden = true;
2183 break;
2184 case 1048: // alt screen cursor
2185 this.restoreCursor();
2186 break;
2187 case 1049: // alt screen buffer cursor
2188 // FALL-THROUGH
2189 case 47: // normal screen buffer
2190 case 1047: // normal screen buffer - clearing it first
2191 // Ensure the selection manager has the correct buffer
2192 this._bufferService.buffers.activateNormalBuffer();
2193 if (params.params[i] === 1049) {
2194 this.restoreCursor();
2195 }
2196 this._coreService.isCursorInitialized = true;
2197 this._onRequestRefreshRows.fire(undefined);
2198 this._onRequestSyncScrollBar.fire();
2199 break;
2200 case 2004: // bracketed paste mode (https://cirw.in/blog/bracketed-paste)
2201 this._coreService.decPrivateModes.bracketedPasteMode = false;
2202 break;
2203 case 2026: // synchronized output (https://github.com/contour-terminal/vt-extensions/blob/master/synchronized-output.md)
2204 this._coreService.decPrivateModes.synchronizedOutput = false;
2205 this._onRequestRefreshRows.fire(undefined);
2206 break;
2207 }
2208 }
2209 return true;
2210 }
2211
2212 /**
2213 * CSI Ps $ p Request ANSI Mode (DECRQM).
2214 *
2215 * Reports CSI Ps; Pm $ y (DECRPM), where Ps is the mode number as in SM/RM,
2216 * and Pm is the mode value:
2217 * 0 - not recognized
2218 * 1 - set
2219 * 2 - reset
2220 * 3 - permanently set
2221 * 4 - permanently reset
2222 *
2223 * @vt: #Y CSI DECRQM "Request Mode" "CSI Ps $p" "Request mode state."
2224 * Returns a report as `CSI Ps; Pm $ y` (DECRPM), where `Ps` is the mode number as in SM/RM
2225 * or DECSET/DECRST, and `Pm` is the mode value:
2226 * - 0: not recognized
2227 * - 1: set
2228 * - 2: reset
2229 * - 3: permanently set
2230 * - 4: permanently reset
2231 *
2232 * For modes not understood xterm.js always returns `notRecognized`. In general this means,
2233 * that a certain operation mode is not implemented and cannot be used.
2234 *
2235 * Modes changing the active terminal buffer (47, 1047, 1049) are not subqueried
2236 * and only report, whether the alternate buffer is set.
2237 *
2238 * Mouse encodings and mouse protocols are handled mutual exclusive,
2239 * thus only one of each of those can be set at a given time.
2240 *
2241 * There is a chance, that some mode reports are not fully in line with xterm.js' behavior,
2242 * e.g. if the default implementation already exposes a certain behavior. If you find
2243 * discrepancies in the mode reports, please file a bug.
2244 */
2245 public requestMode(params: IParams, ansi: boolean): boolean {
2246 // return value as in DECRPM
2247 const enum V {
2248 NOT_RECOGNIZED = 0,
2249 SET = 1,
2250 RESET = 2,
2251 PERMANENTLY_SET = 3,
2252 PERMANENTLY_RESET = 4
2253 }
2254
2255 // access helpers
2256 const dm = this._coreService.decPrivateModes;
2257 const { activeProtocol: mouseProtocol, activeEncoding: mouseEncoding } = this._coreMouseService;
2258 const cs = this._coreService;
2259 const { buffers, cols } = this._bufferService;
2260 const { active, alt } = buffers;
2261 const opts = this._optionsService.rawOptions;
2262
2263 const f = (m: number, v: V): boolean => {
2264 cs.triggerDataEvent(`${C0.ESC}[${ansi ? '' : '?'}${m};${v}$y`);
2265 return true;
2266 };
2267 const b2v = (value: boolean): V => value ? V.SET : V.RESET;
2268
2269 const p = params.params[0];
2270
2271 if (ansi) {
2272 if (p === 2) return f(p, V.PERMANENTLY_RESET);
2273 if (p === 4) return f(p, b2v(cs.modes.insertMode));
2274 if (p === 12) return f(p, V.PERMANENTLY_SET);
2275 if (p === 20) return f(p, b2v(opts.convertEol));
2276 return f(p, V.NOT_RECOGNIZED);
2277 }
2278
2279 if (p === 1) return f(p, b2v(dm.applicationCursorKeys));
2280 if (p === 3) return f(p, opts.windowOptions.setWinLines ? (cols === 80 ? V.RESET : cols === 132 ? V.SET : V.NOT_RECOGNIZED) : V.NOT_RECOGNIZED);
2281 if (p === 6) return f(p, b2v(dm.origin));
2282 if (p === 7) return f(p, b2v(dm.wraparound));
2283 if (p === 8) return f(p, V.PERMANENTLY_SET);
2284 if (p === 9) return f(p, b2v(mouseProtocol === 'X10'));
2285 if (p === 12) return f(p, b2v(opts.cursorBlink));
2286 if (p === 25) return f(p, b2v(!cs.isCursorHidden));
2287 if (p === 45) return f(p, b2v(dm.reverseWraparound));
2288 if (p === 66) return f(p, b2v(dm.applicationKeypad));
2289 if (p === 67) return f(p, V.PERMANENTLY_RESET);
2290 if (p === 1000) return f(p, b2v(mouseProtocol === 'VT200'));
2291 if (p === 1002) return f(p, b2v(mouseProtocol === 'DRAG'));
2292 if (p === 1003) return f(p, b2v(mouseProtocol === 'ANY'));
2293 if (p === 1004) return f(p, b2v(dm.sendFocus));
2294 if (p === 1005) return f(p, V.PERMANENTLY_RESET);
2295 if (p === 1006) return f(p, b2v(mouseEncoding === 'SGR'));
2296 if (p === 1015) return f(p, V.PERMANENTLY_RESET);
2297 if (p === 1016) return f(p, b2v(mouseEncoding === 'SGR_PIXELS'));
2298 if (p === 1048) return f(p, V.SET); // xterm always returns SET here
2299 if (p === 47 || p === 1047 || p === 1049) return f(p, b2v(active === alt));
2300 if (p === 2004) return f(p, b2v(dm.bracketedPasteMode));
2301 if (p === 2026) return f(p, b2v(dm.synchronizedOutput));
2302 return f(p, V.NOT_RECOGNIZED);
2303 }
2304
2305 /**
2306 * Helper to write color information packed with color mode.
2307 */
2308 private _updateAttrColor(color: number, mode: number, c1: number, c2: number, c3: number): number {
2309 if (mode === 2) {
2310 color |= Attributes.CM_RGB;
2311 color &= ~Attributes.RGB_MASK;
2312 color |= AttributeData.fromColorRGB([c1, c2, c3]);
2313 } else if (mode === 5) {
2314 color &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
2315 color |= Attributes.CM_P256 | (c1 & 0xff);
2316 }
2317 return color;
2318 }
2319
2320 /**
2321 * Helper to extract and apply color params/subparams.
2322 * Returns advance for params index.
2323 */
2324 private _extractColor(params: IParams, pos: number, attr: IAttributeData): number {
2325 // normalize params
2326 // meaning: [target, CM, ign, val, val, val]
2327 // RGB : [ 38/48, 2, ign, r, g, b]
2328 // P256 : [ 38/48, 5, ign, v, ign, ign]
2329 const accu = [0, 0, -1, 0, 0, 0];
2330
2331 // alignment placeholder for non color space sequences
2332 let cSpace = 0;
2333
2334 // return advance we took in params
2335 let advance = 0;
2336
2337 do {
2338 accu[advance + cSpace] = params.params[pos + advance];
2339 if (params.hasSubParams(pos + advance)) {
2340 const subparams = params.getSubParams(pos + advance)!;
2341 let i = 0;
2342 do {
2343 if (accu[1] === 5) {
2344 cSpace = 1;
2345 }
2346 accu[advance + i + 1 + cSpace] = subparams[i];
2347 } while (++i < subparams.length && i + advance + 1 + cSpace < accu.length);
2348 break;
2349 }
2350 // exit early if can decide color mode with semicolons
2351 if ((accu[1] === 5 && advance + cSpace >= 2)
2352 || (accu[1] === 2 && advance + cSpace >= 5)) {
2353 break;
2354 }
2355 // offset colorSpace slot for semicolon mode
2356 if (accu[1]) {
2357 cSpace = 1;
2358 }
2359 } while (++advance + pos < params.length && advance + cSpace < accu.length);
2360
2361 // set default values to 0
2362 for (let i = 2; i < accu.length; ++i) {
2363 if (accu[i] === -1) {
2364 accu[i] = 0;
2365 }
2366 }
2367
2368 // apply colors
2369 switch (accu[0]) {
2370 case 38:
2371 attr.fg = this._updateAttrColor(attr.fg, accu[1], accu[3], accu[4], accu[5]);
2372 break;
2373 case 48:
2374 attr.bg = this._updateAttrColor(attr.bg, accu[1], accu[3], accu[4], accu[5]);
2375 break;
2376 case 58:
2377 attr.extended = attr.extended.clone();
2378 attr.extended.underlineColor = this._updateAttrColor(attr.extended.underlineColor, accu[1], accu[3], accu[4], accu[5]);
2379 }
2380
2381 return advance;
2382 }
2383
2384 /**
2385 * SGR 4 subparams:
2386 * 4:0 - equal to SGR 24 (turn off all underline)
2387 * 4:1 - equal to SGR 4 (single underline)
2388 * 4:2 - equal to SGR 21 (double underline)
2389 * 4:3 - curly underline
2390 * 4:4 - dotted underline
2391 * 4:5 - dashed underline
2392 */
2393 private _processUnderline(style: number, attr: IAttributeData): void {
2394 // treat extended attrs as immutable, thus always clone from old one
2395 // this is needed since the buffer only holds references to it
2396 attr.extended = attr.extended.clone();
2397
2398 // default to 1 == single underline
2399 if (!~style || style > 5) {
2400 style = 1;
2401 }
2402 attr.extended.underlineStyle = style;
2403 attr.fg |= FgFlags.UNDERLINE;
2404
2405 // 0 deactivates underline
2406 if (style === 0) {
2407 attr.fg &= ~FgFlags.UNDERLINE;
2408 }
2409
2410 // update HAS_EXTENDED in BG
2411 attr.updateExtended();
2412 }
2413
2414 private _processSGR0(attr: IAttributeData): void {
2415 attr.fg = DEFAULT_ATTR_DATA.fg;
2416 attr.bg = DEFAULT_ATTR_DATA.bg;
2417 attr.extended = attr.extended.clone();
2418 // Reset underline style and color. Note that we don't want to reset other
2419 // fields such as the url id.
2420 attr.extended.underlineStyle = UnderlineStyle.NONE;
2421 attr.extended.underlineColor &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
2422 attr.updateExtended();
2423 }
2424
2425 /**
2426 * CSI Pm m Character Attributes (SGR).
2427 *
2428 * @vt: #P[See below for supported attributes.] CSI SGR "Select Graphic Rendition" "CSI Pm m" "Set/Reset various text attributes."
2429 * SGR selects one or more character attributes at the same time. Multiple params (up to 32)
2430 * are applied in order from left to right. The changed attributes are applied to all new
2431 * characters received. If you move characters in the viewport by scrolling or any other means,
2432 * then the attributes move with the characters.
2433 *
2434 * Supported param values by SGR:
2435 *
2436 * | Param | Meaning | Support |
2437 * | --------- | -------------------------------------------------------- | ------- |
2438 * | 0 | Normal (default). Resets any other preceding SGR. | #Y |
2439 * | 1 | Bold. (also see `options.drawBoldTextInBrightColors`) | #Y |
2440 * | 2 | Faint, decreased intensity. | #Y |
2441 * | 3 | Italic. | #Y |
2442 * | 4 | Underlined (see below for style support). | #Y |
2443 * | 5 | Slowly blinking. | #N |
2444 * | 6 | Rapidly blinking. | #N |
2445 * | 7 | Inverse. Flips foreground and background color. | #Y |
2446 * | 8 | Invisible (hidden). | #Y |
2447 * | 9 | Crossed-out characters (strikethrough). | #Y |
2448 * | 21 | Doubly underlined. | #Y |
2449 * | 22 | Normal (neither bold nor faint). | #Y |
2450 * | 23 | No italic. | #Y |
2451 * | 24 | Not underlined. | #Y |
2452 * | 25 | Steady (not blinking). | #Y |
2453 * | 27 | Positive (not inverse). | #Y |
2454 * | 28 | Visible (not hidden). | #Y |
2455 * | 29 | Not Crossed-out (strikethrough). | #Y |
2456 * | 30 | Foreground color: Black. | #Y |
2457 * | 31 | Foreground color: Red. | #Y |
2458 * | 32 | Foreground color: Green. | #Y |
2459 * | 33 | Foreground color: Yellow. | #Y |
2460 * | 34 | Foreground color: Blue. | #Y |
2461 * | 35 | Foreground color: Magenta. | #Y |
2462 * | 36 | Foreground color: Cyan. | #Y |
2463 * | 37 | Foreground color: White. | #Y |
2464 * | 38 | Foreground color: Extended color. | #P[Support for RGB and indexed colors, see below.] |
2465 * | 39 | Foreground color: Default (original). | #Y |
2466 * | 40 | Background color: Black. | #Y |
2467 * | 41 | Background color: Red. | #Y |
2468 * | 42 | Background color: Green. | #Y |
2469 * | 43 | Background color: Yellow. | #Y |
2470 * | 44 | Background color: Blue. | #Y |
2471 * | 45 | Background color: Magenta. | #Y |
2472 * | 46 | Background color: Cyan. | #Y |
2473 * | 47 | Background color: White. | #Y |
2474 * | 48 | Background color: Extended color. | #P[Support for RGB and indexed colors, see below.] |
2475 * | 49 | Background color: Default (original). | #Y |
2476 * | 53 | Overlined. | #Y |
2477 * | 55 | Not Overlined. | #Y |
2478 * | 58 | Underline color: Extended color. | #P[Support for RGB and indexed colors, see below.] |
2479 * | 90 - 97 | Bright foreground color (analogous to 30 - 37). | #Y |
2480 * | 100 - 107 | Bright background color (analogous to 40 - 47). | #Y |
2481 *
2482 * Underline supports subparams to denote the style in the form `4 : x`:
2483 *
2484 * | x | Meaning | Support |
2485 * | ------ | ------------------------------------------------------------- | ------- |
2486 * | 0 | No underline. Same as `SGR 24 m`. | #Y |
2487 * | 1 | Single underline. Same as `SGR 4 m`. | #Y |
2488 * | 2 | Double underline. | #Y |
2489 * | 3 | Curly underline. | #Y |
2490 * | 4 | Dotted underline. | #Y |
2491 * | 5 | Dashed underline. | #Y |
2492 * | other | Single underline. Same as `SGR 4 m`. | #Y |
2493 *
2494 * Extended colors are supported for foreground (Ps=38), background (Ps=48) and underline (Ps=58)
2495 * as follows:
2496 *
2497 * | Ps + 1 | Meaning | Support |
2498 * | ------ | ------------------------------------------------------------- | ------- |
2499 * | 0 | Implementation defined. | #N |
2500 * | 1 | Transparent. | #N |
2501 * | 2 | RGB color as `Ps ; 2 ; R ; G ; B` or `Ps : 2 : : R : G : B`. | #Y |
2502 * | 3 | CMY color. | #N |
2503 * | 4 | CMYK color. | #N |
2504 * | 5 | Indexed (256 colors) as `Ps ; 5 ; INDEX` or `Ps : 5 : INDEX`. | #Y |
2505 *
2506 *
2507 * FIXME: blinking is implemented in attrs, but not working in renderers?
2508 * FIXME: remove dead branch for p=100
2509 */
2510 public charAttributes(params: IParams): boolean {
2511 // Optimize a single SGR0.
2512 if (params.length === 1 && params.params[0] === 0) {
2513 this._processSGR0(this._curAttrData);
2514 return true;
2515 }
2516
2517 const l = params.length;
2518 let p;
2519 const attr = this._curAttrData;
2520
2521 for (let i = 0; i < l; i++) {
2522 p = params.params[i];
2523 if (p >= 30 && p <= 37) {
2524 // fg color 8
2525 attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
2526 attr.fg |= Attributes.CM_P16 | (p - 30);
2527 } else if (p >= 40 && p <= 47) {
2528 // bg color 8
2529 attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
2530 attr.bg |= Attributes.CM_P16 | (p - 40);
2531 } else if (p >= 90 && p <= 97) {
2532 // fg color 16
2533 attr.fg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
2534 attr.fg |= Attributes.CM_P16 | (p - 90) | 8;
2535 } else if (p >= 100 && p <= 107) {
2536 // bg color 16
2537 attr.bg &= ~(Attributes.CM_MASK | Attributes.PCOLOR_MASK);
2538 attr.bg |= Attributes.CM_P16 | (p - 100) | 8;
2539 } else if (p === 0) {
2540 // default
2541 this._processSGR0(attr);
2542 } else if (p === 1) {
2543 // bold text
2544 attr.fg |= FgFlags.BOLD;
2545 } else if (p === 3) {
2546 // italic text
2547 attr.bg |= BgFlags.ITALIC;
2548 } else if (p === 4) {
2549 // underlined text
2550 attr.fg |= FgFlags.UNDERLINE;
2551 this._processUnderline(params.hasSubParams(i) ? params.getSubParams(i)![0] : UnderlineStyle.SINGLE, attr);
2552 } else if (p === 5) {
2553 // blink
2554 attr.fg |= FgFlags.BLINK;
2555 } else if (p === 7) {
2556 // inverse and positive
2557 // test with: echo -e '\e[31m\e[42mhello\e[7mworld\e[27mhi\e[m'
2558 attr.fg |= FgFlags.INVERSE;
2559 } else if (p === 8) {
2560 // invisible
2561 attr.fg |= FgFlags.INVISIBLE;
2562 } else if (p === 9) {
2563 // strikethrough
2564 attr.fg |= FgFlags.STRIKETHROUGH;
2565 } else if (p === 2) {
2566 // dimmed text
2567 attr.bg |= BgFlags.DIM;
2568 } else if (p === 21) {
2569 // double underline
2570 this._processUnderline(UnderlineStyle.DOUBLE, attr);
2571 } else if (p === 22) {
2572 // not bold nor faint
2573 attr.fg &= ~FgFlags.BOLD;
2574 attr.bg &= ~BgFlags.DIM;
2575 } else if (p === 23) {
2576 // not italic
2577 attr.bg &= ~BgFlags.ITALIC;
2578 } else if (p === 24) {
2579 // not underlined
2580 attr.fg &= ~FgFlags.UNDERLINE;
2581 this._processUnderline(UnderlineStyle.NONE, attr);
2582 } else if (p === 25) {
2583 // not blink
2584 attr.fg &= ~FgFlags.BLINK;
2585 } else if (p === 27) {
2586 // not inverse
2587 attr.fg &= ~FgFlags.INVERSE;
2588 } else if (p === 28) {
2589 // not invisible
2590 attr.fg &= ~FgFlags.INVISIBLE;
2591 } else if (p === 29) {
2592 // not strikethrough
2593 attr.fg &= ~FgFlags.STRIKETHROUGH;
2594 } else if (p === 39) {
2595 // reset fg
2596 attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
2597 attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
2598 } else if (p === 49) {
2599 // reset bg
2600 attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
2601 attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
2602 } else if (p === 38 || p === 48 || p === 58) {
2603 // fg color 256 and RGB
2604 i += this._extractColor(params, i, attr);
2605 } else if (p === 53) {
2606 // overline
2607 attr.bg |= BgFlags.OVERLINE;
2608 } else if (p === 55) {
2609 // not overline
2610 attr.bg &= ~BgFlags.OVERLINE;
2611 } else if (p === 59) {
2612 attr.extended = attr.extended.clone();
2613 attr.extended.underlineColor = -1;
2614 attr.updateExtended();
2615 } else if (p === 100) { // FIXME: dead branch, p=100 already handled above!
2616 // reset fg/bg
2617 attr.fg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
2618 attr.fg |= DEFAULT_ATTR_DATA.fg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
2619 attr.bg &= ~(Attributes.CM_MASK | Attributes.RGB_MASK);
2620 attr.bg |= DEFAULT_ATTR_DATA.bg & (Attributes.PCOLOR_MASK | Attributes.RGB_MASK);
2621 } else {
2622 this._logService.debug('Unknown SGR attribute: %d.', p);
2623 }
2624 }
2625 return true;
2626 }
2627
2628 /**
2629 * CSI Ps n Device Status Report (DSR).
2630 * Ps = 5 -> Status Report. Result (``OK'') is
2631 * CSI 0 n
2632 * Ps = 6 -> Report Cursor Position (CPR) [row;column].
2633 * Result is
2634 * CSI r ; c R
2635 * CSI ? Ps n
2636 * Device Status Report (DSR, DEC-specific).
2637 * Ps = 6 -> Report Cursor Position (CPR) [row;column] as CSI
2638 * ? r ; c R (assumes page is zero).
2639 * Ps = 1 5 -> Report Printer status as CSI ? 1 0 n (ready).
2640 * or CSI ? 1 1 n (not ready).
2641 * Ps = 2 5 -> Report UDK status as CSI ? 2 0 n (unlocked)
2642 * or CSI ? 2 1 n (locked).
2643 * Ps = 2 6 -> Report Keyboard status as
2644 * CSI ? 2 7 ; 1 ; 0 ; 0 n (North American).
2645 * The last two parameters apply to VT400 & up, and denote key-
2646 * board ready and LK01 respectively.
2647 * Ps = 5 3 -> Report Locator status as
2648 * CSI ? 5 3 n Locator available, if compiled-in, or
2649 * CSI ? 5 0 n No Locator, if not.
2650 *
2651 * @vt: #Y CSI DSR "Device Status Report" "CSI Ps n" "Request cursor position (CPR) with `Ps` = 6."
2652 */
2653 public deviceStatus(params: IParams): boolean {
2654 switch (params.params[0]) {
2655 case 5:
2656 // status report
2657 this._coreService.triggerDataEvent(`${C0.ESC}[0n`);
2658 break;
2659 case 6:
2660 // cursor position
2661 const y = this._activeBuffer.y + 1;
2662 const x = this._activeBuffer.x + 1;
2663 this._coreService.triggerDataEvent(`${C0.ESC}[${y};${x}R`);
2664 break;
2665 }
2666 return true;
2667 }
2668
2669 // @vt: #P[Only CPR is supported.] CSI DECDSR "DEC Device Status Report" "CSI ? Ps n" "Only CPR is supported (same as DSR)."
2670 public deviceStatusPrivate(params: IParams): boolean {
2671 // modern xterm doesnt seem to
2672 // respond to any of these except ?6, 6, and 5
2673 switch (params.params[0]) {
2674 case 6:
2675 // cursor position
2676 const y = this._activeBuffer.y + 1;
2677 const x = this._activeBuffer.x + 1;
2678 this._coreService.triggerDataEvent(`${C0.ESC}[?${y};${x}R`);
2679 break;
2680 case 15:
2681 // no printer
2682 // this.handler(C0.ESC + '[?11n');
2683 break;
2684 case 25:
2685 // dont support user defined keys
2686 // this.handler(C0.ESC + '[?21n');
2687 break;
2688 case 26:
2689 // north american keyboard
2690 // this.handler(C0.ESC + '[?27;1;0;0n');
2691 break;
2692 case 53:
2693 // no dec locator/mouse
2694 // this.handler(C0.ESC + '[?50n');
2695 break;
2696 }
2697 return true;
2698 }
2699
2700 /**
2701 * CSI ! p Soft terminal reset (DECSTR).
2702 * http://vt100.net/docs/vt220-rm/table4-10.html
2703 *
2704 * @vt: #Y CSI DECSTR "Soft Terminal Reset" "CSI ! p" "Reset several terminal attributes to initial state."
2705 * There are two terminal reset sequences - RIS and DECSTR. While RIS performs almost a full
2706 * terminal bootstrap, DECSTR only resets certain attributes. For most needs DECSTR should be
2707 * sufficient.
2708 *
2709 * The following terminal attributes are reset to default values:
2710 * - IRM is reset (dafault = false)
2711 * - scroll margins are reset (default = viewport size)
2712 * - erase attributes are reset to default
2713 * - charsets are reset
2714 * - DECSC data is reset to initial values
2715 * - DECOM is reset to absolute mode
2716 *
2717 *
2718 * FIXME: there are several more attributes missing (see VT520 manual)
2719 */
2720 public softReset(params: IParams): boolean {
2721 this._coreService.isCursorHidden = false;
2722 this._onRequestSyncScrollBar.fire();
2723 this._activeBuffer.scrollTop = 0;
2724 this._activeBuffer.scrollBottom = this._bufferService.rows - 1;
2725 this._curAttrData = DEFAULT_ATTR_DATA.clone();
2726 this._coreService.reset();
2727 this._charsetService.reset();
2728
2729 // reset DECSC data
2730 this._activeBuffer.savedX = 0;
2731 this._activeBuffer.savedY = this._activeBuffer.ybase;
2732 this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;
2733 this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;
2734 this._activeBuffer.savedCharset = this._charsetService.charset;
2735
2736 // reset DECOM
2737 this._coreService.decPrivateModes.origin = false;
2738 return true;
2739 }
2740
2741 /**
2742 * CSI Ps SP q Set cursor style (DECSCUSR, VT520).
2743 * Ps = 0 -> reset to option.
2744 * Ps = 1 -> blinking block (default).
2745 * Ps = 2 -> steady block.
2746 * Ps = 3 -> blinking underline.
2747 * Ps = 4 -> steady underline.
2748 * Ps = 5 -> blinking bar (xterm).
2749 * Ps = 6 -> steady bar (xterm).
2750 *
2751 * @vt: #Y CSI DECSCUSR "Set Cursor Style" "CSI Ps SP q" "Set cursor style."
2752 * Supported cursor styles:
2753 * - 0: reset to option
2754 * - empty, 1: blinking block
2755 * - 2: steady block
2756 * - 3: blinking underline
2757 * - 4: steady underline
2758 * - 5: blinking bar
2759 * - 6: steady bar
2760 */
2761 public setCursorStyle(params: IParams): boolean {
2762 const param = params.length === 0 ? 1 : params.params[0];
2763 if (param === 0) {
2764 this._coreService.decPrivateModes.cursorStyle = undefined;
2765 this._coreService.decPrivateModes.cursorBlink = undefined;
2766 } else {
2767 switch (param) {
2768 case 1:
2769 case 2:
2770 this._coreService.decPrivateModes.cursorStyle = 'block';
2771 break;
2772 case 3:
2773 case 4:
2774 this._coreService.decPrivateModes.cursorStyle = 'underline';
2775 break;
2776 case 5:
2777 case 6:
2778 this._coreService.decPrivateModes.cursorStyle = 'bar';
2779 break;
2780 }
2781 const isBlinking = param % 2 === 1;
2782 this._coreService.decPrivateModes.cursorBlink = isBlinking;
2783 }
2784 return true;
2785 }
2786
2787 /**
2788 * CSI Ps ; Ps r
2789 * Set Scrolling Region [top;bottom] (default = full size of win-
2790 * dow) (DECSTBM).
2791 *
2792 * @vt: #Y CSI DECSTBM "Set Top and Bottom Margin" "CSI Ps ; Ps r" "Set top and bottom margins of the viewport [top;bottom] (default = viewport size)."
2793 */
2794 public setScrollRegion(params: IParams): boolean {
2795 const top = params.params[0] || 1;
2796 let bottom: number;
2797
2798 if (params.length < 2 || (bottom = params.params[1]) > this._bufferService.rows || bottom === 0) {
2799 bottom = this._bufferService.rows;
2800 }
2801
2802 if (bottom > top) {
2803 this._activeBuffer.scrollTop = top - 1;
2804 this._activeBuffer.scrollBottom = bottom - 1;
2805 this._setCursor(0, 0);
2806 }
2807 return true;
2808 }
2809
2810 /**
2811 * CSI Ps ; Ps ; Ps t - Various window manipulations and reports (xterm)
2812 *
2813 * Note: Only those listed below are supported. All others are left to integrators and
2814 * need special treatment based on the embedding environment.
2815 *
2816 * Ps = 1 4 supported
2817 * Report xterm text area size in pixels.
2818 * Result is CSI 4 ; height ; width t
2819 * Ps = 14 ; 2 not implemented
2820 * Ps = 16 supported
2821 * Report xterm character cell size in pixels.
2822 * Result is CSI 6 ; height ; width t
2823 * Ps = 18 supported
2824 * Report the size of the text area in characters.
2825 * Result is CSI 8 ; height ; width t
2826 * Ps = 20 supported
2827 * Report xterm window's icon label.
2828 * Result is OSC L label ST
2829 * Ps = 21 supported
2830 * Report xterm window's title.
2831 * Result is OSC l label ST
2832 * Ps = 22 ; 0 -> Save xterm icon and window title on stack. supported
2833 * Ps = 22 ; 1 -> Save xterm icon title on stack. supported
2834 * Ps = 22 ; 2 -> Save xterm window title on stack. supported
2835 * Ps = 23 ; 0 -> Restore xterm icon and window title from stack. supported
2836 * Ps = 23 ; 1 -> Restore xterm icon title from stack. supported
2837 * Ps = 23 ; 2 -> Restore xterm window title from stack. supported
2838 * Ps >= 24 not implemented
2839 */
2840 public windowOptions(params: IParams): boolean {
2841 if (!paramToWindowOption(params.params[0], this._optionsService.rawOptions.windowOptions)) {
2842 return true;
2843 }
2844 const second = (params.length > 1) ? params.params[1] : 0;
2845 switch (params.params[0]) {
2846 case 14: // GetWinSizePixels, returns CSI 4 ; height ; width t
2847 if (second !== 2) {
2848 this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_WIN_SIZE_PIXELS);
2849 }
2850 break;
2851 case 16: // GetCellSizePixels, returns CSI 6 ; height ; width t
2852 this._onRequestWindowsOptionsReport.fire(WindowsOptionsReportType.GET_CELL_SIZE_PIXELS);
2853 break;
2854 case 18: // GetWinSizeChars, returns CSI 8 ; height ; width t
2855 if (this._bufferService) {
2856 this._coreService.triggerDataEvent(`${C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);
2857 }
2858 break;
2859 case 22: // PushTitle
2860 if (second === 0 || second === 2) {
2861 this._windowTitleStack.push(this._windowTitle);
2862 if (this._windowTitleStack.length > STACK_LIMIT) {
2863 this._windowTitleStack.shift();
2864 }
2865 }
2866 if (second === 0 || second === 1) {
2867 this._iconNameStack.push(this._iconName);
2868 if (this._iconNameStack.length > STACK_LIMIT) {
2869 this._iconNameStack.shift();
2870 }
2871 }
2872 break;
2873 case 23: // PopTitle
2874 if (second === 0 || second === 2) {
2875 if (this._windowTitleStack.length) {
2876 this.setTitle(this._windowTitleStack.pop()!);
2877 }
2878 }
2879 if (second === 0 || second === 1) {
2880 if (this._iconNameStack.length) {
2881 this.setIconName(this._iconNameStack.pop()!);
2882 }
2883 }
2884 break;
2885 }
2886 return true;
2887 }
2888
2889
2890 /**
2891 * CSI s
2892 * ESC 7
2893 * Save cursor (ANSI.SYS).
2894 *
2895 * @vt: #P[TODO...] CSI SCOSC "Save Cursor" "CSI s" "Save cursor position, charmap and text attributes."
2896 * @vt: #Y ESC SC "Save Cursor" "ESC 7" "Save cursor position, charmap and text attributes."
2897 */
2898 public saveCursor(params?: IParams): boolean {
2899 this._activeBuffer.savedX = this._activeBuffer.x;
2900 this._activeBuffer.savedY = this._activeBuffer.ybase + this._activeBuffer.y;
2901 this._activeBuffer.savedCurAttrData.fg = this._curAttrData.fg;
2902 this._activeBuffer.savedCurAttrData.bg = this._curAttrData.bg;
2903 this._activeBuffer.savedCharset = this._charsetService.charset;
2904 return true;
2905 }
2906
2907
2908 /**
2909 * CSI u
2910 * ESC 8
2911 * Restore cursor (ANSI.SYS).
2912 *
2913 * @vt: #P[TODO...] CSI SCORC "Restore Cursor" "CSI u" "Restore cursor position, charmap and text attributes."
2914 * @vt: #Y ESC RC "Restore Cursor" "ESC 8" "Restore cursor position, charmap and text attributes."
2915 */
2916 public restoreCursor(params?: IParams): boolean {
2917 this._activeBuffer.x = this._activeBuffer.savedX || 0;
2918 this._activeBuffer.y = Math.max(this._activeBuffer.savedY - this._activeBuffer.ybase, 0);
2919 this._curAttrData.fg = this._activeBuffer.savedCurAttrData.fg;
2920 this._curAttrData.bg = this._activeBuffer.savedCurAttrData.bg;
2921 this._charsetService.charset = (this as any)._savedCharset;
2922 if (this._activeBuffer.savedCharset) {
2923 this._charsetService.charset = this._activeBuffer.savedCharset;
2924 }
2925 this._restrictCursor();
2926 return true;
2927 }
2928
2929
2930 /**
2931 * OSC 2; <data> ST (set window title)
2932 * Proxy to set window title.
2933 *
2934 * @vt: #P[Icon name is not exposed.] OSC 0 "Set Windows Title and Icon Name" "OSC 0 ; Pt BEL" "Set window title and icon name."
2935 * Icon name is not supported. For Window Title see below.
2936 *
2937 * @vt: #Y OSC 2 "Set Windows Title" "OSC 2 ; Pt BEL" "Set window title."
2938 * xterm.js does not manipulate the title directly, instead exposes changes via the event
2939 * `Terminal.onTitleChange`.
2940 */
2941 public setTitle(data: string): boolean {
2942 this._windowTitle = data;
2943 this._onTitleChange.fire(data);
2944 return true;
2945 }
2946
2947 /**
2948 * OSC 1; <data> ST
2949 * Note: Icon name is not exposed.
2950 */
2951 public setIconName(data: string): boolean {
2952 this._iconName = data;
2953 return true;
2954 }
2955
2956 /**
2957 * OSC 4; <num> ; <text> ST (set ANSI color <num> to <text>)
2958 *
2959 * @vt: #Y OSC 4 "Set ANSI color" "OSC 4 ; c ; spec BEL" "Change color number `c` to the color specified by `spec`."
2960 * `c` is the color index between 0 and 255. The color format of `spec` is derived from
2961 * `XParseColor` (see OSC 10 for supported formats). There may be multipe `c ; spec` pairs present
2962 * in the same instruction. If `spec` contains `?` the terminal returns a sequence with the
2963 * currently set color.
2964 */
2965 public setOrReportIndexedColor(data: string): boolean {
2966 const event: IColorEvent = [];
2967 const slots = data.split(';');
2968 while (slots.length > 1) {
2969 const idx = slots.shift() as string;
2970 const spec = slots.shift() as string;
2971 if (/^\d+$/.exec(idx)) {
2972 const index = parseInt(idx);
2973 if (isValidColorIndex(index)) {
2974 if (spec === '?') {
2975 event.push({ type: ColorRequestType.REPORT, index });
2976 } else {
2977 const color = parseColor(spec);
2978 if (color) {
2979 event.push({ type: ColorRequestType.SET, index, color });
2980 }
2981 }
2982 }
2983 }
2984 }
2985 if (event.length) {
2986 this._onColor.fire(event);
2987 }
2988 return true;
2989 }
2990
2991 /**
2992 * OSC 8 ; <params> ; <uri> ST - create hyperlink
2993 * OSC 8 ; ; ST - finish hyperlink
2994 *
2995 * Test case:
2996 *
2997 * ```sh
2998 * printf '\e]8;;http://example.com\e\\This is a link\e]8;;\e\\\n'
2999 * ```
3000 *
3001 * @vt: #Y OSC 8 "Create hyperlink" "OSC 8 ; params ; uri BEL" "Create a hyperlink to `uri` using `params`."
3002 * `uri` is a hyperlink starting with `http://`, `https://`, `ftp://`, `file://` or `mailto://`. `params` is an
3003 * optional list of key=value assignments, separated by the : character.
3004 * Example: `id=xyz123:foo=bar:baz=quux`.
3005 * Currently only the id key is defined. Cells that share the same ID and URI share hover
3006 * feedback. Use `OSC 8 ; ; BEL` to finish the current hyperlink.
3007 */
3008 public setHyperlink(data: string): boolean {
3009 // Arg parsing is special cases to support unencoded semi-colons in the URIs (#4944)
3010 const idx = data.indexOf(';');
3011 if (idx === -1) {
3012 // malformed sequence, just return as handled
3013 return true;
3014 }
3015 const id = data.slice(0, idx).trim();
3016 const uri = data.slice(idx + 1);
3017 if (uri) {
3018 return this._createHyperlink(id, uri);
3019 }
3020 if (id.trim()) {
3021 return false;
3022 }
3023 return this._finishHyperlink();
3024 }
3025
3026 private _createHyperlink(params: string, uri: string): boolean {
3027 // It's legal to open a new hyperlink without explicitly finishing the previous one
3028 if (this._getCurrentLinkId()) {
3029 this._finishHyperlink();
3030 }
3031 const parsedParams = params.split(':');
3032 let id: string | undefined;
3033 const idParamIndex = parsedParams.findIndex(e => e.startsWith('id='));
3034 if (idParamIndex !== -1) {
3035 id = parsedParams[idParamIndex].slice(3) || undefined;
3036 }
3037 this._curAttrData.extended = this._curAttrData.extended.clone();
3038 this._curAttrData.extended.urlId = this._oscLinkService.registerLink({ id, uri });
3039 this._curAttrData.updateExtended();
3040 return true;
3041 }
3042
3043 private _finishHyperlink(): boolean {
3044 this._curAttrData.extended = this._curAttrData.extended.clone();
3045 this._curAttrData.extended.urlId = 0;
3046 this._curAttrData.updateExtended();
3047 return true;
3048 }
3049
3050 // special colors - OSC 10 | 11 | 12
3051 private _specialColors = [SpecialColorIndex.FOREGROUND, SpecialColorIndex.BACKGROUND, SpecialColorIndex.CURSOR];
3052
3053 /**
3054 * Apply colors requests for special colors in OSC 10 | 11 | 12.
3055 * Since these commands are stacking from multiple parameters,
3056 * we handle them in a loop with an entry offset to `_specialColors`.
3057 */
3058 private _setOrReportSpecialColor(data: string, offset: number): boolean {
3059 const slots = data.split(';');
3060 for (let i = 0; i < slots.length; ++i, ++offset) {
3061 if (offset >= this._specialColors.length) break;
3062 if (slots[i] === '?') {
3063 this._onColor.fire([{ type: ColorRequestType.REPORT, index: this._specialColors[offset] }]);
3064 } else {
3065 const color = parseColor(slots[i]);
3066 if (color) {
3067 this._onColor.fire([{ type: ColorRequestType.SET, index: this._specialColors[offset], color }]);
3068 }
3069 }
3070 }
3071 return true;
3072 }
3073
3074 /**
3075 * OSC 10 ; <xcolor name>|<?> ST - set or query default foreground color
3076 *
3077 * @vt: #Y OSC 10 "Set or query default foreground color" "OSC 10 ; Pt BEL" "Set or query default foreground color."
3078 * To set the color, the following color specification formats are supported:
3079 * - `rgb:<red>/<green>/<blue>` for `<red>, <green>, <blue>` in `h | hh | hhh | hhhh`, where
3080 * `h` is a single hexadecimal digit (case insignificant). The different widths scale
3081 * from 4 bit (`h`) to 16 bit (`hhhh`) and get converted to 8 bit (`hh`).
3082 * - `#RGB` - 4 bits per channel, expanded to `#R0G0B0`
3083 * - `#RRGGBB` - 8 bits per channel
3084 * - `#RRRGGGBBB` - 12 bits per channel, truncated to `#RRGGBB`
3085 * - `#RRRRGGGGBBBB` - 16 bits per channel, truncated to `#RRGGBB`
3086 *
3087 * **Note:** X11 named colors are currently unsupported.
3088 *
3089 * If `Pt` contains `?` instead of a color specification, the terminal
3090 * returns a sequence with the current default foreground color
3091 * (use that sequence to restore the color after changes).
3092 *
3093 * **Note:** Other than xterm, xterm.js does not support OSC 12 - 19.
3094 * Therefore stacking multiple `Pt` separated by `;` only works for the first two entries.
3095 */
3096 public setOrReportFgColor(data: string): boolean {
3097 return this._setOrReportSpecialColor(data, 0);
3098 }
3099
3100 /**
3101 * OSC 11 ; <xcolor name>|<?> ST - set or query default background color
3102 *
3103 * @vt: #Y OSC 11 "Set or query default background color" "OSC 11 ; Pt BEL" "Same as OSC 10, but for default background."
3104 */
3105 public setOrReportBgColor(data: string): boolean {
3106 return this._setOrReportSpecialColor(data, 1);
3107 }
3108
3109 /**
3110 * OSC 12 ; <xcolor name>|<?> ST - set or query default cursor color
3111 *
3112 * @vt: #Y OSC 12 "Set or query default cursor color" "OSC 12 ; Pt BEL" "Same as OSC 10, but for default cursor color."
3113 */
3114 public setOrReportCursorColor(data: string): boolean {
3115 return this._setOrReportSpecialColor(data, 2);
3116 }
3117
3118 /**
3119 * OSC 104 ; <num> ST - restore ANSI color <num>
3120 *
3121 * @vt: #Y OSC 104 "Reset ANSI color" "OSC 104 ; c BEL" "Reset color number `c` to themed color."
3122 * `c` is the color index between 0 and 255. This function restores the default color for `c` as
3123 * specified by the loaded theme. Any number of `c` parameters may be given.
3124 * If no parameters are given, the entire indexed color table will be reset.
3125 */
3126 public restoreIndexedColor(data: string): boolean {
3127 if (!data) {
3128 this._onColor.fire([{ type: ColorRequestType.RESTORE }]);
3129 return true;
3130 }
3131 const event: IColorEvent = [];
3132 const slots = data.split(';');
3133 for (let i = 0; i < slots.length; ++i) {
3134 if (/^\d+$/.exec(slots[i])) {
3135 const index = parseInt(slots[i]);
3136 if (isValidColorIndex(index)) {
3137 event.push({ type: ColorRequestType.RESTORE, index });
3138 }
3139 }
3140 }
3141 if (event.length) {
3142 this._onColor.fire(event);
3143 }
3144 return true;
3145 }
3146
3147 /**
3148 * OSC 110 ST - restore default foreground color
3149 *
3150 * @vt: #Y OSC 110 "Restore default foreground color" "OSC 110 BEL" "Restore default foreground to themed color."
3151 */
3152 public restoreFgColor(data: string): boolean {
3153 this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.FOREGROUND }]);
3154 return true;
3155 }
3156
3157 /**
3158 * OSC 111 ST - restore default background color
3159 *
3160 * @vt: #Y OSC 111 "Restore default background color" "OSC 111 BEL" "Restore default background to themed color."
3161 */
3162 public restoreBgColor(data: string): boolean {
3163 this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.BACKGROUND }]);
3164 return true;
3165 }
3166
3167 /**
3168 * OSC 112 ST - restore default cursor color
3169 *
3170 * @vt: #Y OSC 112 "Restore default cursor color" "OSC 112 BEL" "Restore default cursor to themed color."
3171 */
3172 public restoreCursorColor(data: string): boolean {
3173 this._onColor.fire([{ type: ColorRequestType.RESTORE, index: SpecialColorIndex.CURSOR }]);
3174 return true;
3175 }
3176
3177 /**
3178 * ESC E
3179 * C1.NEL
3180 * DEC mnemonic: NEL (https://vt100.net/docs/vt510-rm/NEL)
3181 * Moves cursor to first position on next line.
3182 *
3183 * @vt: #Y C1 NEL "Next Line" "\x85" "Move the cursor to the beginning of the next row."
3184 * @vt: #Y ESC NEL "Next Line" "ESC E" "Move the cursor to the beginning of the next row."
3185 */
3186 public nextLine(): boolean {
3187 this._activeBuffer.x = 0;
3188 this.index();
3189 return true;
3190 }
3191
3192 /**
3193 * ESC =
3194 * DEC mnemonic: DECKPAM (https://vt100.net/docs/vt510-rm/DECKPAM.html)
3195 * Enables the numeric keypad to send application sequences to the host.
3196 */
3197 public keypadApplicationMode(): boolean {
3198 this._logService.debug('Serial port requested application keypad.');
3199 this._coreService.decPrivateModes.applicationKeypad = true;
3200 this._onRequestSyncScrollBar.fire();
3201 return true;
3202 }
3203
3204 /**
3205 * ESC >
3206 * DEC mnemonic: DECKPNM (https://vt100.net/docs/vt510-rm/DECKPNM.html)
3207 * Enables the keypad to send numeric characters to the host.
3208 */
3209 public keypadNumericMode(): boolean {
3210 this._logService.debug('Switching back to normal keypad.');
3211 this._coreService.decPrivateModes.applicationKeypad = false;
3212 this._onRequestSyncScrollBar.fire();
3213 return true;
3214 }
3215
3216 /**
3217 * ESC % @
3218 * ESC % G
3219 * Select default character set. UTF-8 is not supported (string are unicode anyways)
3220 * therefore ESC % G does the same.
3221 */
3222 public selectDefaultCharset(): boolean {
3223 this._charsetService.setgLevel(0);
3224 this._charsetService.setgCharset(0, DEFAULT_CHARSET); // US (default)
3225 return true;
3226 }
3227
3228 /**
3229 * ESC ( C
3230 * Designate G0 Character Set, VT100, ISO 2022.
3231 * ESC ) C
3232 * Designate G1 Character Set (ISO 2022, VT100).
3233 * ESC * C
3234 * Designate G2 Character Set (ISO 2022, VT220).
3235 * ESC + C
3236 * Designate G3 Character Set (ISO 2022, VT220).
3237 * ESC - C
3238 * Designate G1 Character Set (VT300).
3239 * ESC . C
3240 * Designate G2 Character Set (VT300).
3241 * ESC / C
3242 * Designate G3 Character Set (VT300). C = A -> ISO Latin-1 Supplemental. - Supported?
3243 */
3244 public selectCharset(collectAndFlag: string): boolean {
3245 if (collectAndFlag.length !== 2) {
3246 this.selectDefaultCharset();
3247 return true;
3248 }
3249 if (collectAndFlag[0] === '/') {
3250 return true; // TODO: Is this supported?
3251 }
3252 this._charsetService.setgCharset(GLEVEL[collectAndFlag[0]], CHARSETS[collectAndFlag[1]] || DEFAULT_CHARSET);
3253 return true;
3254 }
3255
3256 /**
3257 * ESC D
3258 * C1.IND
3259 * DEC mnemonic: IND (https://vt100.net/docs/vt510-rm/IND.html)
3260 * Moves the cursor down one line in the same column.
3261 *
3262 * @vt: #Y C1 IND "Index" "\x84" "Move the cursor one line down scrolling if needed."
3263 * @vt: #Y ESC IND "Index" "ESC D" "Move the cursor one line down scrolling if needed."
3264 */
3265 public index(): boolean {
3266 this._restrictCursor();
3267 this._activeBuffer.y++;
3268 if (this._activeBuffer.y === this._activeBuffer.scrollBottom + 1) {
3269 this._activeBuffer.y--;
3270 this._bufferService.scroll(this._eraseAttrData());
3271 } else if (this._activeBuffer.y >= this._bufferService.rows) {
3272 this._activeBuffer.y = this._bufferService.rows - 1;
3273 }
3274 this._restrictCursor();
3275 return true;
3276 }
3277
3278 /**
3279 * ESC H
3280 * C1.HTS
3281 * DEC mnemonic: HTS (https://vt100.net/docs/vt510-rm/HTS.html)
3282 * Sets a horizontal tab stop at the column position indicated by
3283 * the value of the active column when the terminal receives an HTS.
3284 *
3285 * @vt: #Y C1 HTS "Horizontal Tabulation Set" "\x88" "Places a tab stop at the current cursor position."
3286 * @vt: #Y ESC HTS "Horizontal Tabulation Set" "ESC H" "Places a tab stop at the current cursor position."
3287 */
3288 public tabSet(): boolean {
3289 this._activeBuffer.tabs[this._activeBuffer.x] = true;
3290 return true;
3291 }
3292
3293 /**
3294 * ESC M
3295 * C1.RI
3296 * DEC mnemonic: HTS
3297 * Moves the cursor up one line in the same column. If the cursor is at the top margin,
3298 * the page scrolls down.
3299 *
3300 * @vt: #Y ESC IR "Reverse Index" "ESC M" "Move the cursor one line up scrolling if needed."
3301 */
3302 public reverseIndex(): boolean {
3303 this._restrictCursor();
3304 if (this._activeBuffer.y === this._activeBuffer.scrollTop) {
3305 // possibly move the code below to term.reverseScroll();
3306 // test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
3307 // blankLine(true) is xterm/linux behavior
3308 const scrollRegionHeight = this._activeBuffer.scrollBottom - this._activeBuffer.scrollTop;
3309 this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase + this._activeBuffer.y, scrollRegionHeight, 1);
3310 this._activeBuffer.lines.set(this._activeBuffer.ybase + this._activeBuffer.y, this._activeBuffer.getBlankLine(this._eraseAttrData()));
3311 this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop, this._activeBuffer.scrollBottom);
3312 } else {
3313 this._activeBuffer.y--;
3314 this._restrictCursor(); // quickfix to not run out of bounds
3315 }
3316 return true;
3317 }
3318
3319 /**
3320 * ESC c
3321 * DEC mnemonic: RIS (https://vt100.net/docs/vt510-rm/RIS.html)
3322 * Reset to initial state.
3323 */
3324 public fullReset(): boolean {
3325 this._parser.reset();
3326 this._onRequestReset.fire();
3327 return true;
3328 }
3329
3330 public reset(): void {
3331 this._curAttrData = DEFAULT_ATTR_DATA.clone();
3332 this._eraseAttrDataInternal = DEFAULT_ATTR_DATA.clone();
3333 }
3334
3335 /**
3336 * back_color_erase feature for xterm.
3337 */
3338 private _eraseAttrData(): IAttributeData {
3339 this._eraseAttrDataInternal.bg &= ~(Attributes.CM_MASK | 0xFFFFFF);
3340 this._eraseAttrDataInternal.bg |= this._curAttrData.bg & ~0xFC000000;
3341 return this._eraseAttrDataInternal;
3342 }
3343
3344 /**
3345 * ESC n
3346 * ESC o
3347 * ESC |
3348 * ESC }
3349 * ESC ~
3350 * DEC mnemonic: LS (https://vt100.net/docs/vt510-rm/LS.html)
3351 * When you use a locking shift, the character set remains in GL or GR until
3352 * you use another locking shift. (partly supported)
3353 */
3354 public setgLevel(level: number): boolean {
3355 this._charsetService.setgLevel(level);
3356 return true;
3357 }
3358
3359 /**
3360 * ESC # 8
3361 * DEC mnemonic: DECALN (https://vt100.net/docs/vt510-rm/DECALN.html)
3362 * This control function fills the complete screen area with
3363 * a test pattern (E) used for adjusting screen alignment.
3364 *
3365 * @vt: #Y ESC DECALN "Screen Alignment Pattern" "ESC # 8" "Fill viewport with a test pattern (E)."
3366 */
3367 public screenAlignmentPattern(): boolean {
3368 // prepare cell data
3369 const cell = new CellData();
3370 cell.content = 1 << Content.WIDTH_SHIFT | 'E'.charCodeAt(0);
3371 cell.fg = this._curAttrData.fg;
3372 cell.bg = this._curAttrData.bg;
3373
3374
3375 this._setCursor(0, 0);
3376 for (let yOffset = 0; yOffset < this._bufferService.rows; ++yOffset) {
3377 const row = this._activeBuffer.ybase + this._activeBuffer.y + yOffset;
3378 const line = this._activeBuffer.lines.get(row);
3379 if (line) {
3380 line.fill(cell);
3381 line.isWrapped = false;
3382 }
3383 }
3384 this._dirtyRowTracker.markAllDirty();
3385 this._setCursor(0, 0);
3386 return true;
3387 }
3388
3389
3390 /**
3391 * DCS $ q Pt ST
3392 * DECRQSS (https://vt100.net/docs/vt510-rm/DECRQSS.html)
3393 * Request Status String (DECRQSS), VT420 and up.
3394 * Response: DECRPSS (https://vt100.net/docs/vt510-rm/DECRPSS.html)
3395 *
3396 * @vt: #P[Limited support, see below.] DCS DECRQSS "Request Selection or Setting" "DCS $ q Pt ST" "Request several terminal settings."
3397 * Response is in the form `ESC P 1 $ r Pt ST` for valid requests, where `Pt` contains the
3398 * corresponding CSI string, `ESC P 0 ST` for invalid requests.
3399 *
3400 * Supported requests and responses:
3401 *
3402 * | Type | Request | Response (`Pt`) |
3403 * | -------------------------------- | ----------------- | ----------------------------------------------------- |
3404 * | Graphic Rendition (SGR) | `DCS $ q m ST` | always reporting `0m` (currently broken) |
3405 * | Top and Bottom Margins (DECSTBM) | `DCS $ q r ST` | `Ps ; Ps r` |
3406 * | Cursor Style (DECSCUSR) | `DCS $ q SP q ST` | `Ps SP q` |
3407 * | Protection Attribute (DECSCA) | `DCS $ q " q ST` | `Ps " q` (DECSCA 2 is reported as Ps = 0) |
3408 * | Conformance Level (DECSCL) | `DCS $ q " p ST` | always reporting `61 ; 1 " p` (DECSCL is unsupported) |
3409 *
3410 *
3411 * TODO:
3412 * - fix SGR report
3413 * - either check which conformance is better suited or remove the report completely
3414 * --> we are currently a mixture of all up to VT400 but dont follow anyone strictly
3415 */
3416 public requestStatusString(data: string, params: IParams): boolean {
3417 const f = (s: string): boolean => {
3418 this._coreService.triggerDataEvent(`${C0.ESC}${s}${C0.ESC}\\`);
3419 return true;
3420 };
3421
3422 // access helpers
3423 const b = this._bufferService.buffer;
3424 const opts = this._optionsService.rawOptions;
3425 const STYLES: { [key: string]: number } = { 'block': 2, 'underline': 4, 'bar': 6 };
3426
3427 if (data === '"q') return f(`P1$r${this._curAttrData.isProtected() ? 1 : 0}"q`);
3428 if (data === '"p') return f(`P1$r61;1"p`);
3429 if (data === 'r') return f(`P1$r${b.scrollTop + 1};${b.scrollBottom + 1}r`);
3430 // FIXME: report real SGR settings instead of 0m
3431 if (data === 'm') return f(`P1$r0m`);
3432 if (data === ' q') return f(`P1$r${STYLES[opts.cursorStyle] - (opts.cursorBlink ? 1 : 0)} q`);
3433 return f(`P0$r`);
3434 }
3435
3436 public markRangeDirty(y1: number, y2: number): void {
3437 this._dirtyRowTracker.markRangeDirty(y1, y2);
3438 }
3439 }
3440
3441 export interface IDirtyRowTracker {
3442 readonly start: number;
3443 readonly end: number;
3444
3445 clearRange(): void;
3446 markDirty(y: number): void;
3447 markRangeDirty(y1: number, y2: number): void;
3448 markAllDirty(): void;
3449 }
3450
3451 class DirtyRowTracker implements IDirtyRowTracker {
3452 public start!: number;
3453 public end!: number;
3454
3455 constructor(
3456 @IBufferService private readonly _bufferService: IBufferService
3457 ) {
3458 this.clearRange();
3459 }
3460
3461 public clearRange(): void {
3462 this.start = this._bufferService.buffer.y;
3463 this.end = this._bufferService.buffer.y;
3464 }
3465
3466 public markDirty(y: number): void {
3467 if (y < this.start) {
3468 this.start = y;
3469 } else if (y > this.end) {
3470 this.end = y;
3471 }
3472 }
3473
3474 public markRangeDirty(y1: number, y2: number): void {
3475 if (y1 > y2) {
3476 $temp = y1;
3477 y1 = y2;
3478 y2 = $temp;
3479 }
3480 if (y1 < this.start) {
3481 this.start = y1;
3482 }
3483 if (y2 > this.end) {
3484 this.end = y2;
3485 }
3486 }
3487
3488 public markAllDirty(): void {
3489 this.markRangeDirty(0, this._bufferService.rows - 1);
3490 }
3491 }
3492
3493 export function isValidColorIndex(value: number): value is ColorIndex {
3494 return 0 <= value && value < 256;
3495 }