prettier/src/doc/doc-builders.js

179 lines
3.6 KiB
JavaScript
Raw Normal View History

"use strict";
2017-01-28 18:50:22 +03:00
function assertDoc(val) {
/* istanbul ignore if */
2017-01-28 18:50:22 +03:00
if (
2017-02-23 20:57:51 +03:00
!(typeof val === "string" || (val != null && typeof val.type === "string"))
2017-01-28 18:50:22 +03:00
) {
throw new Error(
"Value " + JSON.stringify(val) + " is not a valid document"
);
}
}
function concat(parts) {
if (process.env.NODE_ENV !== "production") {
parts.forEach(assertDoc);
}
// We cannot do this until we change `printJSXElement` to not
// access the internals of a document directly.
// if(parts.length === 1) {
// // If it's a single document, no need to concat it.
// return parts[0];
// }
return { type: "concat", parts };
}
function indent(contents) {
if (process.env.NODE_ENV !== "production") {
assertDoc(contents);
}
return { type: "indent", contents };
}
function align(n, contents) {
if (process.env.NODE_ENV !== "production") {
assertDoc(contents);
}
return { type: "align", contents, n };
}
function group(contents, opts) {
opts = opts || {};
if (process.env.NODE_ENV !== "production") {
assertDoc(contents);
}
return {
type: "group",
id: opts.id,
contents: contents,
break: !!opts.shouldBreak,
expandedStates: opts.expandedStates
};
}
function dedentToRoot(contents) {
return align(-Infinity, contents);
}
function markAsRoot(contents) {
return align({ type: "root" }, contents);
}
function dedent(contents) {
return align(-1, contents);
}
function conditionalGroup(states, opts) {
return group(
states[0],
Object.assign(opts || {}, { expandedStates: states })
);
}
function fill(parts) {
if (process.env.NODE_ENV !== "production") {
parts.forEach(assertDoc);
}
return { type: "fill", parts };
}
function ifBreak(breakContents, flatContents, opts) {
opts = opts || {};
if (process.env.NODE_ENV !== "production") {
if (breakContents) {
assertDoc(breakContents);
}
if (flatContents) {
assertDoc(flatContents);
}
}
return {
type: "if-break",
breakContents,
flatContents,
groupId: opts.groupId
};
}
function lineSuffix(contents) {
if (process.env.NODE_ENV !== "production") {
assertDoc(contents);
}
return { type: "line-suffix", contents };
}
const lineSuffixBoundary = { type: "line-suffix-boundary" };
2017-01-28 18:50:22 +03:00
const breakParent = { type: "break-parent" };
const trim = { type: "trim" };
const line = { type: "line" };
const softline = { type: "line", soft: true };
2017-01-28 18:50:22 +03:00
const hardline = concat([{ type: "line", hard: true }, breakParent]);
const literalline = concat([
{ type: "line", hard: true, literal: true },
breakParent
]);
const cursor = { type: "cursor", placeholder: Symbol("cursor") };
function join(sep, arr) {
const res = [];
for (let i = 0; i < arr.length; i++) {
if (i !== 0) {
res.push(sep);
}
res.push(arr[i]);
}
return concat(res);
}
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 https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#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
2017-05-21 20:14:13 +03:00
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,
line,
softline,
hardline,
literalline,
group,
conditionalGroup,
fill,
lineSuffix,
lineSuffixBoundary,
Add `cursorOffset` option for cursor translation (#1637) * Add `formatWithCursor` API with `cursorOffset` option This addresses https://github.com/prettier/prettier/issues/93 by adding a new option, `cursorOffset`, that tells prettier to determine the location of the cursor after the code has been formatted. This is accessible through the API via a new function, `formatWithCursor`, which returns a `{formatted: string, cursorOffset: ?number}`. Here's a usage example: ```js require("prettier").formatWithCursor(" 1", { cursorOffset: 2 }); // -> { formatted: '1;\n', cursorOffset: 1 } ``` * Add `--cursor-offset` CLI option It will print out the offset instead of the formatted output. This makes it easier to test. For example: echo ' 1' | prettier --stdin --cursor-offset 2 # prints 1 * Add basic test of cursor translation * Document `cursorOffset` option and `formatWithCursor()` * Print translated cursor offset to stderr when --cursor-offset is given This lets us continue to print the formatted code, while also communicating the updated cursor position. See https://github.com/prettier/prettier/pull/1637#discussion_r119735496 * doc-print cursor placeholder in comments.printComments() See https://github.com/prettier/prettier/pull/1637#discussion_r119735149 * Compare array index to -1 instead of >= 0 to determine element presence See https://github.com/prettier/prettier/pull/1637#discussion_r119736623 * Return {formatted, cursor} from printDocToString() instead of mutating options See https://github.com/prettier/prettier/pull/1637#discussion_r119737354
2017-06-02 01:52:29 +03:00
cursor,
breakParent,
ifBreak,
trim,
indent,
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 https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#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
2017-05-21 20:14:13 +03:00
align,
addAlignmentToDoc,
markAsRoot,
dedentToRoot,
dedent
};