diff --git a/package.json b/package.json index 1d2383be7..8eaa500db 100644 --- a/package.json +++ b/package.json @@ -284,6 +284,12 @@ } } } + }, + "ruby.format": { + "type": [ "boolean", "string" ], + "enum": [ false, "rubocop" ], + "default": false, + "description": "Which system to use for formatting, or false for no formatting" } } }, diff --git a/readme.md b/readme.md index c21eec908..51dbe51b1 100644 --- a/readme.md +++ b/readme.md @@ -136,8 +136,20 @@ Settings available (in your VSCode workspace) for each of the linters: ``` ## Formatting +The VS Code Ruby extension can automatically format your Ruby files whenever you save. + +### Rubocop + +Set `ruby.format` to `rubocop` to enable rubocop formatting on save. + Formatting requires the rubocop gem to be installed. Note that you may have to turn on some of the AutoCorrect functions in your `.rubocop.yml` file. See the [rubocop documentation](http://rubocop.readthedocs.io/en/latest/configuration/). +Important note: VS Code has a timeout that limits file formatters to 750ms. This is often not enough time for rubocop to complete. In the near future VS Code will allow customizing this timeout via the `editor.formatOnSaveTimeout` setting. See [#43702](https://github.com/Microsoft/vscode/pull/43702) for more details. + +### Rufo + +Rufo is an alternative Ruby formatting tool. See the [VS Code Rufo Extension](https://github.com/bessey/vscode-rufo) if you want to try it. + ## Autocomplete The `ruby.codeCompletion` setting lets you select a method for code completion and other intellisense features. Valid options are `solargraph`, `rcodetools`, and `none`. diff --git a/src/format/rubyFormat.ts b/src/format/rubyFormat.ts index 8ef8dfaaa..5bd654f20 100644 --- a/src/format/rubyFormat.ts +++ b/src/format/rubyFormat.ts @@ -6,16 +6,18 @@ import { AutoCorrect } from './RuboCop'; export class RubyDocumentFormattingEditProvider implements vscode.DocumentFormattingEditProvider { private autoCorrect: AutoCorrect; - constructor() { - this.autoCorrect = new AutoCorrect(); - } - public register(ctx: vscode.ExtensionContext) { + // only attempt to format if ruby.format is set to rubocop + if (vscode.workspace.getConfiguration("ruby").get("format") !== "rubocop") { + return; + } + + this.autoCorrect = new AutoCorrect(); this.autoCorrect.test().then( () => ctx.subscriptions.push( vscode.languages.registerDocumentFormattingEditProvider('ruby', this) - ), - () => console.log("Rubocop not installed") + ) + // silent failure - AutoCorrect will handle error messages ); } @@ -28,7 +30,7 @@ export class RubyDocumentFormattingEditProvider implements vscode.DocumentFormat return [new vscode.TextEdit(document.validateRange(new vscode.Range(0, 0, Infinity, Infinity)), result)]; }, err => { - console.log("Failed to format:", err); + // silent failure - AutoCorrect will handle error messages return []; } );