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

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 (77) 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-editor-zone-widget.js +1 -1
  14. package/lib/browser/monaco-frontend-application-contribution.js +25 -25
  15. package/lib/browser/simple-monaco-editor.d.ts +3 -1
  16. package/lib/browser/simple-monaco-editor.d.ts.map +1 -1
  17. package/lib/browser/simple-monaco-editor.js +9 -2
  18. package/lib/browser/simple-monaco-editor.js.map +1 -1
  19. package/package.json +8 -8
  20. package/src/browser/index.ts +17 -17
  21. package/src/browser/markdown-renderer/monaco-markdown-renderer.ts +109 -109
  22. package/src/browser/monaco-bulk-edit-service.ts +64 -64
  23. package/src/browser/monaco-color-registry.ts +73 -73
  24. package/src/browser/monaco-command-registry.ts +85 -85
  25. package/src/browser/monaco-command-service.ts +90 -90
  26. package/src/browser/monaco-command.ts +303 -303
  27. package/src/browser/monaco-context-key-service.ts +144 -144
  28. package/src/browser/monaco-context-menu.ts +112 -112
  29. package/src/browser/monaco-diff-editor.ts +141 -141
  30. package/src/browser/monaco-diff-navigator-factory.ts +39 -39
  31. package/src/browser/monaco-editor-model.ts +693 -693
  32. package/src/browser/monaco-editor-peek-view-widget.ts +233 -233
  33. package/src/browser/monaco-editor-provider.ts +455 -455
  34. package/src/browser/monaco-editor-service.ts +152 -152
  35. package/src/browser/monaco-editor-zone-widget.ts +250 -250
  36. package/src/browser/monaco-editor.ts +733 -733
  37. package/src/browser/monaco-formatting-conflicts.ts +116 -116
  38. package/src/browser/monaco-frontend-application-contribution.ts +182 -182
  39. package/src/browser/monaco-frontend-module.ts +319 -319
  40. package/src/browser/monaco-gotoline-quick-access.ts +47 -47
  41. package/src/browser/monaco-gotosymbol-quick-access.ts +53 -53
  42. package/src/browser/monaco-icon-registry.ts +49 -49
  43. package/src/browser/monaco-indexed-db.ts +130 -130
  44. package/src/browser/monaco-init.ts +134 -134
  45. package/src/browser/monaco-keybinding.ts +111 -111
  46. package/src/browser/monaco-keycode-map.ts +171 -171
  47. package/src/browser/monaco-languages.ts +177 -177
  48. package/src/browser/monaco-marker-collection.ts +83 -83
  49. package/src/browser/monaco-menu.ts +147 -147
  50. package/src/browser/monaco-mime-service.ts +71 -71
  51. package/src/browser/monaco-outline-contribution.ts +404 -404
  52. package/src/browser/monaco-outline-decorator.ts +66 -66
  53. package/src/browser/monaco-quick-access-registry.ts +112 -112
  54. package/src/browser/monaco-quick-input-service.ts +701 -701
  55. package/src/browser/monaco-resolved-keybinding.ts +162 -162
  56. package/src/browser/monaco-snippet-suggest-provider.ts +306 -306
  57. package/src/browser/monaco-standalone-theme-service.ts +51 -51
  58. package/src/browser/monaco-status-bar-contribution.ts +110 -110
  59. package/src/browser/monaco-text-model-service.ts +157 -157
  60. package/src/browser/monaco-theming-service.ts +204 -204
  61. package/src/browser/monaco-to-protocol-converter.ts +82 -82
  62. package/src/browser/monaco-undo-redo-handler.ts +64 -64
  63. package/src/browser/monaco-workspace.ts +416 -416
  64. package/src/browser/protocol-to-monaco-converter.ts +158 -158
  65. package/src/browser/simple-monaco-editor.ts +228 -216
  66. package/src/browser/style/index.css +266 -266
  67. package/src/browser/textmate/index.ts +20 -20
  68. package/src/browser/textmate/monaco-textmate-frontend-bindings.ts +90 -90
  69. package/src/browser/textmate/monaco-textmate-service.ts +187 -187
  70. package/src/browser/textmate/monaco-theme-registry.ts +176 -176
  71. package/src/browser/textmate/monaco-theme-types.ts +37 -37
  72. package/src/browser/textmate/textmate-contribution.ts +29 -29
  73. package/src/browser/textmate/textmate-registry.ts +129 -129
  74. package/src/browser/textmate/textmate-snippet-completion-provider.ts +73 -73
  75. package/src/browser/textmate/textmate-tokenizer.ts +84 -84
  76. package/src/browser/workspace-symbol-command.ts +196 -196
  77. package/src/package.spec.ts +28 -28
@@ -1,693 +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 } 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
- }
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
+ }