@wendongfly/zihi 1.0.0

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