@theia/monaco 1.34.1 → 1.34.3

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 (170) hide show
  1. package/LICENSE +641 -641
  2. package/README.md +100 -100
  3. package/data/monaco-nls.json +1379 -1379
  4. package/data/monaco-themes/vscode/dark_plus.json +201 -201
  5. package/data/monaco-themes/vscode/dark_theia.json +5 -5
  6. package/data/monaco-themes/vscode/dark_vs.json +392 -392
  7. package/data/monaco-themes/vscode/hc_black.json +457 -457
  8. package/data/monaco-themes/vscode/hc_light.json +590 -590
  9. package/data/monaco-themes/vscode/hc_theia.json +5 -5
  10. package/data/monaco-themes/vscode/hc_theia_light.json +5 -5
  11. package/data/monaco-themes/vscode/light_plus.json +202 -202
  12. package/data/monaco-themes/vscode/light_theia.json +10 -10
  13. package/data/monaco-themes/vscode/light_vs.json +421 -421
  14. package/lib/browser/index.d.ts +1 -1
  15. package/lib/browser/index.js +28 -28
  16. package/lib/browser/markdown-renderer/monaco-markdown-renderer.d.ts +24 -24
  17. package/lib/browser/markdown-renderer/monaco-markdown-renderer.js +137 -137
  18. package/lib/browser/monaco-bulk-edit-service.d.ts +14 -14
  19. package/lib/browser/monaco-bulk-edit-service.js +66 -66
  20. package/lib/browser/monaco-color-registry.d.ts +16 -16
  21. package/lib/browser/monaco-color-registry.js +82 -82
  22. package/lib/browser/monaco-command-registry.d.ts +19 -19
  23. package/lib/browser/monaco-command-registry.js +82 -82
  24. package/lib/browser/monaco-command-service.d.ts +26 -26
  25. package/lib/browser/monaco-command-service.js +92 -92
  26. package/lib/browser/monaco-command.d.ts +94 -94
  27. package/lib/browser/monaco-command.js +306 -306
  28. package/lib/browser/monaco-context-key-service.d.ts +22 -22
  29. package/lib/browser/monaco-context-key-service.js +147 -147
  30. package/lib/browser/monaco-context-menu.d.ts +16 -16
  31. package/lib/browser/monaco-context-menu.js +102 -102
  32. package/lib/browser/monaco-diagnostic-collection.d.ts +28 -28
  33. package/lib/browser/monaco-diagnostic-collection.js +86 -86
  34. package/lib/browser/monaco-diff-editor.d.ts +29 -29
  35. package/lib/browser/monaco-diff-editor.js +74 -74
  36. package/lib/browser/monaco-diff-navigator-factory.d.ts +7 -7
  37. package/lib/browser/monaco-diff-navigator-factory.js +66 -66
  38. package/lib/browser/monaco-editor-model.d.ts +156 -156
  39. package/lib/browser/monaco-editor-model.js +555 -555
  40. package/lib/browser/monaco-editor-provider.d.ts +89 -89
  41. package/lib/browser/monaco-editor-provider.js +440 -440
  42. package/lib/browser/monaco-editor-service.d.ts +27 -27
  43. package/lib/browser/monaco-editor-service.js +151 -151
  44. package/lib/browser/monaco-editor-zone-widget.d.ts +43 -43
  45. package/lib/browser/monaco-editor-zone-widget.js +194 -194
  46. package/lib/browser/monaco-editor.d.ts +151 -151
  47. package/lib/browser/monaco-editor.js +497 -497
  48. package/lib/browser/monaco-formatting-conflicts.d.ts +13 -13
  49. package/lib/browser/monaco-formatting-conflicts.js +110 -110
  50. package/lib/browser/monaco-frontend-application-contribution.d.ts +26 -26
  51. package/lib/browser/monaco-frontend-application-contribution.js +201 -201
  52. package/lib/browser/monaco-frontend-module.d.ts +7 -7
  53. package/lib/browser/monaco-frontend-module.js +266 -266
  54. package/lib/browser/monaco-gotoline-quick-access.d.ts +11 -11
  55. package/lib/browser/monaco-gotoline-quick-access.js +64 -64
  56. package/lib/browser/monaco-gotosymbol-quick-access.d.ts +16 -16
  57. package/lib/browser/monaco-gotosymbol-quick-access.js +70 -70
  58. package/lib/browser/monaco-indexed-db.d.ts +28 -28
  59. package/lib/browser/monaco-indexed-db.js +131 -131
  60. package/lib/browser/monaco-keybinding-contexts.d.ts +15 -15
  61. package/lib/browser/monaco-keybinding-contexts.js +50 -50
  62. package/lib/browser/monaco-keybinding.d.ts +16 -16
  63. package/lib/browser/monaco-keybinding.js +134 -134
  64. package/lib/browser/monaco-keycode-map.d.ts +2 -2
  65. package/lib/browser/monaco-keycode-map.js +163 -163
  66. package/lib/browser/monaco-languages.d.ts +27 -27
  67. package/lib/browser/monaco-languages.js +136 -136
  68. package/lib/browser/monaco-menu.d.ts +20 -20
  69. package/lib/browser/monaco-menu.js +145 -145
  70. package/lib/browser/monaco-mime-service.d.ts +10 -10
  71. package/lib/browser/monaco-mime-service.js +78 -78
  72. package/lib/browser/monaco-outline-contribution.d.ts +78 -78
  73. package/lib/browser/monaco-outline-contribution.js +384 -384
  74. package/lib/browser/monaco-outline-decorator.d.ts +12 -12
  75. package/lib/browser/monaco-outline-decorator.js +67 -67
  76. package/lib/browser/monaco-quick-access-registry.d.ts +11 -11
  77. package/lib/browser/monaco-quick-access-registry.js +99 -99
  78. package/lib/browser/monaco-quick-input-service.d.ts +99 -99
  79. package/lib/browser/monaco-quick-input-service.js +555 -555
  80. package/lib/browser/monaco-resolved-keybinding.d.ts +23 -23
  81. package/lib/browser/monaco-resolved-keybinding.js +131 -131
  82. package/lib/browser/monaco-snippet-suggest-provider.d.ts +64 -64
  83. package/lib/browser/monaco-snippet-suggest-provider.js +269 -269
  84. package/lib/browser/monaco-status-bar-contribution.d.ts +17 -17
  85. package/lib/browser/monaco-status-bar-contribution.js +120 -120
  86. package/lib/browser/monaco-text-model-service.d.ts +51 -51
  87. package/lib/browser/monaco-text-model-service.js +184 -184
  88. package/lib/browser/monaco-theming-service.d.ts +67 -67
  89. package/lib/browser/monaco-theming-service.js +171 -171
  90. package/lib/browser/monaco-to-protocol-converter.d.ts +26 -26
  91. package/lib/browser/monaco-to-protocol-converter.js +61 -61
  92. package/lib/browser/monaco-workspace.d.ts +83 -83
  93. package/lib/browser/monaco-workspace.js +369 -369
  94. package/lib/browser/protocol-to-monaco-converter.d.ts +31 -31
  95. package/lib/browser/protocol-to-monaco-converter.js +133 -133
  96. package/lib/browser/textmate/index.d.ts +4 -4
  97. package/lib/browser/textmate/index.js +31 -31
  98. package/lib/browser/textmate/monaco-textmate-frontend-bindings.d.ts +12 -12
  99. package/lib/browser/textmate/monaco-textmate-frontend-bindings.js +94 -94
  100. package/lib/browser/textmate/monaco-textmate-service.d.ts +30 -30
  101. package/lib/browser/textmate/monaco-textmate-service.js +185 -185
  102. package/lib/browser/textmate/monaco-theme-registry.d.ts +27 -27
  103. package/lib/browser/textmate/monaco-theme-registry.js +171 -171
  104. package/lib/browser/textmate/monaco-theme-types.d.ts +20 -20
  105. package/lib/browser/textmate/monaco-theme-types.js +21 -21
  106. package/lib/browser/textmate/textmate-contribution.d.ts +9 -9
  107. package/lib/browser/textmate/textmate-contribution.js +27 -27
  108. package/lib/browser/textmate/textmate-registry.d.ts +31 -31
  109. package/lib/browser/textmate/textmate-registry.js +109 -109
  110. package/lib/browser/textmate/textmate-snippet-completion-provider.d.ts +26 -26
  111. package/lib/browser/textmate/textmate-snippet-completion-provider.js +53 -53
  112. package/lib/browser/textmate/textmate-tokenizer.d.ts +22 -22
  113. package/lib/browser/textmate/textmate-tokenizer.js +65 -65
  114. package/lib/browser/workspace-symbol-command.d.ts +55 -55
  115. package/lib/browser/workspace-symbol-command.js +215 -215
  116. package/lib/package.spec.js +25 -25
  117. package/package.json +8 -8
  118. package/src/browser/index.ts +17 -17
  119. package/src/browser/markdown-renderer/monaco-markdown-renderer.ts +117 -117
  120. package/src/browser/monaco-bulk-edit-service.ts +64 -64
  121. package/src/browser/monaco-color-registry.ts +73 -73
  122. package/src/browser/monaco-command-registry.ts +82 -82
  123. package/src/browser/monaco-command-service.ts +99 -99
  124. package/src/browser/monaco-command.ts +311 -311
  125. package/src/browser/monaco-context-key-service.ts +143 -143
  126. package/src/browser/monaco-context-menu.ts +90 -90
  127. package/src/browser/monaco-diagnostic-collection.ts +101 -101
  128. package/src/browser/monaco-diff-editor.ts +101 -101
  129. package/src/browser/monaco-diff-navigator-factory.ts +61 -61
  130. package/src/browser/monaco-editor-model.ts +681 -681
  131. package/src/browser/monaco-editor-provider.ts +452 -452
  132. package/src/browser/monaco-editor-service.ts +144 -144
  133. package/src/browser/monaco-editor-zone-widget.ts +250 -250
  134. package/src/browser/monaco-editor.ts +644 -644
  135. package/src/browser/monaco-formatting-conflicts.ts +115 -115
  136. package/src/browser/monaco-frontend-application-contribution.ts +188 -188
  137. package/src/browser/monaco-frontend-module.ts +314 -314
  138. package/src/browser/monaco-gotoline-quick-access.ts +47 -47
  139. package/src/browser/monaco-gotosymbol-quick-access.ts +53 -53
  140. package/src/browser/monaco-indexed-db.ts +130 -130
  141. package/src/browser/monaco-keybinding-contexts.ts +43 -43
  142. package/src/browser/monaco-keybinding.ts +111 -111
  143. package/src/browser/monaco-keycode-map.ts +171 -171
  144. package/src/browser/monaco-languages.ts +129 -129
  145. package/src/browser/monaco-menu.ts +142 -142
  146. package/src/browser/monaco-mime-service.ts +71 -71
  147. package/src/browser/monaco-outline-contribution.ts +404 -404
  148. package/src/browser/monaco-outline-decorator.ts +66 -66
  149. package/src/browser/monaco-quick-access-registry.ts +112 -112
  150. package/src/browser/monaco-quick-input-service.ts +651 -651
  151. package/src/browser/monaco-resolved-keybinding.ts +162 -162
  152. package/src/browser/monaco-snippet-suggest-provider.ts +300 -300
  153. package/src/browser/monaco-status-bar-contribution.ts +109 -109
  154. package/src/browser/monaco-text-model-service.ts +194 -194
  155. package/src/browser/monaco-theming-service.ts +204 -204
  156. package/src/browser/monaco-to-protocol-converter.ts +71 -71
  157. package/src/browser/monaco-workspace.ts +393 -393
  158. package/src/browser/protocol-to-monaco-converter.ts +158 -158
  159. package/src/browser/style/index.css +267 -267
  160. package/src/browser/textmate/index.ts +20 -20
  161. package/src/browser/textmate/monaco-textmate-frontend-bindings.ts +94 -94
  162. package/src/browser/textmate/monaco-textmate-service.ts +187 -187
  163. package/src/browser/textmate/monaco-theme-registry.ts +176 -176
  164. package/src/browser/textmate/monaco-theme-types.ts +37 -37
  165. package/src/browser/textmate/textmate-contribution.ts +29 -29
  166. package/src/browser/textmate/textmate-registry.ts +129 -129
  167. package/src/browser/textmate/textmate-snippet-completion-provider.ts +73 -73
  168. package/src/browser/textmate/textmate-tokenizer.ts +84 -84
  169. package/src/browser/workspace-symbol-command.ts +196 -196
  170. package/src/package.spec.ts +28 -28
