Skip to content

Commit e86a49e

Browse files
committed
Merge pull request #815 from lordmat0/auto_format_on_save
Auto format on save
2 parents 8becb8e + 0e012b9 commit e86a49e

File tree

7 files changed

+50
-24
lines changed

7 files changed

+50
-24
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ JavaScript developers can now just open a `.ts` file and start hacking away like
3131
* Project Build Support
3232
* `package.json` Support
3333
* React Support
34-
* Format code
34+
* Format code (configurable to be on save)
3535
* Goto Declaration
3636
* Find References
3737
* Block comment and uncomment
@@ -107,6 +107,8 @@ Covered here : http://basarat.gitbooks.io/typescript/content/docs/jsx/tsx.html
107107
## Format Code
108108
Shortcut : `ctrl+alt+l` or `cmd+alt+l`. Will format just the selection if you have something selected otherwise it will format the entire file.
109109

110+
Format on save is covered [here](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#formatOnSave)
111+
110112
## Go to Declaration
111113
Shortcut : `F12`. Will open the *first* declaration of the said item for now. (Note: some people call it Go to Definition)
112114

dist/main/atom/onSaveHandler.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,9 @@ function handle(event) {
2727
if (fileDetails.project.buildOnSave) {
2828
atom.commands.dispatch(atom.views.getView(event.editor), 'typescript:build');
2929
}
30+
if (fileDetails.project.atom.formatOnSave) {
31+
atom.commands.dispatch(atom.views.getView(event.editor), 'typescript:format-code');
32+
}
3033
});
3134
}
3235
exports.handle = handle;

