Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format on save #12454

Merged
merged 5 commits into from
Sep 23, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 119 additions & 41 deletions src/vs/workbench/api/node/mainThreadSaveParticipant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,33 @@

'use strict';

import {IDisposable, dispose} from 'vs/base/common/lifecycle';
import {TPromise} from 'vs/base/common/winjs.base';
import {sequence} from 'vs/base/common/async';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {IThreadService} from 'vs/workbench/services/thread/common/threadService';
import {ISaveParticipant, ITextFileEditorModel} from 'vs/workbench/parts/files/common/files';
import {IFilesConfiguration} from 'vs/platform/files/common/files';
import {IPosition, IModel} from 'vs/editor/common/editorCommon';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IPosition, IModel, ICommonCodeEditor, ISingleEditOperation} from 'vs/editor/common/editorCommon';
import {Range} from 'vs/editor/common/core/range';
import {Selection} from 'vs/editor/common/core/selection';
import {trimTrailingWhitespace} from 'vs/editor/common/commands/trimTrailingWhitespaceCommand';
import {getDocumentRangeFormattingEdits} from 'vs/editor/contrib/format/common/format';
import {EditOperationsCommand} from 'vs/editor/contrib/format/common/formatCommand';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {TextFileEditorModel} from 'vs/workbench/parts/files/common/editors/textFileEditorModel';
import {ExtHostContext, ExtHostDocumentSaveParticipantShape} from './extHost.protocol';

// TODO@joh move this to the extension host
class TrimWhitespaceParticipant {

private trimTrailingWhitespace: boolean = false;
private toUnbind: IDisposable[] = [];
class TrimWhitespaceParticipant implements ISaveParticipant {

constructor(
@IConfigurationService private configurationService: IConfigurationService,
@ICodeEditorService private codeEditorService: ICodeEditorService
) {
this.registerListeners();
this.onConfigurationChange(this.configurationService.getConfiguration<IFilesConfiguration>());
}

public dispose(): void {
this.toUnbind = dispose(this.toUnbind);
}

private registerListeners(): void {
this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config)));
}

private onConfigurationChange(configuration: IFilesConfiguration): void {
this.trimTrailingWhitespace = configuration && configuration.files && configuration.files.trimTrailingWhitespace;
// Nothing
}

public participate(model: ITextFileEditorModel, env: { isAutoSaved: boolean }): any {
if (this.trimTrailingWhitespace) {
if (this.configurationService.lookup('files.trimTrailingWhitespace').value) {
this.doTrimTrailingWhitespace(model.textEditorModel, env.isAutoSaved);
}
}
Expand Down Expand Up @@ -89,34 +75,126 @@ class TrimWhitespaceParticipant {
}
}

class FormatOnSaveParticipant implements ISaveParticipant {

constructor(
@ICodeEditorService private _editorService: ICodeEditorService,
@IConfigurationService private _configurationService: IConfigurationService
) {
// Nothing
}

participate(editorModel: ITextFileEditorModel, env: { isAutoSaved: boolean }): TPromise<any> {

if (!this._configurationService.lookup('files.formatOnSave').value) {
return;
}

const model: IModel = editorModel.textEditorModel;
const editor = this._findEditor(model);
const {tabSize, insertSpaces} = model.getOptions();

return getDocumentRangeFormattingEdits(model, model.getFullModelRange(), { tabSize, insertSpaces }).then(edits => {
if (edits) {
if (editor) {
this._editsWithEditor(editor, edits, env.isAutoSaved);
} else {
this._editWithModel(model, edits);
}
}
});
}

private _editsWithEditor(editor: ICommonCodeEditor, edits: ISingleEditOperation[], isAutoSaved: boolean): void {

if (isAutoSaved && editor.isFocused()) {
// when we save an focus (active) editor we check if
// formatting edits intersect with any cursor. iff so
// we ignore this

let intersectsCursor = false;
outer: for (const selection of editor.getSelections()) {
for (const {range} of edits) {
if (Range.areIntersectingOrTouching(range, selection)) {
intersectsCursor = true;
break outer;
}
}
}
if (intersectsCursor) {
return;
}
}

editor.executeCommand('files.formatOnSave', new EditOperationsCommand(edits, editor.getSelection()));
}

private _editWithModel(model: IModel, edits: ISingleEditOperation[]): void {
model.applyEdits(edits.map(({text, range}) => ({
text,
range: Range.lift(range),
identifier: undefined,
forceMoveMarkers: true
})));
}

private _findEditor(model: IModel) {
if (!model.isAttachedToEditor()) {
return;
}

let candidate: ICommonCodeEditor;
for (const editor of this._editorService.listCodeEditors()) {
if (editor.getModel() === model) {
if (editor.isFocused()) {
return editor;
} else {
candidate = editor;
}
}
}
return candidate;
}
}

class ExtHostSaveParticipant implements ISaveParticipant {

private _proxy: ExtHostDocumentSaveParticipantShape;

constructor( @IThreadService threadService: IThreadService) {
this._proxy = threadService.get(ExtHostContext.ExtHostDocumentSaveParticipant);
}

participate(editorModel: ITextFileEditorModel, env: { isAutoSaved: boolean }): TPromise<any> {
return this._proxy.$participateInSave(editorModel.getResource());
}
}

// The save participant can change a model before its saved to support various scenarios like trimming trailing whitespace
export class SaveParticipant implements ISaveParticipant {

private _mainThreadSaveParticipant: TrimWhitespaceParticipant;
private _extHostSaveParticipant: ExtHostDocumentSaveParticipantShape;
private _saveParticipants: ISaveParticipant[];

constructor(
@IConfigurationService configurationService: IConfigurationService,
@ICodeEditorService codeEditorService: ICodeEditorService,
@IInstantiationService instantiationService: IInstantiationService,
@IThreadService threadService: IThreadService
) {
this._mainThreadSaveParticipant = new TrimWhitespaceParticipant(configurationService, codeEditorService);
this._extHostSaveParticipant = threadService.get(ExtHostContext.ExtHostDocumentSaveParticipant);

this._saveParticipants = [
instantiationService.createInstance(TrimWhitespaceParticipant),
instantiationService.createInstance(FormatOnSaveParticipant),
instantiationService.createInstance(ExtHostSaveParticipant)
];

// Hook into model
TextFileEditorModel.setSaveParticipant(this);
}

dispose() {
this._mainThreadSaveParticipant.dispose();
}

participate(model: ITextFileEditorModel, env: { isAutoSaved: boolean }): TPromise<any> {
try {
this._mainThreadSaveParticipant.participate(model, env);
} catch (err) {
// ignore
}
return this._extHostSaveParticipant.$participateInSave(model.getResource());
const promiseFactory = this._saveParticipants.map(p => () => {
return TPromise.as(p.participate(model, env)).then(undefined, err => {
// console.error(err);
});
});
return sequence(promiseFactory);
}
}
}
5 changes: 5 additions & 0 deletions src/vs/workbench/parts/files/browser/files.contribution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,11 @@ configurationRegistry.registerConfiguration({
'default': false,
'description': nls.localize('trimTrailingWhitespace', "When enabled, will trim trailing whitespace when you save a file.")
},
'files.formatOnSave': {
'type': 'boolean',
'default': false,
'description': nls.localize('formatOnSave', "Format a file on save - a matching formatting provider must be available.")
},
'files.autoSave': {
'type': 'string',
'enum': [AutoSaveConfiguration.OFF, AutoSaveConfiguration.AFTER_DELAY, AutoSaveConfiguration.ON_FOCUS_CHANGE, , AutoSaveConfiguration.ON_WINDOW_CHANGE],
Expand Down