Add `--range-start` and `--range-end` options to format only parts of the input (#1609)

* Add `--range-start` and `--range-end` options to format only parts of the input

These options default to `0` and `Infinity`, respectively, so that the
entire input is formatted by default. However, if either option is
specified such that a node lies completely outside the resulting range,
the node will be treated as if it has a `// prettier-ignore` comment.

Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179
Related to https://github.com/prettier/prettier/issues/1324
Related to https://github.com/prettier/prettier/issues/593

* printer: Extract hasPrettierIgnoreComment() helper

* Move isOutsideRange() to util

* Don't throw errors about comments outside range "not printing"

* Remove unnecessary check from isOutsideRange()

* Make --range-end exclusive

This lets it use the conventional way of specifying ranges in strings.

Note that if the rangeEnd in the tests is changed to 158, it will fail,
but it wouldn't have failed before this change.

* Change range formatting approach

NOTE: This doesn't pass its test yet. Note that since we're reading the
indentation from the first line, it is expected not to change. However,
a semicolon is added, and the lines outside the range are not changed.

The new approach is roughly:

* Require that the range exactly covers an integer number of lines of the input
* Detect the indentation of the line the range starts on
* Format the range's substring using `printAstToDoc`
* Add enough `indent`s to the doc to restore the detected indentation
* Format the doc to a string with `printDocToString`
* Prepend/append the original input before/after the range

See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273

---

Given `tests/range/range.js`, run the following:

    prettier tests/range/range.js --range-start 165 --range-end 246

See the range's text with:

    dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null

* Don't use default function parameters

Node v4 doesn't support them. See
http://node.green/#ES2015-syntax-default-function-parameters

* Hackily fix indentation of range formatting

See
https://github.com/prettier/prettier/pull/1609#issuecomment-301625368

Also update the snapshot to reflect that the indentation actually should
decrease by one space, since there were 13 spaces in the input and we
round down after dividing by tabWidth.

* Revert "printer: Extract hasPrettierIgnoreComment() helper"

See https://github.com/prettier/prettier/pull/1609#discussion_r116804853

This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d.

* Test automatically using the beginning of the rangeStart line and same for the end

See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076

* Fix automatically using the beginning of the rangeStart line and same for the end

See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076

* Propagate breaks after adding an indentation-triggering hardline

See c1a61ebde8 (r116805581)

* Extract getAlignmentSize(), use instead of countIndents()

See c1a61ebde8 (r116804694)

* Extract addAlignmentToDoc(), use instead of addIndentsToDoc()

See c1a61ebde8 (r116804694)

* Document that --range-start and --range-end include the entire line

* Fix rangeStart calculation

Before, it was incorrectly resulting in 1 when the originally provided
value was 0

* Extract formatRange() helper function

* Move getAlignmentSize() from printer to util

This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241

* Move addAlignmentToDoc() from printer to doc-builders

This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
master
Joseph Frazier 2017-05-21 13:14:13 -04:00 committed by Christopher Chedeau
parent f3a049627d
commit 569380155b
10 changed files with 148 additions and 30 deletions

View File

@ -262,6 +262,8 @@ Prettier ships with a handful of customizable format options, usable in both the
| **JSX Brackets on Same Line** - Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line | `false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>` |
| **Parser** - Specify which parser to use. | `babylon` | <code>--parser <flow&#124;babylon></code> | <code>parser: "<flow&#124;babylon>"</code> |
| **Semicolons** - Print semicolons at the ends of statements.<br /><br />Valid options: <br /> - `true` - add a semicolon at the end of every statement <br /> - `false` - only add semicolons at the beginning of lines that may introduce ASI failures | `true` | `--no-semi` | `semi: <bool>` |
| **Range Start** - Format code starting at a given character offset. The range will extend backwards to the start of the line. | `0` | `--range-start <int>` | `rangeStart: <int>` |
| **Range End** - Format code ending at a given character offset (exclusive). The range will extend forwards to the end of the line. | `Infinity` | `--range-end <int>` | `rangeEnd: <int>` |
### Excluding code from formatting

View File

@ -33,7 +33,7 @@ const argv = minimist(process.argv.slice(2), {
// Deprecated in 0.0.10
"flow-parser"
],
string: ["print-width", "tab-width", "parser", "trailing-comma"],
string: ["print-width", "tab-width", "parser", "trailing-comma", "range-start", "range-end"],
default: { semi: true, color: true, "bracket-spacing": true, parser: "babylon" },
alias: { help: "h", version: "v", "list-different": "l" },
unknown: param => {
@ -127,6 +127,8 @@ function getTrailingComma() {
}
const options = {
rangeStart: getIntOption("range-start"),
rangeEnd: getIntOption("range-end"),
useTabs: argv["use-tabs"],
semi: argv["semi"],
printWidth: getIntOption("print-width"),
@ -217,6 +219,8 @@ if (argv["help"] || (!filepatterns.length && !stdin)) {
" --trailing-comma <none|es5|all>\n" +
" Print trailing commas wherever possible. Defaults to none.\n" +
" --parser <flow|babylon> Specify which parse to use. Defaults to babylon.\n" +
" --range-start <int> Format code starting at a given character offset. The range will extend backwards to the start of the line. Defaults to 0.\n" +
" --range-end <int> Format code ending at a given character offset (exclusive). The range will extend forwards to the end of the line. Defaults to Infinity.\n" +
" --no-color Do not colorize error messages.\n" +
" --version or -v Print Prettier version.\n" +
"\n"

View File

@ -3,6 +3,7 @@
const comments = require("./src/comments");
const version = require("./package.json").version;
const printAstToDoc = require("./src/printer").printAstToDoc;
const getAlignmentSize = require("./src/util").getAlignmentSize;
const printDocToString = require("./src/doc-printer").printDocToString;
const normalizeOptions = require("./src/options").normalize;
const parser = require("./src/parser");
@ -48,16 +49,59 @@ function ensureAllCommentsPrinted(astComments) {
});
}
function format(text, opts) {
function format(text, opts, addAlignmentSize) {
addAlignmentSize = addAlignmentSize || 0;
const formattedRangeOnly = formatRange(text, opts);
if (formattedRangeOnly) {
return formattedRangeOnly;
}
const ast = parser.parse(text, opts);
const astComments = attachComments(text, ast, opts);
const doc = printAstToDoc(ast, opts);
const doc = printAstToDoc(ast, opts, addAlignmentSize);
opts.newLine = guessLineEnding(text);
const str = printDocToString(doc, opts);
ensureAllCommentsPrinted(astComments);
// Remove extra leading newline as well as the added indentation after last newline
if (addAlignmentSize > 0) {
return str.slice(opts.newLine.length).trimRight() + opts.newLine;
}
return str;
}
function formatRange(text, opts) {
// Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
const rangeStart = Math.min(
opts.rangeStart,
text.lastIndexOf("\n", opts.rangeStart) + 1
);
// Use `text.length - 1` as the maximum since `indexOf` returns -1 if `fromIndex >= text.length`
const fromIndex = Math.min(opts.rangeEnd, text.length - 1);
const nextNewLineIndex = text.indexOf("\n", fromIndex);
const rangeEnd = (nextNewLineIndex < 0 ? fromIndex : nextNewLineIndex) + 1; // Add one to make rangeEnd exclusive
if (0 < rangeStart || rangeEnd < text.length) {
const rangeString = text.substring(rangeStart, rangeEnd);
const alignmentSize = getAlignmentSize(
rangeString.slice(0, rangeString.search(/[^ \t]/)),
opts.tabWidth
);
const rangeFormatted = format(
rangeString,
Object.assign({}, opts, {
rangeStart: 0,
rangeEnd: Infinity,
printWidth: opts.printWidth - alignmentSize
}),
alignmentSize
);
return text.slice(0, rangeStart) + rangeFormatted + text.slice(rangeEnd);
}
}
function formatWithShebang(text, opts) {
if (!text.startsWith("#!")) {
return format(text, opts);

View File

@ -100,6 +100,22 @@ function join(sep, arr) {
return concat(res);
}
function addAlignmentToDoc(doc, size, tabWidth) {
let aligned = doc;
if (size > 0) {
// Use indent to add tabs for all the levels of tabs we need
for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
aligned = indent(aligned);
}
// Use align for all the spaces that are needed
aligned = align(size % tabWidth, aligned);
// size is absolute from 0 and not relative to the current
// indentation, so we use -Infinity to reset the indentation to 0
aligned = align(-Infinity, aligned);
}
return aligned;
}
module.exports = {
concat,
join,
@ -115,5 +131,6 @@ module.exports = {
breakParent,
ifBreak,
indent,
align
align,
addAlignmentToDoc
};

View File

@ -4,6 +4,8 @@ const validate = require("jest-validate").validate;
const deprecatedConfig = require("./deprecated");
const defaults = {
rangeStart: 0,
rangeEnd: Infinity,
useTabs: false,
tabWidth: 2,
printWidth: 80,

View File

@ -21,6 +21,7 @@ const fill = docBuilders.fill;
const ifBreak = docBuilders.ifBreak;
const breakParent = docBuilders.breakParent;
const lineSuffixBoundary = docBuilders.lineSuffixBoundary;
const addAlignmentToDoc = docBuilders.addAlignmentToDoc;
const docUtils = require("./doc-utils");
const willBreak = docUtils.willBreak;
@ -1670,31 +1671,14 @@ function genericPrintNoParens(path, options, print, args) {
const index = value.lastIndexOf('\n');
const tabWidth = options.tabWidth;
if (index !== -1) {
for (let i = index + 1; i < value.length; ++i) {
if (value[i] === '\t') {
// Tabs behave in a way that they are aligned to the nearest
// multiple of tabWidth:
// 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
// 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
size = size + tabWidth - size % tabWidth;
} else {
size++;
}
}
size = util.getAlignmentSize(value, tabWidth, index + 1);
}
let aligned = removeLines(expressions[i]);
if (size > 0) {
// Use indent to add tabs for all the levels of tabs we need
for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
aligned = indent(aligned);
}
// Use align for all the spaces that are needed
aligned = align(size % tabWidth, aligned);
// size is absolute from 0 and not relative to the current
// indentation, so we use -Infinity to reset the indentation to 0
aligned = align(-Infinity, aligned);
}
let aligned = addAlignmentToDoc(
removeLines(expressions[i]),
size,
tabWidth
);
parts.push(
"${",
@ -4281,7 +4265,9 @@ function removeLines(doc) {
});
}
function printAstToDoc(ast, options) {
function printAstToDoc(ast, options, addAlignmentSize) {
addAlignmentSize = addAlignmentSize || 0;
function printGenerically(path, args) {
return comments.printComments(
path,
@ -4291,7 +4277,16 @@ function printAstToDoc(ast, options) {
);
}
const doc = printGenerically(FastPath.from(ast));
let doc = printGenerically(FastPath.from(ast));
if (addAlignmentSize > 0) {
// Add a hardline to make the indents take effect
// It should be removed in index.js format()
doc = addAlignmentToDoc(
removeLines(concat([hardline, doc])),
addAlignmentSize,
options.tabWidth
);
}
docUtils.propagateBreaks(doc);
return doc;
}

View File

@ -320,6 +320,25 @@ function isBlockComment(comment) {
return comment.type === "Block" || comment.type === "CommentBlock";
}
function getAlignmentSize(value, tabWidth, startIndex) {
startIndex = startIndex || 0;
let size = 0;
for (let i = startIndex; i < value.length; ++i) {
if (value[i] === '\t') {
// Tabs behave in a way that they are aligned to the nearest
// multiple of tabWidth:
// 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
// 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
size = size + tabWidth - size % tabWidth;
} else {
size++;
}
}
return size;
}
module.exports = {
getPrecedence,
isExportDeclaration,
@ -341,5 +360,6 @@ module.exports = {
setLocEnd,
startsWithNoLookaheadToken,
hasBlockComments,
isBlockComment
isBlockComment,
getAlignmentSize
};

View File

@ -0,0 +1,24 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`range.js 1`] = `
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
\`multiline template string
with too much indentation\`
// The [165, 246) range selects the above two lines, including the second newline
}
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
\`multiline template string
with too much indentation\`;
// The [165, 246) range selects the above two lines, including the second newline
}
}
}
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { rangeStart: 180, rangeEnd: 220 });

9
tests/range/range.js Normal file
View File

@ -0,0 +1,9 @@
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
function ugly ( {a=1, b = 2 } ) {
`multiline template string
with too much indentation`
// The [165, 246) range selects the above two lines, including the second newline
}
}
}