dist/main/tsconfig/tsconfig.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ function getDefaultInMemoryProject(srcFile) {
181181
compileOnSave: true,
182182
buildOnSave: false,
183183
scripts: {},
184-
atom: { rewriteTsconfig: true },
184+
atom: { rewriteTsconfig: true, formatOnSave: false },
185185
};
186186
return {
187187
projectFileDirectory: dir,
@@ -253,7 +253,7 @@ function getProjectSync(pathOrSrcFile) {
253253
externalTranspiler: projectSpec.externalTranspiler == undefined ? undefined : projectSpec.externalTranspiler,
254254
scripts: projectSpec.scripts || {},
255255
buildOnSave: !!projectSpec.buildOnSave,
256-
atom: { rewriteTsconfig: true }
256+
atom: { rewriteTsconfig: true, formatOnSave: !!projectSpec.atom.formatOnSave }
257257
};
258258
var validationResult = validator.validate(projectSpec.compilerOptions);
259259
if (validationResult.errorMessage) {

docs/tsconfig.md

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ i.e. an empty JSON file at the *root* of your project :heart: This will be suffi
2020
* [`compileOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#compileonsave) : Should AtomTS compile on save
2121
* [`buildOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#buildonsave) : Should AtomTS build on save
2222
* [`scripts`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#scripts) : Sometimes its useful to have post build scripts
23-
* [`atom`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#rewriteTsconfig) : Configuration specific to Atom. Currently
24-
only contains `rewriteTsconfig` which prevents Atom from rewriting a project's `tsconfig.json`.
23+
* [`atom`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#atom) : Configuration specific to Atom.
24+
* [`rewriteTsconfig`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#rewriteTsconfig) which prevents Atom from rewriting a project's `tsconfig.json`
25+
* [`formatOnSave`](https://github.com/TypeStrong/atom-typescript/blob/master/docs/tsconfig.md#formatOnSave) which will format the Typescript file on save.
2526

2627
## Examples
2728

@@ -134,5 +135,17 @@ to `false` (this defaults to `true`).
134135
}
135136
```
136137

138+
**formatOnSave**
139+
140+
Setting this to `true` will format the entire file exactly like `ctrl+alt+l` or `cmd+alt+l` does on save. (this defaults to `false`)
141+
142+
```json
143+
{
144+
"atom": {
145+
"formatOnSave": true
146+
}
147+
}
148+
```
149+
137150
## Additional Notes
138151
FWIW [a json schema is also available](http://json.schemastore.org/tsconfig)

lib/main/atom/onSaveHandler.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,12 @@ export function handle(event: { filePath: string; editor: AtomCore.IEditor }) {
5353
'typescript:build');
5454
}
5555

56+
if (fileDetails.project.atom.formatOnSave) {
57+
// Trigger a format
58+
atom.commands.dispatch(
59+
atom.views.getView(event.editor),
60+
'typescript:format-code');
61+
}
62+
5663
});
5764
}

lib/main/tsconfig/tsconfig.ts

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ interface TypeScriptProjectRawSpecification {
139139
buildOnSave?: boolean;
140140
externalTranspiler?: string | { name: string; options?: any };
141141
scripts?: { postbuild?: string };
142-
atom?: { rewriteTsconfig?: boolean };
142+
atom?: { rewriteTsconfig?: boolean, formatOnSave?: boolean };
143143
}
144144

145145
/**
@@ -157,7 +157,7 @@ export interface TypeScriptProjectSpecification {
157157
package?: UsefulFromPackageJson;
158158
externalTranspiler?: string | { name: string; options?: any };
159159
scripts: { postbuild?: string };
160-
atom: { rewriteTsconfig: boolean };
160+
atom: { rewriteTsconfig: boolean, formatOnSave: boolean };
161161
}
162162

163163
///////// FOR USE WITH THE API /////////////
@@ -290,7 +290,7 @@ function mixin(target: any, source: any): any {
290290

291291
function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string): ts.CompilerOptions {
292292
// Cannot use Object.create because the compiler checks hasOwnProperty
293-
var compilerOptions = <ts.CompilerOptions> mixin({}, defaults);
293+
var compilerOptions = <ts.CompilerOptions>mixin({}, defaults);
294294
for (var key in jsonOptions) {
295295
if (typescriptEnumMap[key]) {
296296
compilerOptions[key] = typescriptEnumMap[key][jsonOptions[key].toLowerCase()];
@@ -322,7 +322,7 @@ function rawToTsCompilerOptions(jsonOptions: CompilerOptions, projectDir: string
322322

323323
function tsToRawCompilerOptions(compilerOptions: ts.CompilerOptions): CompilerOptions {
324324
// Cannot use Object.create because JSON.stringify will only serialize own properties
325-
var jsonOptions = <CompilerOptions> mixin({}, compilerOptions);
325+
var jsonOptions = <CompilerOptions>mixin({}, compilerOptions);
326326

327327
Object.keys(compilerOptions).forEach((key) => {
328328
if (jsonEnumMap[key] && compilerOptions[key]) {
@@ -350,7 +350,7 @@ export function getDefaultInMemoryProject(srcFile: string): TypeScriptProjectFil
350350
compileOnSave: true,
351351
buildOnSave: false,
352352
scripts: {},
353-
atom: { rewriteTsconfig: true },
353+
atom: { rewriteTsconfig: true, formatOnSave: false },
354354
};
355355

356356
return {
@@ -375,8 +375,8 @@ export function getProjectSync(pathOrSrcFile: string): TypeScriptProjectFileDeta
375375
var projectFile = tsconfig.resolveSync(dir);
376376

377377
if (!projectFile) {
378-
throw errorWithDetails<GET_PROJECT_NO_PROJECT_FOUND_Details>(
379-
new Error(errors.GET_PROJECT_NO_PROJECT_FOUND), { projectFilePath: fsu.consistentPath(pathOrSrcFile), errorMessage: 'not found' });
378+
throw errorWithDetails<GET_PROJECT_NO_PROJECT_FOUND_Details>(
379+
new Error(errors.GET_PROJECT_NO_PROJECT_FOUND), { projectFilePath: fsu.consistentPath(pathOrSrcFile), errorMessage: 'not found' });
380380
}
381381

382382
var projectFileDirectory = path.dirname(projectFile) + path.sep;
@@ -442,7 +442,7 @@ export function getProjectSync(pathOrSrcFile: string): TypeScriptProjectFileDeta
442442
externalTranspiler: projectSpec.externalTranspiler == undefined ? undefined : projectSpec.externalTranspiler,
443443
scripts: projectSpec.scripts || {},
444444
buildOnSave: !!projectSpec.buildOnSave,
445-
atom: { rewriteTsconfig: true }
445+
atom: { rewriteTsconfig: true, formatOnSave: !!projectSpec.atom.formatOnSave }
446446
};
447447

448448
// Validate the raw compiler options before converting them to TS compiler options
@@ -521,7 +521,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
521521
}
522522
}
523523

524-
var getReferencedOrImportedFiles = (files: string[]): string[]=> {
524+
var getReferencedOrImportedFiles = (files: string[]): string[] => {
525525
var referenced: string[][] = [];
526526

527527
files.forEach(file => {
@@ -553,7 +553,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
553553
return file;
554554
}
555555
return getIfExists(file);
556-
}).filter(file=> !!file)
556+
}).filter(file => !!file)
557557
.concat(
558558
preProcessedFileInfo.importedFiles
559559
.filter((fileReference) => pathIsRelative(fileReference.fileName))
@@ -564,7 +564,7 @@ function increaseProjectForReferenceAndImports(files: string[]): string[] {
564564
file = getIfExists(`${file}/index`);
565565
}
566566
return file;
567-
}).filter(file=> !!file)
567+
}).filter(file => !!file)
568568
)
569569
);
570570
});
@@ -610,9 +610,9 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
610610
// Find our `typings` (anything in a typings folder with extension `.d.ts` is considered a typing)
611611
// These are INF powerful
612612
var ourTypings = files
613-
.filter(f=> path.basename(path.dirname(f)) == 'typings' && endsWith(f, '.d.ts')
613+
.filter(f => path.basename(path.dirname(f)) == 'typings' && endsWith(f, '.d.ts')
614614
|| path.basename(path.dirname(path.dirname(f))) == 'typings' && endsWith(f, '.d.ts'));
615-
ourTypings.forEach(f=> typings[path.basename(f)] = { filePath: f, version: Infinity });
615+
ourTypings.forEach(f => typings[path.basename(f)] = { filePath: f, version: Infinity });
616616
var existing = createMap(files.map(fsu.consistentPath));
617617

618618
function addAllReferencedFilesWithMaxVersion(file: string) {
@@ -635,7 +635,7 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
635635
if (fs.existsSync(file + '.d.ts')) {
636636
return file + '.d.ts';
637637
}
638-
}).filter(f=> !!f);
638+
}).filter(f => !!f);
639639

640640
// Only ones we don't have by name yet
641641
// TODO: replace INF with an actual version
@@ -644,7 +644,7 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
644644
// Add these
645645
files.forEach(f => typings[path.basename(f)] = { filePath: f, version: Infinity });
646646
// Keep expanding
647-
files.forEach(f=> addAllReferencedFilesWithMaxVersion(f));
647+
files.forEach(f => addAllReferencedFilesWithMaxVersion(f));
648648
}
649649

650650
// Keep going up till we find node_modules
@@ -691,11 +691,11 @@ function getDefinitionsForNodeModules(projectDir: string, files: string[]): { ou
691691

692692
var all = Object.keys(typings)
693693
.map(typing => typings[typing].filePath)
694-
.map(x=> fsu.consistentPath(x));
694+
.map(x => fsu.consistentPath(x));
695695
var implicit = all
696-
.filter(x=> !existing[x]);
696+
.filter(x => !existing[x]);
697697
var ours = all
698-
.filter(x=> existing[x]);
698+
.filter(x => existing[x]);
699699

700700
return { implicit, ours, packagejson };
701701
}

lib/tsconfig.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@
134134
],
135135
"exclude": [],
136136
"atom": {
137-
"rewriteTsconfig": true
137+
"rewriteTsconfig": true,
138+
"formatOnSave": false
138139
}
139140
}

0 commit comments

Comments
 (0)