@@ -1,681 +1,681 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2017 TypeFox and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
-
17
- import { Position, Range, TextDocumentSaveReason, TextDocumentContentChangeEvent } from '@theia/core/shared/vscode-languageserver-protocol';
18
- import { TextEditorDocument, EncodingMode, FindMatchesOptions, FindMatch, EditorPreferences } from '@theia/editor/lib/browser';
19
- import { DisposableCollection, Disposable } from '@theia/core/lib/common/disposable';
20
- import { Emitter, Event } from '@theia/core/lib/common/event';
21
- import { CancellationTokenSource, CancellationToken } from '@theia/core/lib/common/cancellation';
22
- import { Resource, ResourceError, ResourceVersion, UNTITLED_SCHEME } from '@theia/core/lib/common/resource';
23
- import { Saveable, SaveOptions } from '@theia/core/lib/browser/saveable';
24
- import { MonacoToProtocolConverter } from './monaco-to-protocol-converter';
25
- import { ProtocolToMonacoConverter } from './protocol-to-monaco-converter';
26
- import { ILogger, Loggable, Log } from '@theia/core/lib/common/logger';
27
- import { IIdentifiedSingleEditOperation, ITextBufferFactory, ITextModel, ITextSnapshot } from '@theia/monaco-editor-core/esm/vs/editor/common/model';
28
- import { IResolvedTextEditorModel } from '@theia/monaco-editor-core/esm/vs/editor/common/services/resolverService';
29
- import * as monaco from '@theia/monaco-editor-core';
30
- import { StandaloneServices } from '@theia/monaco-editor-core/esm/vs/editor/standalone/browser/standaloneServices';
31
- import { ILanguageService } from '@theia/monaco-editor-core/esm/vs/editor/common/languages/language';
32
- import { IModelService } from '@theia/monaco-editor-core/esm/vs/editor/common/services/model';
33
- import { createTextBufferFactoryFromStream } from '@theia/monaco-editor-core/esm/vs/editor/common/model/textModel';
34
- import { editorGeneratedPreferenceProperties } from '@theia/editor/lib/browser/editor-generated-preference-schema';
35
-
36
- export {
37
- TextDocumentSaveReason
38
- };
39
-
40
- export interface WillSaveMonacoModelEvent {
41
- readonly model: MonacoEditorModel;
42
- readonly reason: TextDocumentSaveReason;
43
- readonly options?: SaveOptions;
44
- waitUntil(thenable: Thenable<IIdentifiedSingleEditOperation[]>): void;
45
- }
46
-
47
- export interface MonacoModelContentChangedEvent {
48
- readonly model: MonacoEditorModel;
49
- readonly contentChanges: TextDocumentContentChangeEvent[];
50
- }
51
-
52
- export class MonacoEditorModel implements IResolvedTextEditorModel, TextEditorDocument {
53
-
54
- autoSave: EditorPreferences['files.autoSave'] = 'afterDelay';
55
- autoSaveDelay = 500;
56
- suppressOpenEditorWhenDirty = false;
57
- lineNumbersMinChars = 3;
58
-
59
- /* @deprecated there is no general save timeout, each participant should introduce a sensible timeout */
60
- readonly onWillSaveLoopTimeOut = 1500;
61
- protected bufferSavedVersionId: number;
62
-
63
- protected model: ITextModel;
64
- protected readonly resolveModel: Promise<void>;
65
-
66
- protected readonly toDispose = new DisposableCollection();
67
- protected readonly toDisposeOnAutoSave = new DisposableCollection();
68
-
69
- protected readonly onDidChangeContentEmitter = new Emitter<MonacoModelContentChangedEvent>();
70
- readonly onDidChangeContent = this.onDidChangeContentEmitter.event;
71
-
72
- protected readonly onDidSaveModelEmitter = new Emitter<ITextModel>();
73
- readonly onDidSaveModel = this.onDidSaveModelEmitter.event;
74
-
75
- protected readonly onWillSaveModelEmitter = new Emitter<WillSaveMonacoModelEvent>();
76
- readonly onWillSaveModel = this.onWillSaveModelEmitter.event;
77
-
78
- protected readonly onDidChangeValidEmitter = new Emitter<void>();
79
- readonly onDidChangeValid = this.onDidChangeValidEmitter.event;
80
-
81
- protected readonly onDidChangeEncodingEmitter = new Emitter<string>();
82
- readonly onDidChangeEncoding = this.onDidChangeEncodingEmitter.event;
83
-
84
- private preferredEncoding: string | undefined;
85
- private contentEncoding: string | undefined;
86
-
87
- protected resourceVersion: ResourceVersion | undefined;
88
-
89
- constructor(
90
- protected readonly resource: Resource,
91
- protected readonly m2p: MonacoToProtocolConverter,
92
- protected readonly p2m: ProtocolToMonacoConverter,
93
- protected readonly logger?: ILogger,
94
- protected readonly editorPreferences?: EditorPreferences
95
- ) {
96
- this.toDispose.push(resource);
97
- this.toDispose.push(this.toDisposeOnAutoSave);
98
- this.toDispose.push(this.onDidChangeContentEmitter);
99
- this.toDispose.push(this.onDidSaveModelEmitter);
100
- this.toDispose.push(this.onWillSaveModelEmitter);
101
- this.toDispose.push(this.onDirtyChangedEmitter);
102
- this.toDispose.push(this.onDidChangeValidEmitter);
103
- this.toDispose.push(Disposable.create(() => this.cancelSave()));
104
- this.toDispose.push(Disposable.create(() => this.cancelSync()));
105
- this.resolveModel = this.readContents().then(
106
- content => this.initialize(content || '')
107
- );
108
- }
109
-
110
- dispose(): void {
111
- this.toDispose.dispose();
112
- }
113
-
114
- isDisposed(): boolean {
115
- return this.toDispose.disposed;
116
- }
117
-
118
- resolve(): Promise<void> {
119
- return this.resolveModel;
120
- }
121
-
122
- isResolved(): boolean {
123
- return Boolean(this.model);
124
- }
125
-
126
- setEncoding(encoding: string, mode: EncodingMode): Promise<void> {
127
- if (mode === EncodingMode.Decode && this.dirty) {
128
- return Promise.resolve();
129
- }
130
- if (!this.setPreferredEncoding(encoding)) {
131
- return Promise.resolve();
132
- }
133
- if (mode === EncodingMode.Decode) {
134
- return this.sync();
135
- }
136
- return this.scheduleSave(TextDocumentSaveReason.Manual, this.cancelSave(), true);
137
- }
138
-
139
- getEncoding(): string | undefined {
140
- return this.preferredEncoding || this.contentEncoding;
141
- }
142
-
143
- protected setPreferredEncoding(encoding: string): boolean {
144
- if (encoding === this.preferredEncoding || (!this.preferredEncoding && encoding === this.contentEncoding)) {
145
- return false;
146
- }
147
- this.preferredEncoding = encoding;
148
- this.onDidChangeEncodingEmitter.fire(encoding);
149
- return true;
150
- }
151
-
152
- protected updateContentEncoding(): void {
153
- const contentEncoding = this.resource.encoding;
154
- if (!contentEncoding || this.contentEncoding === contentEncoding) {
155
- return;
156
- }
157
- this.contentEncoding = contentEncoding;
158
- if (!this.preferredEncoding) {
159
- this.onDidChangeEncodingEmitter.fire(contentEncoding);
160
- }
161
- }
162
-
163
- /**
164
- * #### Important
165
- * Only this method can create an instance of `monaco.editor.IModel`,
166
- * there should not be other calls to `monaco.editor.createModel`.
167
- */
168
- protected initialize(value: string | ITextBufferFactory): void {
169
- if (!this.toDispose.disposed) {
170
- const uri = monaco.Uri.parse(this.resource.uri.toString());
171
- let firstLine;
172
- if (typeof value === 'string') {
173
- firstLine = value;
174
- const firstLF = value.indexOf('\n');
175
- if (firstLF !== -1) {
176
- firstLine = value.substring(0, firstLF);
177
- }
178
- } else {
179
- firstLine = value.getFirstLineText(1000);
180
- }
181
- const languageSelection = StandaloneServices.get(ILanguageService).createByFilepathOrFirstLine(uri, firstLine);
182
- this.model = StandaloneServices.get(IModelService).createModel(value, languageSelection, uri);
183
- this.resourceVersion = this.resource.version;
184
- this.setDirty(this._dirty || (this.resource.uri.scheme === UNTITLED_SCHEME && this.model.getValueLength() > 0));
185
- this.updateSavedVersionId();
186
- this.toDispose.push(this.model);
187
- this.toDispose.push(this.model.onDidChangeContent(event => this.fireDidChangeContent(event)));
188
- if (this.resource.onDidChangeContents) {
189
- this.toDispose.push(this.resource.onDidChangeContents(() => this.sync()));
190
- }
191
- }
192
- }
193
-
194
- /**
195
- * Use `valid` to access it.
196
- * Use `setValid` to mutate it.
197
- */
198
- protected _valid = false;
199
- /**
200
- * Whether it is possible to load content from the underlying resource.
201
- */
202
- get valid(): boolean {
203
- return this._valid;
204
- }
205
- protected setValid(valid: boolean): void {
206
- if (valid === this._valid) {
207
- return;
208
- }
209
- this._valid = valid;
210
- this.onDidChangeValidEmitter.fire(undefined);
211
- }
212
-
213
- protected _dirty = false;
214
- get dirty(): boolean {
215
- return this._dirty;
216
- }
217
- protected setDirty(dirty: boolean): void {
218
- if (dirty === this._dirty) {
219
- return;
220
- }
221
- this._dirty = dirty;
222
- if (dirty === false) {
223
- this.updateSavedVersionId();
224
- }
225
- this.onDirtyChangedEmitter.fire(undefined);
226
- }
227
-
228
- private updateSavedVersionId(): void {
229
- this.bufferSavedVersionId = this.model.getAlternativeVersionId();
230
- }
231
-
232
- protected readonly onDirtyChangedEmitter = new Emitter<void>();
233
- get onDirtyChanged(): Event<void> {
234
- return this.onDirtyChangedEmitter.event;
235
- }
236
-
237
- get uri(): string {
238
- return this.resource.uri.toString();
239
- }
240
-
241
- protected _languageId: string | undefined;
242
- get languageId(): string {
243
- return this._languageId !== undefined ? this._languageId : this.model.getLanguageId();
244
- }
245
-
246
- getLanguageId(): string | undefined {
247
- return this.languageId;
248
- }
249
-
250
- /**
251
- * It's a hack to dispatch close notification with an old language id; don't use it.
252
- */
253
- setLanguageId(languageId: string | undefined): void {
254
- this._languageId = languageId;
255
- }
256
-
257
- get version(): number {
258
- return this.model.getVersionId();
259
- }
260
-
261
- /**
262
- * Return selected text by Range or all text by default
263
- */
264
- getText(range?: Range): string {
265
- if (!range) {
266
- return this.model.getValue();
267
- } else {
268
- return this.model.getValueInRange(this.p2m.asRange(range));
269
- }
270
- }
271
-
272
- positionAt(offset: number): Position {
273
- const { lineNumber, column } = this.model.getPositionAt(offset);
274
- return this.m2p.asPosition(lineNumber, column);
275
- }
276
-
277
- offsetAt(position: Position): number {
278
- return this.model.getOffsetAt(this.p2m.asPosition(position));
279
- }
280
-
281
- get lineCount(): number {
282
- return this.model.getLineCount();
283
- }
284
-
285
- /**
286
- * Retrieves a line in a text document expressed as a one-based position.
287
- */
288
- getLineContent(lineNumber: number): string {
289
- return this.model.getLineContent(lineNumber);
290
- }
291
-
292
- getLineMaxColumn(lineNumber: number): number {
293
- return this.model.getLineMaxColumn(lineNumber);
294
- }
295
-
296
- toValidPosition(position: Position): Position {
297
- const { lineNumber, column } = this.model.validatePosition(this.p2m.asPosition(position));
298
- return this.m2p.asPosition(lineNumber, column);
299
- }
300
-
301
- toValidRange(range: Range): Range {
302
- return this.m2p.asRange(this.model.validateRange(this.p2m.asRange(range)));
303
- }
304
-
305
- get readOnly(): boolean {
306
- return this.resource.saveContents === undefined;
307
- }
308
-
309
- isReadonly(): boolean {
310
- return this.readOnly;
311
- }
312
-
313
- get onDispose(): monaco.IEvent<void> {
314
- return this.toDispose.onDispose;
315
- }
316
-
317
- get onWillDispose(): Event<void> {
318
- return this.toDispose.onDispose;
319
- }
320
-
321
- // We have a TypeScript problem here. There is a const enum `DefaultEndOfLine` used for ITextModel and a non-const redeclaration of that enum in the public API in
322
- // Monaco.editor. The values will be the same, but TS won't accept that the two enums are equivalent, so it says these types are irreconcilable.
323
- get textEditorModel(): monaco.editor.ITextModel & ITextModel {
324
- // @ts-expect-error ts(2322)
325
- return this.model;
326
- }
327
-
328
- /**
329
- * Find all matches in an editor for the given options.
330
- * @param options the options for finding matches.
331
- *
332
- * @returns the list of matches.
333
- */
334
- findMatches(options: FindMatchesOptions): FindMatch[] {
335
- const wordSeparators = this.editorPreferences?.['editor.wordSeparators'] ?? editorGeneratedPreferenceProperties['editor.wordSeparators'].default as string;
336
- const results: monaco.editor.FindMatch[] = this.model.findMatches(
337
- options.searchString,
338
- false,
339
- options.isRegex,
340
- options.matchCase,
341
- // eslint-disable-next-line no-null/no-null
342
- options.matchWholeWord ? wordSeparators : null,
343
- true,
344
- options.limitResultCount
345
- );
346
- const extractedMatches: FindMatch[] = [];
347
- results.forEach(r => {
348
- if (r.matches) {
349
- extractedMatches.push({
350
- matches: r.matches,
351
- range: Range.create(r.range.startLineNumber, r.range.startColumn, r.range.endLineNumber, r.range.endColumn)
352
- });
353
- }
354
- });
355
- return extractedMatches;
356
- }
357
-
358
- async load(): Promise<MonacoEditorModel> {
359
- await this.resolveModel;
360
- return this;
361
- }
362
-
363
- save(options?: SaveOptions): Promise<void> {
364
- return this.scheduleSave(TextDocumentSaveReason.Manual, undefined, undefined, options);
365
- }
366
-
367
- protected pendingOperation = Promise.resolve();
368
- protected async run(operation: () => Promise<void>): Promise<void> {
369
- if (this.toDispose.disposed) {
370
- return;
371
- }
372
- return this.pendingOperation = this.pendingOperation.then(async () => {
373
- try {
374
- await operation();
375
- } catch (e) {
376
- console.error(e);
377
- }
378
- });
379
- }
380
-
381
- protected syncCancellationTokenSource = new CancellationTokenSource();
382
- protected cancelSync(): CancellationToken {
383
- this.trace(log => log('MonacoEditorModel.cancelSync'));
384
- this.syncCancellationTokenSource.cancel();
385
- this.syncCancellationTokenSource = new CancellationTokenSource();
386
- return this.syncCancellationTokenSource.token;
387
- }
388
-
389
- async sync(): Promise<void> {
390
- const token = this.cancelSync();
391
- return this.run(() => this.doSync(token));
392
- }
393
- protected async doSync(token: CancellationToken): Promise<void> {
394
- this.trace(log => log('MonacoEditorModel.doSync - enter'));
395
- if (token.isCancellationRequested) {
396
- this.trace(log => log('MonacoEditorModel.doSync - exit - cancelled'));
397
- return;
398
- }
399
-
400
- const value = await this.readContents();
401
- if (value === undefined) {
402
- this.trace(log => log('MonacoEditorModel.doSync - exit - resource not found'));
403
- return;
404
- }
405
- if (token.isCancellationRequested) {
406
- this.trace(log => log('MonacoEditorModel.doSync - exit - cancelled while looking for a resource'));
407
- return;
408
- }
409
- if (this._dirty) {
410
- this.trace(log => log('MonacoEditorModel.doSync - exit - pending dirty changes'));
411
- return;
412
- }
413
-
414
- this.resourceVersion = this.resource.version;
415
- this.updateModel(() => StandaloneServices.get(IModelService).updateModel(this.model, value), {
416
- ignoreDirty: true,
417
- ignoreContentChanges: true
418
- });
419
- this.trace(log => log('MonacoEditorModel.doSync - exit'));
420
- }
421
- protected async readContents(): Promise<string | ITextBufferFactory | undefined> {
422
- try {
423
- const options = { encoding: this.getEncoding() };
424
- const content = await (this.resource.readStream ? this.resource.readStream(options) : this.resource.readContents(options));
425
- let value;
426
- if (typeof content === 'string') {
427
- value = content;
428
- } else {
429
- value = createTextBufferFactoryFromStream(content);
430
- }
431
- this.updateContentEncoding();
432
- this.setValid(true);
433
- return value;
434
- } catch (e) {
435
- this.setValid(false);
436
- if (ResourceError.NotFound.is(e)) {
437
- return undefined;
438
- }
439
- throw e;
440
- }
441
- }
442
-
443
- protected ignoreDirtyEdits = false;
444
- protected markAsDirty(): void {
445
- this.trace(log => log('MonacoEditorModel.markAsDirty - enter'));
446
- if (this.ignoreDirtyEdits) {
447
- this.trace(log => log('MonacoEditorModel.markAsDirty - exit - ignoring dirty changes enabled'));
448
- return;
449
- }
450
- this.cancelSync();
451
- this.setDirty(true);
452
- this.doAutoSave();
453
- this.trace(log => log('MonacoEditorModel.markAsDirty - exit'));
454
- }
455
-
456
- protected doAutoSave(): void {
457
- if (this.autoSave !== 'off' && this.resource.uri.scheme !== UNTITLED_SCHEME) {
458
- const token = this.cancelSave();
459
- this.toDisposeOnAutoSave.dispose();
460
- const handle = window.setTimeout(() => {
461
- this.scheduleSave(TextDocumentSaveReason.AfterDelay, token);
462
- }, this.autoSaveDelay);
463
- this.toDisposeOnAutoSave.push(Disposable.create(() =>
464
- window.clearTimeout(handle))
465
- );
466
- }
467
- }
468
-
469
- protected saveCancellationTokenSource = new CancellationTokenSource();
470
- protected cancelSave(): CancellationToken {
471
- this.trace(log => log('MonacoEditorModel.cancelSave'));
472
- this.saveCancellationTokenSource.cancel();
473
- this.saveCancellationTokenSource = new CancellationTokenSource();
474
- return this.saveCancellationTokenSource.token;
475
- }
476
-
477
- protected scheduleSave(reason: TextDocumentSaveReason, token: CancellationToken = this.cancelSave(), overwriteEncoding?: boolean, options?: SaveOptions): Promise<void> {
478
- return this.run(() => this.doSave(reason, token, overwriteEncoding, options));
479
- }
480
-
481
- protected ignoreContentChanges = false;
482
- protected readonly contentChanges: TextDocumentContentChangeEvent[] = [];
483
- protected pushContentChanges(contentChanges: TextDocumentContentChangeEvent[]): void {
484
- if (!this.ignoreContentChanges) {
485
- this.contentChanges.push(...contentChanges);
486
- }
487
- }
488
-
489
- protected fireDidChangeContent(event: monaco.editor.IModelContentChangedEvent): void {
490
- this.trace(log => log(`MonacoEditorModel.fireDidChangeContent - enter - ${JSON.stringify(event, undefined, 2)}`));
491
- if (this.model.getAlternativeVersionId() === this.bufferSavedVersionId) {
492
- this.setDirty(false);
493
- } else {
494
- this.markAsDirty();
495
- }
496
-
497
- const changeContentEvent = this.asContentChangedEvent(event);
498
- this.onDidChangeContentEmitter.fire(changeContentEvent);
499
- this.pushContentChanges(changeContentEvent.contentChanges);
500
- this.trace(log => log('MonacoEditorModel.fireDidChangeContent - exit'));
501
- }
502
- protected asContentChangedEvent(event: monaco.editor.IModelContentChangedEvent): MonacoModelContentChangedEvent {
503
- const contentChanges = event.changes.map(change => this.asTextDocumentContentChangeEvent(change));
504
- return { model: this, contentChanges };
505
- }
506
- protected asTextDocumentContentChangeEvent(change: monaco.editor.IModelContentChange): TextDocumentContentChangeEvent {
507
- const range = this.m2p.asRange(change.range);
508
- const rangeLength = change.rangeLength;
509
- const text = change.text;
510
- return { range, rangeLength, text };
511
- }
512
-
513
- protected applyEdits(
514
- operations: monaco.editor.IIdentifiedSingleEditOperation[],
515
- options?: Partial<MonacoEditorModel.ApplyEditsOptions>
516
- ): void {
517
- return this.updateModel(() => this.model.applyEdits(operations), options);
518
- }
519
-
520
- protected updateModel<T>(doUpdate: () => T, options?: Partial<MonacoEditorModel.ApplyEditsOptions>): T {
521
- const resolvedOptions: MonacoEditorModel.ApplyEditsOptions = {
522
- ignoreDirty: false,
523
- ignoreContentChanges: false,
524
- ...options
525
- };
526
- const { ignoreDirtyEdits, ignoreContentChanges } = this;
527
- this.ignoreDirtyEdits = resolvedOptions.ignoreDirty;
528
- this.ignoreContentChanges = resolvedOptions.ignoreContentChanges;
529
- try {
530
- return doUpdate();
531
- } finally {
532
- this.ignoreDirtyEdits = ignoreDirtyEdits;
533
- this.ignoreContentChanges = ignoreContentChanges;
534
- }
535
- }
536
-
537
- protected async doSave(reason: TextDocumentSaveReason, token: CancellationToken, overwriteEncoding?: boolean, options?: SaveOptions): Promise<void> {
538
- if (token.isCancellationRequested || !this.resource.saveContents) {
539
- return;
540
- }
541
-
542
- await this.fireWillSaveModel(reason, token, options);
543
- if (token.isCancellationRequested) {
544
- return;
545
- }
546
-
547
- const changes = [...this.contentChanges];
548
- if (changes.length === 0 && !overwriteEncoding && reason !== TextDocumentSaveReason.Manual) {
549
- return;
550
- }
551
-
552
- const contentLength = this.model.getValueLength();
553
- const content = this.model.createSnapshot() || this.model.getValue();
554
- try {
555
- const encoding = this.getEncoding();
556
- const version = this.resourceVersion;
557
- await Resource.save(this.resource, { changes, content, contentLength, options: { encoding, overwriteEncoding, version } }, token);
558
- this.contentChanges.splice(0, changes.length);
559
- this.resourceVersion = this.resource.version;
560
- this.updateContentEncoding();
561
- this.setValid(true);
562
-
563
- if (token.isCancellationRequested) {
564
- return;
565
- }
566
-
567
- this.setDirty(false);
568
- this.fireDidSaveModel();
569
- } catch (e) {
570
- if (!ResourceError.OutOfSync.is(e)) {
571
- throw e;
572
- }
573
- }
574
- }
575
-
576
- protected async fireWillSaveModel(reason: TextDocumentSaveReason, token: CancellationToken, options?: SaveOptions): Promise<void> {
577
- type EditContributor = Thenable<monaco.editor.IIdentifiedSingleEditOperation[]>;
578
-
579
- const firing = this.onWillSaveModelEmitter.sequence(async listener => {
580
- if (token.isCancellationRequested) {
581
- return false;
582
- }
583
- const waitables: EditContributor[] = [];
584
- const { version } = this;
585
-
586
- const event = {
587
- model: this, reason, options,
588
- waitUntil: (thenable: EditContributor) => {
589
- if (Object.isFrozen(waitables)) {
590
- throw new Error('waitUntil cannot be called asynchronously.');
591
- }
592
- waitables.push(thenable);
593
- }
594
- };
595
-
596
- // Fire.
597
- try {
598
- listener(event);
599
- } catch (err) {
600
- console.error(err);
601
- return true;
602
- }
603
-
604
- // Asynchronous calls to `waitUntil` should fail.
605
- Object.freeze(waitables);
606
-
607
- // Wait for all promises.
608
- const edits = await Promise.all(waitables).then(allOperations =>
609
- ([] as monaco.editor.IIdentifiedSingleEditOperation[]).concat(...allOperations)
610
- );
611
- if (token.isCancellationRequested) {
612
- return false;
613
- }
614
-
615
- // In a perfect world, we should only apply edits if document is clean.
616
- if (version !== this.version) {
617
- console.error('onWillSave listeners should provide edits, not directly alter the document.');
618
- }
619
-
620
- // Finally apply edits provided by this listener before firing the next.
621
- if (edits && edits.length > 0) {
622
- this.applyEdits(edits, {
623
- ignoreDirty: true,
624
- });
625
- }
626
-
627
- return true;
628
- });
629
-
630
- try {
631
- await firing;
632
- } catch (e) {
633
- console.error(e);
634
- }
635
- }
636
-
637
- protected fireDidSaveModel(): void {
638
- this.onDidSaveModelEmitter.fire(this.model);
639
- }
640
-
641
- async revert(options?: Saveable.RevertOptions): Promise<void> {
642
- this.trace(log => log('MonacoEditorModel.revert - enter'));
643
- this.cancelSave();
644
- const soft = options && options.soft;
645
- if (soft !== true) {
646
- const dirty = this._dirty;
647
- this._dirty = false;
648
- try {
649
- await this.sync();
650
- } finally {
651
- this._dirty = dirty;
652
- }
653
- }
654
- this.setDirty(false);
655
- this.trace(log => log('MonacoEditorModel.revert - exit'));
656
- }
657
-
658
- createSnapshot(preserveBOM?: boolean): ITextSnapshot {
659
- return this.model.createSnapshot(preserveBOM);
660
- }
661
-
662
- applySnapshot(snapshot: Saveable.Snapshot): void {
663
- const value = 'value' in snapshot ? snapshot.value : snapshot.read() ?? '';
664
- this.model.setValue(value);
665
- }
666
-
667
- protected trace(loggable: Loggable): void {
668
- if (this.logger) {
669
- this.logger.debug((log: Log) =>
670
- loggable((message, ...params) => log(message, ...params, this.resource.uri.toString(true)))
671
- );
672
- }
673
- }
674
-
675
- }
676
- export namespace MonacoEditorModel {
677
- export interface ApplyEditsOptions {
678
- ignoreDirty: boolean
679
- ignoreContentChanges: boolean
680
- }
681
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2017 TypeFox and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ import { Position, Range, TextDocumentSaveReason, TextDocumentContentChangeEvent } from '@theia/core/shared/vscode-languageserver-protocol';
18
+ import { TextEditorDocument, EncodingMode, FindMatchesOptions, FindMatch, EditorPreferences } from '@theia/editor/lib/browser';
19
+ import { DisposableCollection, Disposable } from '@theia/core/lib/common/disposable';
20
+ import { Emitter, Event } from '@theia/core/lib/common/event';
21
+ import { CancellationTokenSource, CancellationToken } from '@theia/core/lib/common/cancellation';
22
+ import { Resource, ResourceError, ResourceVersion, UNTITLED_SCHEME } from '@theia/core/lib/common/resource';
23
+ import { Saveable, SaveOptions } from '@theia/core/lib/browser/saveable';
24
+ import { MonacoToProtocolConverter } from './monaco-to-protocol-converter';
25
+ import { ProtocolToMonacoConverter } from './protocol-to-monaco-converter';
26
+ import { ILogger, Loggable, Log } from '@theia/core/lib/common/logger';
27
+ import { IIdentifiedSingleEditOperation, ITextBufferFactory, ITextModel, ITextSnapshot } from '@theia/monaco-editor-core/esm/vs/editor/common/model';
28
+ import { IResolvedTextEditorModel } from '@theia/monaco-editor-core/esm/vs/editor/common/services/resolverService';
29
+ import * as monaco from '@theia/monaco-editor-core';
30
+ import { StandaloneServices } from '@theia/monaco-editor-core/esm/vs/editor/standalone/browser/standaloneServices';
31
+ import { ILanguageService } from '@theia/monaco-editor-core/esm/vs/editor/common/languages/language';
32
+ import { IModelService } from '@theia/monaco-editor-core/esm/vs/editor/common/services/model';
33
+ import { createTextBufferFactoryFromStream } from '@theia/monaco-editor-core/esm/vs/editor/common/model/textModel';
34
+ import { editorGeneratedPreferenceProperties } from '@theia/editor/lib/browser/editor-generated-preference-schema';
35
+
36
+ export {
37
+ TextDocumentSaveReason
38
+ };
39
+
40
+ export interface WillSaveMonacoModelEvent {
41
+ readonly model: MonacoEditorModel;
42
+ readonly reason: TextDocumentSaveReason;
43
+ readonly options?: SaveOptions;
44
+ waitUntil(thenable: Thenable<IIdentifiedSingleEditOperation[]>): void;
45
+ }
46
+
47
+ export interface MonacoModelContentChangedEvent {
48
+ readonly model: MonacoEditorModel;
49
+ readonly contentChanges: TextDocumentContentChangeEvent[];
50
+ }
51
+
52
+ export class MonacoEditorModel implements IResolvedTextEditorModel, TextEditorDocument {
53
+
54
+ autoSave: EditorPreferences['files.autoSave'] = 'afterDelay';
55
+ autoSaveDelay = 500;
56
+ suppressOpenEditorWhenDirty = false;
57
+ lineNumbersMinChars = 3;
58
+
59
+ /* @deprecated there is no general save timeout, each participant should introduce a sensible timeout */
60
+ readonly onWillSaveLoopTimeOut = 1500;
61
+ protected bufferSavedVersionId: number;
62
+
63
+ protected model: ITextModel;
64
+ protected readonly resolveModel: Promise<void>;
65
+
66
+ protected readonly toDispose = new DisposableCollection();
67
+ protected readonly toDisposeOnAutoSave = new DisposableCollection();
68
+
69
+ protected readonly onDidChangeContentEmitter = new Emitter<MonacoModelContentChangedEvent>();
70
+ readonly onDidChangeContent = this.onDidChangeContentEmitter.event;
71
+
72
+ protected readonly onDidSaveModelEmitter = new Emitter<ITextModel>();
73
+ readonly onDidSaveModel = this.onDidSaveModelEmitter.event;
74
+
75
+ protected readonly onWillSaveModelEmitter = new Emitter<WillSaveMonacoModelEvent>();
76
+ readonly onWillSaveModel = this.onWillSaveModelEmitter.event;
77
+
78
+ protected readonly onDidChangeValidEmitter = new Emitter<void>();
79
+ readonly onDidChangeValid = this.onDidChangeValidEmitter.event;
80
+
81
+ protected readonly onDidChangeEncodingEmitter = new Emitter<string>();
82
+ readonly onDidChangeEncoding = this.onDidChangeEncodingEmitter.event;
83
+
84
+ private preferredEncoding: string | undefined;
85
+ private contentEncoding: string | undefined;
86
+
87
+ protected resourceVersion: ResourceVersion | undefined;
88
+
89
+ constructor(
90
+ protected readonly resource: Resource,
91
+ protected readonly m2p: MonacoToProtocolConverter,
92
+ protected readonly p2m: ProtocolToMonacoConverter,
93
+ protected readonly logger?: ILogger,
94
+ protected readonly editorPreferences?: EditorPreferences
95
+ ) {
96
+ this.toDispose.push(resource);
97
+ this.toDispose.push(this.toDisposeOnAutoSave);
98
+ this.toDispose.push(this.onDidChangeContentEmitter);
99
+ this.toDispose.push(this.onDidSaveModelEmitter);
100
+ this.toDispose.push(this.onWillSaveModelEmitter);
101
+ this.toDispose.push(this.onDirtyChangedEmitter);
102
+ this.toDispose.push(this.onDidChangeValidEmitter);
103
+ this.toDispose.push(Disposable.create(() => this.cancelSave()));
104
+ this.toDispose.push(Disposable.create(() => this.cancelSync()));
105
+ this.resolveModel = this.readContents().then(
106
+ content => this.initialize(content || '')
107
+ );
108
+ }
109
+
110
+ dispose(): void {
111
+ this.toDispose.dispose();
112
+ }
113
+
114
+ isDisposed(): boolean {
115
+ return this.toDispose.disposed;
116
+ }
117
+
118
+ resolve(): Promise<void> {
119
+ return this.resolveModel;
120
+ }
121
+
122
+ isResolved(): boolean {
123
+ return Boolean(this.model);
124
+ }
125
+
126
+ setEncoding(encoding: string, mode: EncodingMode): Promise<void> {
127
+ if (mode === EncodingMode.Decode && this.dirty) {
128
+ return Promise.resolve();
129
+ }
130
+ if (!this.setPreferredEncoding(encoding)) {
131
+ return Promise.resolve();
132
+ }
133
+ if (mode === EncodingMode.Decode) {
134
+ return this.sync();
135
+ }
136
+ return this.scheduleSave(TextDocumentSaveReason.Manual, this.cancelSave(), true);
137
+ }
138
+
139
+ getEncoding(): string | undefined {
140
+ return this.preferredEncoding || this.contentEncoding;
141
+ }
142
+
143
+ protected setPreferredEncoding(encoding: string): boolean {
144
+ if (encoding === this.preferredEncoding || (!this.preferredEncoding && encoding === this.contentEncoding)) {
145
+ return false;
146
+ }
147
+ this.preferredEncoding = encoding;
148
+ this.onDidChangeEncodingEmitter.fire(encoding);
149
+ return true;
150
+ }
151
+
152
+ protected updateContentEncoding(): void {
153
+ const contentEncoding = this.resource.encoding;
154
+ if (!contentEncoding || this.contentEncoding === contentEncoding) {
155
+ return;
156
+ }
157
+ this.contentEncoding = contentEncoding;
158
+ if (!this.preferredEncoding) {
159
+ this.onDidChangeEncodingEmitter.fire(contentEncoding);
160
+ }
161
+ }
162
+
163
+ /**
164
+ * #### Important
165
+ * Only this method can create an instance of `monaco.editor.IModel`,
166
+ * there should not be other calls to `monaco.editor.createModel`.
167
+ */
168
+ protected initialize(value: string | ITextBufferFactory): void {
169
+ if (!this.toDispose.disposed) {
170
+ const uri = monaco.Uri.parse(this.resource.uri.toString());
171
+ let firstLine;
172
+ if (typeof value === 'string') {
173
+ firstLine = value;
174
+ const firstLF = value.indexOf('\n');
175
+ if (firstLF !== -1) {
176
+ firstLine = value.substring(0, firstLF);
177
+ }
178
+ } else {
179
+ firstLine = value.getFirstLineText(1000);
180
+ }
181
+ const languageSelection = StandaloneServices.get(ILanguageService).createByFilepathOrFirstLine(uri, firstLine);
182
+ this.model = StandaloneServices.get(IModelService).createModel(value, languageSelection, uri);
183
+ this.resourceVersion = this.resource.version;
184
+ this.setDirty(this._dirty || (this.resource.uri.scheme === UNTITLED_SCHEME && this.model.getValueLength() > 0));
185
+ this.updateSavedVersionId();
186
+ this.toDispose.push(this.model);
187
+ this.toDispose.push(this.model.onDidChangeContent(event => this.fireDidChangeContent(event)));
188
+ if (this.resource.onDidChangeContents) {
189
+ this.toDispose.push(this.resource.onDidChangeContents(() => this.sync()));
190
+ }
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Use `valid` to access it.
196
+ * Use `setValid` to mutate it.
197
+ */
198
+ protected _valid = false;
199
+ /**
200
+ * Whether it is possible to load content from the underlying resource.
201
+ */
202
+ get valid(): boolean {
203
+ return this._valid;
204
+ }
205
+ protected setValid(valid: boolean): void {
206
+ if (valid === this._valid) {
207
+ return;
208
+ }
209
+ this._valid = valid;
210
+ this.onDidChangeValidEmitter.fire(undefined);
211
+ }
212
+
213
+ protected _dirty = false;
214
+ get dirty(): boolean {
215
+ return this._dirty;
216
+ }
217
+ protected setDirty(dirty: boolean): void {
218
+ if (dirty === this._dirty) {
219
+ return;
220
+ }
221
+ this._dirty = dirty;
222
+ if (dirty === false) {
223
+ this.updateSavedVersionId();
224
+ }
225
+ this.onDirtyChangedEmitter.fire(undefined);
226
+ }
227
+
228
+ private updateSavedVersionId(): void {
229
+ this.bufferSavedVersionId = this.model.getAlternativeVersionId();
230
+ }
231
+
232
+ protected readonly onDirtyChangedEmitter = new Emitter<void>();
233
+ get onDirtyChanged(): Event<void> {
234
+ return this.onDirtyChangedEmitter.event;
235
+ }
236
+
237
+ get uri(): string {
238
+ return this.resource.uri.toString();
239
+ }
240
+
241
+ protected _languageId: string | undefined;
242
+ get languageId(): string {
243
+ return this._languageId !== undefined ? this._languageId : this.model.getLanguageId();
244
+ }
245
+
246
+ getLanguageId(): string | undefined {
247
+ return this.languageId;
248
+ }
249
+
250
+ /**
251
+ * It's a hack to dispatch close notification with an old language id; don't use it.
252
+ */
253
+ setLanguageId(languageId: string | undefined): void {
254
+ this._languageId = languageId;
255
+ }
256
+
257
+ get version(): number {
258
+ return this.model.getVersionId();
259
+ }
260
+
261
+ /**
262
+ * Return selected text by Range or all text by default
263
+ */
264
+ getText(range?: Range): string {
265
+ if (!range) {
266
+ return this.model.getValue();
267
+ } else {
268
+ return this.model.getValueInRange(this.p2m.asRange(range));
269
+ }
270
+ }
271
+
272
+ positionAt(offset: number): Position {
273
+ const { lineNumber, column } = this.model.getPositionAt(offset);
274
+ return this.m2p.asPosition(lineNumber, column);
275
+ }
276
+
277
+ offsetAt(position: Position): number {
278
+ return this.model.getOffsetAt(this.p2m.asPosition(position));
279
+ }
280
+
281
+ get lineCount(): number {
282
+ return this.model.getLineCount();
283
+ }
284
+
285
+ /**
286
+ * Retrieves a line in a text document expressed as a one-based position.
287
+ */
288
+ getLineContent(lineNumber: number): string {
289
+ return this.model.getLineContent(lineNumber);
290
+ }
291
+
292
+ getLineMaxColumn(lineNumber: number): number {
293
+ return this.model.getLineMaxColumn(lineNumber);
294
+ }
295
+
296
+ toValidPosition(position: Position): Position {
297
+ const { lineNumber, column } = this.model.validatePosition(this.p2m.asPosition(position));
298
+ return this.m2p.asPosition(lineNumber, column);
299
+ }
300
+
301
+ toValidRange(range: Range): Range {
302
+ return this.m2p.asRange(this.model.validateRange(this.p2m.asRange(range)));
303
+ }
304
+
305
+ get readOnly(): boolean {
306
+ return this.resource.saveContents === undefined;
307
+ }
308
+
309
+ isReadonly(): boolean {
310
+ return this.readOnly;
311
+ }
312
+
313
+ get onDispose(): monaco.IEvent<void> {
314
+ return this.toDispose.onDispose;
315
+ }
316
+
317
+ get onWillDispose(): Event<void> {
318
+ return this.toDispose.onDispose;
319
+ }
320
+
321
+ // We have a TypeScript problem here. There is a const enum `DefaultEndOfLine` used for ITextModel and a non-const redeclaration of that enum in the public API in
322
+ // Monaco.editor. The values will be the same, but TS won't accept that the two enums are equivalent, so it says these types are irreconcilable.
323
+ get textEditorModel(): monaco.editor.ITextModel & ITextModel {
324
+ // @ts-expect-error ts(2322)
325
+ return this.model;
326
+ }
327
+
328
+ /**
329
+ * Find all matches in an editor for the given options.
330
+ * @param options the options for finding matches.
331
+ *
332
+ * @returns the list of matches.
333
+ */
334
+ findMatches(options: FindMatchesOptions): FindMatch[] {
335
+ const wordSeparators = this.editorPreferences?.['editor.wordSeparators'] ?? editorGeneratedPreferenceProperties['editor.wordSeparators'].default as string;
336
+ const results: monaco.editor.FindMatch[] = this.model.findMatches(
337
+ options.searchString,
338
+ false,
339
+ options.isRegex,
340
+ options.matchCase,
341
+ // eslint-disable-next-line no-null/no-null
342
+ options.matchWholeWord ? wordSeparators : null,
343
+ true,
344
+ options.limitResultCount
345
+ );
346
+ const extractedMatches: FindMatch[] = [];
347
+ results.forEach(r => {
348
+ if (r.matches) {
349
+ extractedMatches.push({
350
+ matches: r.matches,
351
+ range: Range.create(r.range.startLineNumber, r.range.startColumn, r.range.endLineNumber, r.range.endColumn)
352
+ });
353
+ }
354
+ });
355
+ return extractedMatches;
356
+ }
357
+
358
+ async load(): Promise<MonacoEditorModel> {
359
+ await this.resolveModel;
360
+ return this;
361
+ }
362
+
363
+ save(options?: SaveOptions): Promise<void> {
364
+ return this.scheduleSave(TextDocumentSaveReason.Manual, undefined, undefined, options);
365
+ }
366
+
367
+ protected pendingOperation = Promise.resolve();
368
+ protected async run(operation: () => Promise<void>): Promise<void> {
369
+ if (this.toDispose.disposed) {
370
+ return;
371
+ }
372
+ return this.pendingOperation = this.pendingOperation.then(async () => {
373
+ try {
374
+ await operation();
375
+ } catch (e) {
376
+ console.error(e);
377
+ }
378
+ });
379
+ }
380
+
381
+ protected syncCancellationTokenSource = new CancellationTokenSource();
382
+ protected cancelSync(): CancellationToken {
383
+ this.trace(log => log('MonacoEditorModel.cancelSync'));
384
+ this.syncCancellationTokenSource.cancel();
385
+ this.syncCancellationTokenSource = new CancellationTokenSource();
386
+ return this.syncCancellationTokenSource.token;
387
+ }
388
+
389
+ async sync(): Promise<void> {
390
+ const token = this.cancelSync();
391
+ return this.run(() => this.doSync(token));
392
+ }
393
+ protected async doSync(token: CancellationToken): Promise<void> {
394
+ this.trace(log => log('MonacoEditorModel.doSync - enter'));
395
+ if (token.isCancellationRequested) {
396
+ this.trace(log => log('MonacoEditorModel.doSync - exit - cancelled'));
397
+ return;
398
+ }
399
+
400
+ const value = await this.readContents();
401
+ if (value === undefined) {
402
+ this.trace(log => log('MonacoEditorModel.doSync - exit - resource not found'));
403
+ return;
404
+ }
405
+ if (token.isCancellationRequested) {
406
+ this.trace(log => log('MonacoEditorModel.doSync - exit - cancelled while looking for a resource'));
407
+ return;
408
+ }
409
+ if (this._dirty) {
410
+ this.trace(log => log('MonacoEditorModel.doSync - exit - pending dirty changes'));
411
+ return;
412
+ }
413
+
414
+ this.resourceVersion = this.resource.version;
415
+ this.updateModel(() => StandaloneServices.get(IModelService).updateModel(this.model, value), {
416
+ ignoreDirty: true,
417
+ ignoreContentChanges: true
418
+ });
419
+ this.trace(log => log('MonacoEditorModel.doSync - exit'));
420
+ }
421
+ protected async readContents(): Promise<string | ITextBufferFactory | undefined> {
422
+ try {
423
+ const options = { encoding: this.getEncoding() };
424
+ const content = await (this.resource.readStream ? this.resource.readStream(options) : this.resource.readContents(options));
425
+ let value;
426
+ if (typeof content === 'string') {
427
+ value = content;
428
+ } else {
429
+ value = createTextBufferFactoryFromStream(content);
430
+ }
431
+ this.updateContentEncoding();
432
+ this.setValid(true);
433
+ return value;
434
+ } catch (e) {
435
+ this.setValid(false);
436
+ if (ResourceError.NotFound.is(e)) {
437
+ return undefined;
438
+ }
439
+ throw e;
440
+ }
441
+ }
442
+
443
+ protected ignoreDirtyEdits = false;
444
+ protected markAsDirty(): void {
445
+ this.trace(log => log('MonacoEditorModel.markAsDirty - enter'));
446
+ if (this.ignoreDirtyEdits) {
447
+ this.trace(log => log('MonacoEditorModel.markAsDirty - exit - ignoring dirty changes enabled'));
448
+ return;
449
+ }
450
+ this.cancelSync();
451
+ this.setDirty(true);
452
+ this.doAutoSave();
453
+ this.trace(log => log('MonacoEditorModel.markAsDirty - exit'));
454
+ }
455
+
456
+ protected doAutoSave(): void {
457
+ if (this.autoSave !== 'off' && this.resource.uri.scheme !== UNTITLED_SCHEME) {
458
+ const token = this.cancelSave();
459
+ this.toDisposeOnAutoSave.dispose();
460
+ const handle = window.setTimeout(() => {
461
+ this.scheduleSave(TextDocumentSaveReason.AfterDelay, token);
462
+ }, this.autoSaveDelay);
463
+ this.toDisposeOnAutoSave.push(Disposable.create(() =>
464
+ window.clearTimeout(handle))
465
+ );
466
+ }
467
+ }
468
+
469
+ protected saveCancellationTokenSource = new CancellationTokenSource();
470
+ protected cancelSave(): CancellationToken {
471
+ this.trace(log => log('MonacoEditorModel.cancelSave'));
472
+ this.saveCancellationTokenSource.cancel();
473
+ this.saveCancellationTokenSource = new CancellationTokenSource();
474
+ return this.saveCancellationTokenSource.token;
475
+ }
476
+
477
+ protected scheduleSave(reason: TextDocumentSaveReason, token: CancellationToken = this.cancelSave(), overwriteEncoding?: boolean, options?: SaveOptions): Promise<void> {
478
+ return this.run(() => this.doSave(reason, token, overwriteEncoding, options));
479
+ }
480
+
481
+ protected ignoreContentChanges = false;
482
+ protected readonly contentChanges: TextDocumentContentChangeEvent[] = [];
483
+ protected pushContentChanges(contentChanges: TextDocumentContentChangeEvent[]): void {
484
+ if (!this.ignoreContentChanges) {
485
+ this.contentChanges.push(...contentChanges);
486
+ }
487
+ }
488
+
489
+ protected fireDidChangeContent(event: monaco.editor.IModelContentChangedEvent): void {
490
+ this.trace(log => log(`MonacoEditorModel.fireDidChangeContent - enter - ${JSON.stringify(event, undefined, 2)}`));
491
+ if (this.model.getAlternativeVersionId() === this.bufferSavedVersionId) {
492
+ this.setDirty(false);
493
+ } else {
494
+ this.markAsDirty();
495
+ }
496
+
497
+ const changeContentEvent = this.asContentChangedEvent(event);
498
+ this.onDidChangeContentEmitter.fire(changeContentEvent);
499
+ this.pushContentChanges(changeContentEvent.contentChanges);
500
+ this.trace(log => log('MonacoEditorModel.fireDidChangeContent - exit'));
501
+ }
502
+ protected asContentChangedEvent(event: monaco.editor.IModelContentChangedEvent): MonacoModelContentChangedEvent {
503
+ const contentChanges = event.changes.map(change => this.asTextDocumentContentChangeEvent(change));
504
+ return { model: this, contentChanges };
505
+ }
506
+ protected asTextDocumentContentChangeEvent(change: monaco.editor.IModelContentChange): TextDocumentContentChangeEvent {
507
+ const range = this.m2p.asRange(change.range);
508
+ const rangeLength = change.rangeLength;
509
+ const text = change.text;
510
+ return { range, rangeLength, text };
511
+ }
512
+
513
+ protected applyEdits(
514
+ operations: monaco.editor.IIdentifiedSingleEditOperation[],
515
+ options?: Partial<MonacoEditorModel.ApplyEditsOptions>
516
+ ): void {
517
+ return this.updateModel(() => this.model.applyEdits(operations), options);
518
+ }
519
+
520
+ protected updateModel<T>(doUpdate: () => T, options?: Partial<MonacoEditorModel.ApplyEditsOptions>): T {
521
+ const resolvedOptions: MonacoEditorModel.ApplyEditsOptions = {
522
+ ignoreDirty: false,
523
+ ignoreContentChanges: false,
524
+ ...options
525
+ };
526
+ const { ignoreDirtyEdits, ignoreContentChanges } = this;
527
+ this.ignoreDirtyEdits = resolvedOptions.ignoreDirty;
528
+ this.ignoreContentChanges = resolvedOptions.ignoreContentChanges;
529
+ try {
530
+ return doUpdate();
531
+ } finally {
532
+ this.ignoreDirtyEdits = ignoreDirtyEdits;
533
+ this.ignoreContentChanges = ignoreContentChanges;
534
+ }
535
+ }
536
+
537
+ protected async doSave(reason: TextDocumentSaveReason, token: CancellationToken, overwriteEncoding?: boolean, options?: SaveOptions): Promise<void> {
538
+ if (token.isCancellationRequested || !this.resource.saveContents) {
539
+ return;
540
+ }
541
+
542
+ await this.fireWillSaveModel(reason, token, options);
543
+ if (token.isCancellationRequested) {
544
+ return;
545
+ }
546
+
547
+ const changes = [...this.contentChanges];
548
+ if (changes.length === 0 && !overwriteEncoding && reason !== TextDocumentSaveReason.Manual) {
549
+ return;
550
+ }
551
+
552
+ const contentLength = this.model.getValueLength();
553
+ const content = this.model.createSnapshot() || this.model.getValue();
554
+ try {
555
+ const encoding = this.getEncoding();
556
+ const version = this.resourceVersion;
557
+ await Resource.save(this.resource, { changes, content, contentLength, options: { encoding, overwriteEncoding, version } }, token);
558
+ this.contentChanges.splice(0, changes.length);
559
+ this.resourceVersion = this.resource.version;
560
+ this.updateContentEncoding();
561
+ this.setValid(true);
562
+
563
+ if (token.isCancellationRequested) {
564
+ return;
565
+ }
566
+
567
+ this.setDirty(false);
568
+ this.fireDidSaveModel();
569
+ } catch (e) {
570
+ if (!ResourceError.OutOfSync.is(e)) {
571
+ throw e;
572
+ }
573
+ }
574
+ }
575
+
576
+ protected async fireWillSaveModel(reason: TextDocumentSaveReason, token: CancellationToken, options?: SaveOptions): Promise<void> {
577
+ type EditContributor = Thenable<monaco.editor.IIdentifiedSingleEditOperation[]>;
578
+
579
+ const firing = this.onWillSaveModelEmitter.sequence(async listener => {
580
+ if (token.isCancellationRequested) {
581
+ return false;
582
+ }
583
+ const waitables: EditContributor[] = [];
584
+ const { version } = this;
585
+
586
+ const event = {
587
+ model: this, reason, options,
588
+ waitUntil: (thenable: EditContributor) => {
589
+ if (Object.isFrozen(waitables)) {
590
+ throw new Error('waitUntil cannot be called asynchronously.');
591
+ }
592
+ waitables.push(thenable);
593
+ }
594
+ };
595
+
596
+ // Fire.
597
+ try {
598
+ listener(event);
599
+ } catch (err) {
600
+ console.error(err);
601
+ return true;
602
+ }
603
+
604
+ // Asynchronous calls to `waitUntil` should fail.
605
+ Object.freeze(waitables);
606
+
607
+ // Wait for all promises.
608
+ const edits = await Promise.all(waitables).then(allOperations =>
609
+ ([] as monaco.editor.IIdentifiedSingleEditOperation[]).concat(...allOperations)
610
+ );
611
+ if (token.isCancellationRequested) {
612
+ return false;
613
+ }
614
+
615
+ // In a perfect world, we should only apply edits if document is clean.
616
+ if (version !== this.version) {
617
+ console.error('onWillSave listeners should provide edits, not directly alter the document.');
618
+ }
619
+
620
+ // Finally apply edits provided by this listener before firing the next.
621
+ if (edits && edits.length > 0) {
622
+ this.applyEdits(edits, {
623
+ ignoreDirty: true,
624
+ });
625
+ }
626
+
627
+ return true;
628
+ });
629
+
630
+ try {
631
+ await firing;
632
+ } catch (e) {
633
+ console.error(e);
634
+ }
635
+ }
636
+
637
+ protected fireDidSaveModel(): void {
638
+ this.onDidSaveModelEmitter.fire(this.model);
639
+ }
640
+
641
+ async revert(options?: Saveable.RevertOptions): Promise<void> {
642
+ this.trace(log => log('MonacoEditorModel.revert - enter'));
643
+ this.cancelSave();
644
+ const soft = options && options.soft;
645
+ if (soft !== true) {
646
+ const dirty = this._dirty;
647
+ this._dirty = false;
648
+ try {
649
+ await this.sync();
650
+ } finally {
651
+ this._dirty = dirty;
652
+ }
653
+ }
654
+ this.setDirty(false);
655
+ this.trace(log => log('MonacoEditorModel.revert - exit'));
656
+ }
657
+
658
+ createSnapshot(preserveBOM?: boolean): ITextSnapshot {
659
+ return this.model.createSnapshot(preserveBOM);
660
+ }
661
+
662
+ applySnapshot(snapshot: Saveable.Snapshot): void {
663
+ const value = 'value' in snapshot ? snapshot.value : snapshot.read() ?? '';
664
+ this.model.setValue(value);
665
+ }
666
+
667
+ protected trace(loggable: Loggable): void {
668
+ if (this.logger) {
669
+ this.logger.debug((log: Log) =>
670
+ loggable((message, ...params) => log(message, ...params, this.resource.uri.toString(true)))
671
+ );
672
+ }
673
+ }
674
+
675
+ }
676
+ export namespace MonacoEditorModel {
677
+ export interface ApplyEditsOptions {
678
+ ignoreDirty: boolean
679
+ ignoreContentChanges: boolean
680
+ }
681
+ }