@theia/monaco 1.53.0-next.4 → 1.53.0-next.55

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