-
Notifications
You must be signed in to change notification settings - Fork 31k
/
Copy pathindentation.ts
731 lines (609 loc) · 24.9 KB
/
indentation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DisposableStore } from 'vs/base/common/lifecycle';
import * as strings from 'vs/base/common/strings';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorAction, EditorContributionInstantiation, IActionOptions, registerEditorAction, registerEditorContribution, ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { ShiftCommand } from 'vs/editor/common/commands/shiftCommand';
import { EditorAutoIndentStrategy, EditorOption } from 'vs/editor/common/config/editorOptions';
import { EditOperation, ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { IRange, Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ICommand, ICursorStateComputerData, IEditOperationBuilder, IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { EndOfLineSequence, ITextModel } from 'vs/editor/common/model';
import { TextEdit } from 'vs/editor/common/languages';
import { StandardTokenType } from 'vs/editor/common/encodedTokenAttributes';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { IndentConsts } from 'vs/editor/common/languages/supports/indentRules';
import { IModelService } from 'vs/editor/common/services/model';
import * as indentUtils from 'vs/editor/contrib/indentation/browser/indentUtils';
import * as nls from 'vs/nls';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { normalizeIndentation } from 'vs/editor/common/core/indentation';
import { getGoodIndentForLine, getIndentMetadata } from 'vs/editor/common/languages/autoIndent';
export function getReindentEditOperations(model: ITextModel, languageConfigurationService: ILanguageConfigurationService, startLineNumber: number, endLineNumber: number, inheritedIndent?: string): ISingleEditOperation[] {
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return [];
}
const indentationRules = languageConfigurationService.getLanguageConfiguration(model.getLanguageId()).indentationRules;
if (!indentationRules) {
return [];
}
endLineNumber = Math.min(endLineNumber, model.getLineCount());
// Skip `unIndentedLinePattern` lines
while (startLineNumber <= endLineNumber) {
if (!indentationRules.unIndentedLinePattern) {
break;
}
const text = model.getLineContent(startLineNumber);
if (!indentationRules.unIndentedLinePattern.test(text)) {
break;
}
startLineNumber++;
}
if (startLineNumber > endLineNumber - 1) {
return [];
}
const { tabSize, indentSize, insertSpaces } = model.getOptions();
const shiftIndent = (indentation: string, count?: number) => {
count = count || 1;
return ShiftCommand.shiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
};
const unshiftIndent = (indentation: string, count?: number) => {
count = count || 1;
return ShiftCommand.unshiftIndent(indentation, indentation.length + count, tabSize, indentSize, insertSpaces);
};
const indentEdits: ISingleEditOperation[] = [];
// indentation being passed to lines below
let globalIndent: string;
// Calculate indentation for the first line
// If there is no passed-in indentation, we use the indentation of the first line as base.
const currentLineText = model.getLineContent(startLineNumber);
let adjustedLineContent = currentLineText;
if (inheritedIndent !== undefined && inheritedIndent !== null) {
globalIndent = inheritedIndent;
const oldIndentation = strings.getLeadingWhitespace(currentLineText);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
globalIndent = unshiftIndent(globalIndent);
adjustedLineContent = globalIndent + currentLineText.substring(oldIndentation.length);
}
if (currentLineText !== adjustedLineContent) {
indentEdits.push(EditOperation.replaceMove(new Selection(startLineNumber, 1, startLineNumber, oldIndentation.length + 1), normalizeIndentation(globalIndent, indentSize, insertSpaces)));
}
} else {
globalIndent = strings.getLeadingWhitespace(currentLineText);
}
// idealIndentForNextLine doesn't equal globalIndent when there is a line matching `indentNextLinePattern`.
let idealIndentForNextLine: string = globalIndent;
if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
globalIndent = shiftIndent(globalIndent);
}
else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
}
startLineNumber++;
// Calculate indentation adjustment for all following lines
for (let lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) {
const text = model.getLineContent(lineNumber);
const oldIndentation = strings.getLeadingWhitespace(text);
const adjustedLineContent = idealIndentForNextLine + text.substring(oldIndentation.length);
if (indentationRules.decreaseIndentPattern && indentationRules.decreaseIndentPattern.test(adjustedLineContent)) {
idealIndentForNextLine = unshiftIndent(idealIndentForNextLine);
globalIndent = unshiftIndent(globalIndent);
}
if (oldIndentation !== idealIndentForNextLine) {
indentEdits.push(EditOperation.replaceMove(new Selection(lineNumber, 1, lineNumber, oldIndentation.length + 1), normalizeIndentation(idealIndentForNextLine, indentSize, insertSpaces)));
}
// calculate idealIndentForNextLine
if (indentationRules.unIndentedLinePattern && indentationRules.unIndentedLinePattern.test(text)) {
// In reindent phase, if the line matches `unIndentedLinePattern` we inherit indentation from above lines
// but don't change globalIndent and idealIndentForNextLine.
continue;
} else if (indentationRules.increaseIndentPattern && indentationRules.increaseIndentPattern.test(adjustedLineContent)) {
globalIndent = shiftIndent(globalIndent);
idealIndentForNextLine = globalIndent;
} else if (indentationRules.indentNextLinePattern && indentationRules.indentNextLinePattern.test(adjustedLineContent)) {
idealIndentForNextLine = shiftIndent(idealIndentForNextLine);
} else {
idealIndentForNextLine = globalIndent;
}
}
return indentEdits;
}
export class IndentationToSpacesAction extends EditorAction {
public static readonly ID = 'editor.action.indentationToSpaces';
constructor() {
super({
id: IndentationToSpacesAction.ID,
label: nls.localize('indentationToSpaces', "Convert Indentation to Spaces"),
alias: 'Convert Indentation to Spaces',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const model = editor.getModel();
if (!model) {
return;
}
const modelOpts = model.getOptions();
const selection = editor.getSelection();
if (!selection) {
return;
}
const command = new IndentationToSpacesCommand(selection, modelOpts.tabSize);
editor.pushUndoStop();
editor.executeCommands(this.id, [command]);
editor.pushUndoStop();
model.updateOptions({
insertSpaces: true
});
}
}
export class IndentationToTabsAction extends EditorAction {
public static readonly ID = 'editor.action.indentationToTabs';
constructor() {
super({
id: IndentationToTabsAction.ID,
label: nls.localize('indentationToTabs', "Convert Indentation to Tabs"),
alias: 'Convert Indentation to Tabs',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const model = editor.getModel();
if (!model) {
return;
}
const modelOpts = model.getOptions();
const selection = editor.getSelection();
if (!selection) {
return;
}
const command = new IndentationToTabsCommand(selection, modelOpts.tabSize);
editor.pushUndoStop();
editor.executeCommands(this.id, [command]);
editor.pushUndoStop();
model.updateOptions({
insertSpaces: false
});
}
}
export class ChangeIndentationSizeAction extends EditorAction {
constructor(private readonly insertSpaces: boolean, private readonly displaySizeOnly: boolean, opts: IActionOptions) {
super(opts);
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const quickInputService = accessor.get(IQuickInputService);
const modelService = accessor.get(IModelService);
const model = editor.getModel();
if (!model) {
return;
}
const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
const modelOpts = model.getOptions();
const picks = [1, 2, 3, 4, 5, 6, 7, 8].map(n => ({
id: n.toString(),
label: n.toString(),
// add description for tabSize value set in the configuration
description: (
n === creationOpts.tabSize && n === modelOpts.tabSize
? nls.localize('configuredTabSize', "Configured Tab Size")
: n === creationOpts.tabSize
? nls.localize('defaultTabSize', "Default Tab Size")
: n === modelOpts.tabSize
? nls.localize('currentTabSize', "Current Tab Size")
: undefined
)
}));
// auto focus the tabSize set for the current editor
const autoFocusIndex = Math.min(model.getOptions().tabSize - 1, 7);
setTimeout(() => {
quickInputService.pick(picks, { placeHolder: nls.localize({ key: 'selectTabWidth', comment: ['Tab corresponds to the tab key'] }, "Select Tab Size for Current File"), activeItem: picks[autoFocusIndex] }).then(pick => {
if (pick) {
if (model && !model.isDisposed()) {
const pickedVal = parseInt(pick.label, 10);
if (this.displaySizeOnly) {
model.updateOptions({
tabSize: pickedVal
});
} else {
model.updateOptions({
tabSize: pickedVal,
indentSize: pickedVal,
insertSpaces: this.insertSpaces
});
}
}
}
});
}, 50/* quick input is sensitive to being opened so soon after another */);
}
}
export class IndentUsingTabs extends ChangeIndentationSizeAction {
public static readonly ID = 'editor.action.indentUsingTabs';
constructor() {
super(false, false, {
id: IndentUsingTabs.ID,
label: nls.localize('indentUsingTabs', "Indent Using Tabs"),
alias: 'Indent Using Tabs',
precondition: undefined
});
}
}
export class IndentUsingSpaces extends ChangeIndentationSizeAction {
public static readonly ID = 'editor.action.indentUsingSpaces';
constructor() {
super(true, false, {
id: IndentUsingSpaces.ID,
label: nls.localize('indentUsingSpaces', "Indent Using Spaces"),
alias: 'Indent Using Spaces',
precondition: undefined
});
}
}
export class ChangeTabDisplaySize extends ChangeIndentationSizeAction {
public static readonly ID = 'editor.action.changeTabDisplaySize';
constructor() {
super(true, true, {
id: ChangeTabDisplaySize.ID,
label: nls.localize('changeTabDisplaySize', "Change Tab Display Size"),
alias: 'Change Tab Display Size',
precondition: undefined
});
}
}
export class DetectIndentation extends EditorAction {
public static readonly ID = 'editor.action.detectIndentation';
constructor() {
super({
id: DetectIndentation.ID,
label: nls.localize('detectIndentation', "Detect Indentation from Content"),
alias: 'Detect Indentation from Content',
precondition: undefined
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const modelService = accessor.get(IModelService);
const model = editor.getModel();
if (!model) {
return;
}
const creationOpts = modelService.getCreationOptions(model.getLanguageId(), model.uri, model.isForSimpleWidget);
model.detectIndentation(creationOpts.insertSpaces, creationOpts.tabSize);
}
}
export class ReindentLinesAction extends EditorAction {
constructor() {
super({
id: 'editor.action.reindentlines',
label: nls.localize('editor.reindentlines', "Reindent Lines"),
alias: 'Reindent Lines',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const languageConfigurationService = accessor.get(ILanguageConfigurationService);
const model = editor.getModel();
if (!model) {
return;
}
const edits = getReindentEditOperations(model, languageConfigurationService, 1, model.getLineCount());
if (edits.length > 0) {
editor.pushUndoStop();
editor.executeEdits(this.id, edits);
editor.pushUndoStop();
}
}
}
export class ReindentSelectedLinesAction extends EditorAction {
constructor() {
super({
id: 'editor.action.reindentselectedlines',
label: nls.localize('editor.reindentselectedlines', "Reindent Selected Lines"),
alias: 'Reindent Selected Lines',
precondition: EditorContextKeys.writable
});
}
public run(accessor: ServicesAccessor, editor: ICodeEditor): void {
const languageConfigurationService = accessor.get(ILanguageConfigurationService);
const model = editor.getModel();
if (!model) {
return;
}
const selections = editor.getSelections();
if (selections === null) {
return;
}
const edits: ISingleEditOperation[] = [];
for (const selection of selections) {
let startLineNumber = selection.startLineNumber;
let endLineNumber = selection.endLineNumber;
if (startLineNumber !== endLineNumber && selection.endColumn === 1) {
endLineNumber--;
}
if (startLineNumber === 1) {
if (startLineNumber === endLineNumber) {
continue;
}
} else {
startLineNumber--;
}
const editOperations = getReindentEditOperations(model, languageConfigurationService, startLineNumber, endLineNumber);
edits.push(...editOperations);
}
if (edits.length > 0) {
editor.pushUndoStop();
editor.executeEdits(this.id, edits);
editor.pushUndoStop();
}
}
}
export class AutoIndentOnPasteCommand implements ICommand {
private readonly _edits: { range: IRange; text: string; eol?: EndOfLineSequence }[];
private readonly _initialSelection: Selection;
private _selectionId: string | null;
constructor(edits: TextEdit[], initialSelection: Selection) {
this._initialSelection = initialSelection;
this._edits = [];
this._selectionId = null;
for (const edit of edits) {
if (edit.range && typeof edit.text === 'string') {
this._edits.push(edit as { range: IRange; text: string; eol?: EndOfLineSequence });
}
}
}
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
for (const edit of this._edits) {
builder.addEditOperation(Range.lift(edit.range), edit.text);
}
let selectionIsSet = false;
if (Array.isArray(this._edits) && this._edits.length === 1 && this._initialSelection.isEmpty()) {
if (this._edits[0].range.startColumn === this._initialSelection.endColumn &&
this._edits[0].range.startLineNumber === this._initialSelection.endLineNumber) {
selectionIsSet = true;
this._selectionId = builder.trackSelection(this._initialSelection, true);
} else if (this._edits[0].range.endColumn === this._initialSelection.startColumn &&
this._edits[0].range.endLineNumber === this._initialSelection.startLineNumber) {
selectionIsSet = true;
this._selectionId = builder.trackSelection(this._initialSelection, false);
}
}
if (!selectionIsSet) {
this._selectionId = builder.trackSelection(this._initialSelection);
}
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this._selectionId!);
}
}
export class AutoIndentOnPaste implements IEditorContribution {
public static readonly ID = 'editor.contrib.autoIndentOnPaste';
private readonly callOnDispose = new DisposableStore();
private readonly callOnModel = new DisposableStore();
constructor(
private readonly editor: ICodeEditor,
@ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService
) {
this.callOnDispose.add(editor.onDidChangeConfiguration(() => this.update()));
this.callOnDispose.add(editor.onDidChangeModel(() => this.update()));
this.callOnDispose.add(editor.onDidChangeModelLanguage(() => this.update()));
}
private update(): void {
// clean up
this.callOnModel.clear();
// we are disabled
if (this.editor.getOption(EditorOption.autoIndent) < EditorAutoIndentStrategy.Full || this.editor.getOption(EditorOption.formatOnPaste)) {
return;
}
// no model
if (!this.editor.hasModel()) {
return;
}
this.callOnModel.add(this.editor.onDidPaste(({ range }) => {
this.trigger(range);
}));
}
public trigger(range: Range): void {
const selections = this.editor.getSelections();
if (selections === null || selections.length > 1) {
return;
}
const model = this.editor.getModel();
if (!model) {
return;
}
if (!model.tokenization.isCheapToTokenize(range.getStartPosition().lineNumber)) {
return;
}
const autoIndent = this.editor.getOption(EditorOption.autoIndent);
const { tabSize, indentSize, insertSpaces } = model.getOptions();
const textEdits: TextEdit[] = [];
const indentConverter = {
shiftIndent: (indentation: string) => {
return ShiftCommand.shiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
},
unshiftIndent: (indentation: string) => {
return ShiftCommand.unshiftIndent(indentation, indentation.length + 1, tabSize, indentSize, insertSpaces);
}
};
let startLineNumber = range.startLineNumber;
while (startLineNumber <= range.endLineNumber) {
if (this.shouldIgnoreLine(model, startLineNumber)) {
startLineNumber++;
continue;
}
break;
}
if (startLineNumber > range.endLineNumber) {
return;
}
let firstLineText = model.getLineContent(startLineNumber);
if (!/\S/.test(firstLineText.substring(0, range.startColumn - 1))) {
const indentOfFirstLine = getGoodIndentForLine(autoIndent, model, model.getLanguageId(), startLineNumber, indentConverter, this._languageConfigurationService);
if (indentOfFirstLine !== null) {
const oldIndentation = strings.getLeadingWhitespace(firstLineText);
const newSpaceCnt = indentUtils.getSpaceCnt(indentOfFirstLine, tabSize);
const oldSpaceCnt = indentUtils.getSpaceCnt(oldIndentation, tabSize);
if (newSpaceCnt !== oldSpaceCnt) {
const newIndent = indentUtils.generateIndent(newSpaceCnt, tabSize, insertSpaces);
textEdits.push({
range: new Range(startLineNumber, 1, startLineNumber, oldIndentation.length + 1),
text: newIndent
});
firstLineText = newIndent + firstLineText.substr(oldIndentation.length);
} else {
const indentMetadata = getIndentMetadata(model, startLineNumber, this._languageConfigurationService);
if (indentMetadata === 0 || indentMetadata === IndentConsts.UNINDENT_MASK) {
// we paste content into a line where only contains whitespaces
// after pasting, the indentation of the first line is already correct
// the first line doesn't match any indentation rule
// then no-op.
return;
}
}
}
}
const firstLineNumber = startLineNumber;
// ignore empty or ignored lines
while (startLineNumber < range.endLineNumber) {
if (!/\S/.test(model.getLineContent(startLineNumber + 1))) {
startLineNumber++;
continue;
}
break;
}
if (startLineNumber !== range.endLineNumber) {
const virtualModel = {
tokenization: {
getLineTokens: (lineNumber: number) => {
return model.tokenization.getLineTokens(lineNumber);
},
getLanguageId: () => {
return model.getLanguageId();
},
getLanguageIdAtPosition: (lineNumber: number, column: number) => {
return model.getLanguageIdAtPosition(lineNumber, column);
},
},
getLineContent: (lineNumber: number) => {
if (lineNumber === firstLineNumber) {
return firstLineText;
} else {
return model.getLineContent(lineNumber);
}
}
};
const indentOfSecondLine = getGoodIndentForLine(autoIndent, virtualModel, model.getLanguageId(), startLineNumber + 1, indentConverter, this._languageConfigurationService);
if (indentOfSecondLine !== null) {
const newSpaceCntOfSecondLine = indentUtils.getSpaceCnt(indentOfSecondLine, tabSize);
const oldSpaceCntOfSecondLine = indentUtils.getSpaceCnt(strings.getLeadingWhitespace(model.getLineContent(startLineNumber + 1)), tabSize);
if (newSpaceCntOfSecondLine !== oldSpaceCntOfSecondLine) {
const spaceCntOffset = newSpaceCntOfSecondLine - oldSpaceCntOfSecondLine;
for (let i = startLineNumber + 1; i <= range.endLineNumber; i++) {
const lineContent = model.getLineContent(i);
const originalIndent = strings.getLeadingWhitespace(lineContent);
const originalSpacesCnt = indentUtils.getSpaceCnt(originalIndent, tabSize);
const newSpacesCnt = originalSpacesCnt + spaceCntOffset;
const newIndent = indentUtils.generateIndent(newSpacesCnt, tabSize, insertSpaces);
if (newIndent !== originalIndent) {
textEdits.push({
range: new Range(i, 1, i, originalIndent.length + 1),
text: newIndent
});
}
}
}
}
}
if (textEdits.length > 0) {
this.editor.pushUndoStop();
const cmd = new AutoIndentOnPasteCommand(textEdits, this.editor.getSelection()!);
this.editor.executeCommand('autoIndentOnPaste', cmd);
this.editor.pushUndoStop();
}
}
private shouldIgnoreLine(model: ITextModel, lineNumber: number): boolean {
model.tokenization.forceTokenization(lineNumber);
const nonWhitespaceColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
if (nonWhitespaceColumn === 0) {
return true;
}
const tokens = model.tokenization.getLineTokens(lineNumber);
if (tokens.getCount() > 0) {
const firstNonWhitespaceTokenIndex = tokens.findTokenIndexAtOffset(nonWhitespaceColumn);
if (firstNonWhitespaceTokenIndex >= 0 && tokens.getStandardTokenType(firstNonWhitespaceTokenIndex) === StandardTokenType.Comment) {
return true;
}
}
return false;
}
public dispose(): void {
this.callOnDispose.dispose();
this.callOnModel.dispose();
}
}
function getIndentationEditOperations(model: ITextModel, builder: IEditOperationBuilder, tabSize: number, tabsToSpaces: boolean): void {
if (model.getLineCount() === 1 && model.getLineMaxColumn(1) === 1) {
// Model is empty
return;
}
let spaces = '';
for (let i = 0; i < tabSize; i++) {
spaces += ' ';
}
const spacesRegExp = new RegExp(spaces, 'gi');
for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) {
let lastIndentationColumn = model.getLineFirstNonWhitespaceColumn(lineNumber);
if (lastIndentationColumn === 0) {
lastIndentationColumn = model.getLineMaxColumn(lineNumber);
}
if (lastIndentationColumn === 1) {
continue;
}
const originalIndentationRange = new Range(lineNumber, 1, lineNumber, lastIndentationColumn);
const originalIndentation = model.getValueInRange(originalIndentationRange);
const newIndentation = (
tabsToSpaces
? originalIndentation.replace(/\t/ig, spaces)
: originalIndentation.replace(spacesRegExp, '\t')
);
builder.addEditOperation(originalIndentationRange, newIndentation);
}
}
export class IndentationToSpacesCommand implements ICommand {
private selectionId: string | null = null;
constructor(private readonly selection: Selection, private tabSize: number) { }
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
this.selectionId = builder.trackSelection(this.selection);
getIndentationEditOperations(model, builder, this.tabSize, true);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this.selectionId!);
}
}
export class IndentationToTabsCommand implements ICommand {
private selectionId: string | null = null;
constructor(private readonly selection: Selection, private tabSize: number) { }
public getEditOperations(model: ITextModel, builder: IEditOperationBuilder): void {
this.selectionId = builder.trackSelection(this.selection);
getIndentationEditOperations(model, builder, this.tabSize, false);
}
public computeCursorState(model: ITextModel, helper: ICursorStateComputerData): Selection {
return helper.getTrackedSelection(this.selectionId!);
}
}
registerEditorContribution(AutoIndentOnPaste.ID, AutoIndentOnPaste, EditorContributionInstantiation.BeforeFirstInteraction);
registerEditorAction(IndentationToSpacesAction);
registerEditorAction(IndentationToTabsAction);
registerEditorAction(IndentUsingTabs);
registerEditorAction(IndentUsingSpaces);
registerEditorAction(ChangeTabDisplaySize);
registerEditorAction(DetectIndentation);
registerEditorAction(ReindentLinesAction);
registerEditorAction(ReindentSelectedLinesAction);