Skip to content

Commit

Permalink
Resolve prettier against formatted file
Browse files Browse the repository at this point in the history
  • Loading branch information
CiGit committed Feb 17, 2017
1 parent a5f0d62 commit 675131d
Showing 1 changed file with 27 additions and 4 deletions.
31 changes: 27 additions & 4 deletions src/PrettierEditProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import {
TextEdit
} from 'vscode';

const prettier = require('prettier');
const path = require('path');
const Module = require('module');

interface PrettierConfig {
printWidth: number,
Expand All @@ -20,8 +21,23 @@ interface PrettierConfig {
bracketSpacing: boolean,
parser: string
}
interface Prettier {
format: (string, PrettierConfig?) => string
readonly version: string
}

function requirePrettier(fspath: string): Prettier {
const fileModule = new Module(fspath);
fileModule.paths = Module._nodeModulePaths(path.join(fspath, '..'));
try {
return fileModule.require("prettier");
} catch (e) {
// No local prettier found
}
return require("prettier");
}

function format(text: string): string {
function format(text: string, path: string): string {
const config: PrettierConfig = workspace.getConfiguration('prettier') as any;
/*
handle deprecated parser option
Expand All @@ -30,6 +46,7 @@ function format(text: string): string {
if (!parser) { // unset config
parser = config.useFlowParser ? 'flow' : 'babylon';
}
const prettier = requirePrettier(path);
let transformed: string;
try {
return prettier.format(text, {
Expand Down Expand Up @@ -60,14 +77,20 @@ class PrettierEditProvider implements
options: FormattingOptions,
token: CancellationToken
): TextEdit[] {
return [TextEdit.replace(range, format(document.getText(range)))];
return [TextEdit.replace(
range,
format(document.getText(range), document.fileName)
)];
}
provideDocumentFormattingEdits(
document: TextDocument,
options: FormattingOptions,
token: CancellationToken
): TextEdit[] {
return [TextEdit.replace(fullDocumentRange(document), format(document.getText()))];
return [TextEdit.replace(
fullDocumentRange(document),
format(document.getText(), document.fileName)
)];
}
}

Expand Down

0 comments on commit 675131d

Please sign in to comment.