Refactored option to indent with tabs (#1026)

Refactored option to indent with tabs
master
Rafael Hengles 2017-04-06 23:49:37 -03:00 committed by James Long
parent 651cce2066
commit 170e4d558a
9 changed files with 103 additions and 64 deletions

View File

@ -208,6 +208,9 @@ argument is optional, and all of the defaults are shown below:
const prettier = require("prettier");
prettier.format(source, {
// Indent lines with tabs
useTabs: false,
// Fit code within this line limit
printWidth: 80,

View File

@ -14,6 +14,7 @@ const argv = minimist(process.argv.slice(2), {
boolean: [
"write",
"stdin",
"use-tabs",
"single-quote",
"bracket-spacing",
"jsx-bracket-same-line",
@ -119,6 +120,7 @@ function getTrailingComma() {
}
const options = {
useTabs: argv["use-tabs"],
printWidth: getIntOption("print-width"),
tabWidth: getIntOption("tab-width"),
bracketSpacing: argv["bracket-spacing"],
@ -182,6 +184,7 @@ if (argv["help"] || (!filepatterns.length && !stdin)) {
" --stdin Read input from stdin.\n" +
" --print-width <int> Specify the length of line that the printer will wrap on. Defaults to 80.\n" +
" --tab-width <int> Specify the number of spaces per indentation-level. Defaults to 2.\n" +
" --use-tabs Indent lines with tabs instead of spaces. Defaults to false.\n" +
" --single-quote Use single quotes instead of double.\n" +
" --bracket-spacing Put spaces between brackets. Defaults to true.\n" +
" --jsx-bracket-same-line Put > on the last line. Defaults to false.\n" +

View File

@ -72,7 +72,8 @@ function format(text, opts) {
const ast = parse(text, opts);
const astComments = attachComments(text, ast, opts);
const doc = printAstToDoc(ast, opts);
const str = printDocToString(doc, opts.printWidth, guessLineEnding(text));
opts.newLine = guessLineEnding(text);
const str = printDocToString(doc, opts);
ensureAllCommentsPrinted(astComments);
return str;
}
@ -108,7 +109,7 @@ module.exports = {
formatAST: function(ast, opts) {
opts = normalizeOptions(opts);
const doc = printAstToDoc(ast, opts);
const str = printDocToString(doc, opts.printWidth);
const str = printDocToString(doc, opts);
return str;
},
// Doesn't handle shebang for now
@ -127,7 +128,7 @@ module.exports = {
},
printDocToString: function(doc, opts) {
opts = normalizeOptions(opts);
const str = printDocToString(doc, opts.printWidth);
const str = printDocToString(doc, opts);
return str;
}
}

View File

@ -11,6 +11,7 @@ var concat = docBuilders.concat;
var hardline = docBuilders.hardline;
var breakParent = docBuilders.breakParent;
var indent = docBuilders.indent;
var align = docBuilders.align;
var lineSuffix = docBuilders.lineSuffix;
var join = docBuilders.join;
var util = require("./util");
@ -802,7 +803,7 @@ function printDanglingComments(path, options, sameIndent) {
if (sameIndent) {
return join(hardline, parts);
}
return indent(options.tabWidth, concat([hardline, join(hardline, parts)]));
return indent(concat([hardline, join(hardline, parts)]));
}
function printComments(path, print, options) {

View File

@ -25,10 +25,16 @@ function concat(parts) {
return { type: "concat", parts };
}
function indent(n, contents) {
function indent(contents) {
assertDoc(contents);
return { type: "indent", contents, n };
return { type: "indent", contents };
}
function align(n, contents) {
assertDoc(contents);
return { type: "align", contents, n };
}
function group(contents, opts) {
@ -104,5 +110,6 @@ module.exports = {
lineSuffixBoundary,
breakParent,
ifBreak,
indent
indent,
align
};

View File

@ -67,7 +67,11 @@ function printDoc(doc) {
}
if (doc.type === "indent") {
return "indent(" + doc.n + ", " + printDoc(doc.contents) + ")";
return "indent(" + printDoc(doc.contents) + ")";
}
if (doc.type === "align") {
return "align(" + doc.n + ", " + printDoc(doc.contents) + ")";
}
if (doc.type === "if-break") {

View File

@ -3,6 +3,33 @@
const MODE_BREAK = 1;
const MODE_FLAT = 2;
function rootIndent() {
return {
indent: 0,
align: {
spaces: 0,
tabs: 0
}
};
}
function makeIndent(ind) {
return {
indent: ind.indent + 1,
align: ind.align
};
}
function makeAlign(ind, n) {
return {
indent: ind.indent,
align: {
spaces: ind.align.spaces + n,
tabs: ind.align.tabs + (n ? 1 : 0)
}
};
}
function fits(next, restCommands, width) {
let restIdx = restCommands.length;
const cmds = [next];
@ -35,7 +62,11 @@ function fits(next, restCommands, width) {
break;
case "indent":
cmds.push([ind + doc.n, mode, doc.contents]);
cmds.push([makeIndent(ind), mode, doc.contents]);
break;
case "align":
cmds.push([makeAlign(ind, doc.n), mode, doc.contents]);
break;
case "group":
@ -77,14 +108,14 @@ function fits(next, restCommands, width) {
return false;
}
function printDocToString(doc, width, newLine) {
newLine = newLine || "\n";
function printDocToString(doc, options) {
let width = options.printWidth;
let newLine = options.newLine || "\n";
let pos = 0;
// cmds is basically a stack. We've turned a recursive call into a
// while loop which is much faster. The while loop below adds new
// cmds to the array instead of recursively calling `print`.
let cmds = [[0, MODE_BREAK, doc]];
let cmds = [[rootIndent(), MODE_BREAK, doc]];
let out = [];
let shouldRemeasure = false;
let lineSuffix = [];
@ -108,7 +139,11 @@ function printDocToString(doc, width, newLine) {
break;
case "indent":
cmds.push([ind + doc.n, mode, doc.contents]);
cmds.push([makeIndent(ind), mode, doc.contents]);
break;
case "align":
cmds.push([makeAlign(ind, doc.n), mode, doc.contents]);
break;
case "group":
@ -239,8 +274,12 @@ function printDocToString(doc, width, newLine) {
);
}
out.push(newLine + " ".repeat(ind));
pos = ind;
let length = ind.indent * options.tabWidth + ind.align.spaces;
let indentString = options.useTabs
? "\t".repeat(ind.indent + ind.align.tabs)
: " ".repeat(length);
out.push(newLine + indentString);
pos = length;
}
break;
}

View File

@ -4,6 +4,7 @@ var validate = require("jest-validate").validate;
var deprecatedConfig = require("./deprecated");
var defaults = {
useTabs: false,
tabWidth: 2,
printWidth: 80,
singleQuote: false,

View File

@ -15,6 +15,7 @@ var softline = docBuilders.softline;
var literalline = docBuilders.literalline;
var group = docBuilders.group;
var indent = docBuilders.indent;
var align = docBuilders.align;
var conditionalGroup = docBuilders.conditionalGroup;
var ifBreak = docBuilders.ifBreak;
var breakParent = docBuilders.breakParent;
@ -220,7 +221,7 @@ function genericPrintNoParens(path, options, print) {
// level. The first item is guaranteed to be the first
// left-most expression.
parts.length > 0 ? parts[0] : "",
indent(options.tabWidth, rest)
indent(rest)
])
);
}
@ -327,7 +328,7 @@ function genericPrintNoParens(path, options, print) {
return group(
concat([
concat(parts),
group(indent(options.tabWidth, concat([line, body])))
group(indent(concat([line, body])))
])
);
case "MethodDefinition":
@ -478,7 +479,6 @@ function genericPrintNoParens(path, options, print) {
concat([
"{",
indent(
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
join(concat([",", line]), grouped)
@ -508,7 +508,7 @@ function genericPrintNoParens(path, options, print) {
// we want and this break would take precedence instead.
if (grouped.length === 0) {
return group(
concat([concat(parts), indent(options.tabWidth, concat(fromParts))])
concat([concat(parts), indent(concat(fromParts))])
);
}
@ -552,7 +552,6 @@ function genericPrintNoParens(path, options, print) {
function(childPath) {
parts.push(
indent(
options.tabWidth,
concat([hardline, print(childPath), ";"])
)
);
@ -562,7 +561,7 @@ function genericPrintNoParens(path, options, print) {
}
if (hasContent) {
parts.push(indent(options.tabWidth, concat([hardline, naked])));
parts.push(indent(concat([hardline, naked])));
}
parts.push(comments.printDanglingComments(path, options));
@ -579,7 +578,6 @@ function genericPrintNoParens(path, options, print) {
concat([
" (",
indent(
options.tabWidth,
concat([softline, path.call(print, "argument")])
),
line,
@ -594,7 +592,6 @@ function genericPrintNoParens(path, options, print) {
group(concat([
ifBreak(" (", " "),
indent(
options.tabWidth,
concat([softline, path.call(print, "argument")])
),
softline,
@ -716,13 +713,18 @@ function genericPrintNoParens(path, options, print) {
concat([
leftBrace,
indent(
options.tabWidth + (parentIsUnionTypeAnnotation ? 2 : 0),
concat([options.bracketSpacing ? line : softline, concat(props)])
align(
parentIsUnionTypeAnnotation ? 2 : 0,
concat([
options.bracketSpacing ? line : softline,
concat(props)
])
)
),
ifBreak(
canHaveTrailingComma && shouldPrintComma(options) ? "," : ""
),
indent(
align(
parentIsUnionTypeAnnotation ? 2 : 0,
concat([options.bracketSpacing ? line : softline, rightBrace])
),
@ -805,7 +807,6 @@ function genericPrintNoParens(path, options, print) {
concat([
"[",
indent(
options.tabWidth,
concat([
softline,
printArrayItems(path, options, "elements", print)
@ -887,14 +888,13 @@ function genericPrintNoParens(path, options, print) {
concat([
path.call(print, "test"),
indent(
options.tabWidth,
concat([
line,
"? ",
indent(2, path.call(print, "consequent")),
align(2, path.call(print, "consequent")),
line,
": ",
indent(2, path.call(print, "alternate"))
align(2, path.call(print, "alternate"))
])
)
])
@ -926,7 +926,6 @@ function genericPrintNoParens(path, options, print) {
" ",
printed[0],
indent(
options.tabWidth,
concat(printed.slice(1).map(p => concat([",", line, p])))
)
];
@ -968,7 +967,6 @@ function genericPrintNoParens(path, options, print) {
"if (",
group(concat([
indent(
options.tabWidth,
concat([softline, path.call(print, "test")])
),
softline
@ -1022,7 +1020,6 @@ function genericPrintNoParens(path, options, print) {
group(
concat([
indent(
options.tabWidth,
concat([
softline,
path.call(print, "init"),
@ -1047,7 +1044,6 @@ function genericPrintNoParens(path, options, print) {
group(
concat([
indent(
options.tabWidth,
concat([softline, path.call(print, "test")])
),
softline
@ -1164,7 +1160,6 @@ function genericPrintNoParens(path, options, print) {
") {",
n.cases.length > 0
? indent(
options.tabWidth,
concat([hardline, join(hardline, path.map(print, "cases"))])
)
: "",
@ -1188,7 +1183,7 @@ function genericPrintNoParens(path, options, print) {
parts.push(
isCurlyBracket(cons)
? concat([" ", cons])
: indent(options.tabWidth, concat([hardline, cons]))
: indent(concat([hardline, cons]))
);
}
@ -1250,7 +1245,6 @@ function genericPrintNoParens(path, options, print) {
concat([
"{",
indent(
options.tabWidth,
concat([softline, path.call(print, "expression")])
),
softline,
@ -1290,7 +1284,6 @@ function genericPrintNoParens(path, options, print) {
path.call(print, "name"),
concat([
indent(
options.tabWidth,
concat(
path.map(attr => concat([line, print(attr)]), "attributes")
)
@ -1333,7 +1326,6 @@ function genericPrintNoParens(path, options, print) {
"{",
n.body.length > 0
? indent(
options.tabWidth,
concat([
hardline,
path.call(
@ -1481,7 +1473,6 @@ function genericPrintNoParens(path, options, print) {
concat([
"[",
indent(
options.tabWidth,
concat([
softline,
printArrayItems(path, options, typesField, print)
@ -1620,7 +1611,6 @@ function genericPrintNoParens(path, options, print) {
parts.push(
group(
indent(
options.tabWidth,
concat([
line,
"extends ",
@ -1658,7 +1648,7 @@ function genericPrintNoParens(path, options, print) {
result.push(" & ", types[i]);
} else {
// Otherwise go to the next line and indent
result.push(indent(options.tabWidth, concat([" &", line, types[i]])));
result.push(indent(concat([" &", line, types[i]])));
}
}
return group(concat(result));
@ -1678,14 +1668,14 @@ function genericPrintNoParens(path, options, print) {
const shouldIndent = !(parent.type === "TypeAlias" &&
hasLeadingOwnLineComment(options.originalText, n));
//const token = isIntersection ? "&" : "|";
const code = concat([
ifBreak(concat([shouldIndent ? line : "", "| "])),
join(concat([line, "| "]), path.map(print, "types"))
]);
return group(
indent(
shouldIndent ? options.tabWidth : 0,
concat([
ifBreak(concat([shouldIndent ? line : "", "| "])),
join(concat([line, "| "]), path.map(print, "types"))
])
)
shouldIndent ? indent(code) : code
);
}
case "NullableTypeAnnotation":
@ -1769,7 +1759,6 @@ function genericPrintNoParens(path, options, print) {
" =",
hasLeadingOwnLineComment(options.originalText, n.right)
? indent(
options.tabWidth,
concat([hardline, path.call(print, "right")])
)
: concat([" ", path.call(print, "right")]),
@ -1798,7 +1787,6 @@ function genericPrintNoParens(path, options, print) {
return group(concat([
"<",
indent(
options.tabWidth,
concat([
softline,
join(concat([",", line]), path.map(print, "params")),
@ -2130,7 +2118,6 @@ function printArgumentsList(path, options, print) {
concat([
"(",
indent(
options.tabWidth,
concat([line, join(concat([",", line]), printed)])
),
shouldPrintComma(options, "all") ? "," : "",
@ -2149,7 +2136,6 @@ function printArgumentsList(path, options, print) {
concat([
"(",
indent(
options.tabWidth,
concat([softline, join(concat([",", line]), printed)])
),
ifBreak(shouldPrintComma(options, "all") ? "," : ""),
@ -2241,7 +2227,6 @@ function printFunctionParams(path, print, options) {
return concat([
isFlowShorthandWithOneArg ? "" : "(",
indent(
options.tabWidth,
concat([softline, join(concat([",", line]), printed)])
),
ifBreak(
@ -2403,7 +2388,6 @@ function printExportDeclaration(path, options, print) {
concat([
"{",
indent(
options.tabWidth,
concat([
options.bracketSpacing ? line : softline,
join(concat([",", line]), specifiers)
@ -2497,7 +2481,7 @@ function printClass(path, options, print) {
}
if (partsGroup.length > 0) {
parts.push(group(indent(options.tabWidth, concat(partsGroup))));
parts.push(group(indent(concat(partsGroup))));
}
parts.push(" ", path.call(print, "body"));
@ -2515,7 +2499,7 @@ function printMemberLookup(path, options, print) {
"[",
group(
concat([
indent(options.tabWidth, concat([softline, property])),
indent(concat([softline, property])),
softline
])
),
@ -2683,7 +2667,6 @@ function printMemberChain(path, options, print) {
function printIndentedGroup(groups) {
return indent(
options.tabWidth,
group(concat([hardline, join(hardline, groups.map(printGroup))]))
);
}
@ -2951,7 +2934,6 @@ function printJSXElement(path, options, print) {
concat([
openingLines,
indent(
options.tabWidth,
group(concat(childrenGroupedByLine), { shouldBreak: true })
),
hardline,
@ -2989,7 +2971,7 @@ function maybeWrapJSXElementInParens(path, elem, options) {
return group(
concat([
ifBreak("("),
indent(options.tabWidth, concat([softline, elem])),
indent(concat([softline, elem])),
softline,
ifBreak(")")
])
@ -3086,12 +3068,10 @@ function printAssignment(printedLeft, operator, rightNode, printedRight, options
let printed;
if (hasLeadingOwnLineComment(options.originalText, rightNode)) {
printed = indent(
options.tabWidth,
concat([hardline, printedRight])
);
} else if (isBinaryish(rightNode) && !shouldInlineLogicalExpression(rightNode)) {
printed = indent(
options.tabWidth,
concat([line, printedRight])
);
} else {
@ -3115,7 +3095,7 @@ function adjustClause(clause, options, forceSpace) {
return concat([" ", clause]);
}
return indent(options.tabWidth, concat([line, clause]));
return indent(concat([line, clause]));
}
function isCurlyBracket(doc) {