@xterm/xterm 5.4.0-beta.1

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