Skip to content

Conversation

josephfrazier
Copy link
Collaborator

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 #1577 (comment)
Related to #1324
Related to #593

… 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 prettier#1577 (comment)
Related to prettier#1324
Related to prettier#593
src/printer.js Outdated
if (hasPrettierIgnoreComment(node)) {
if (
hasPrettierIgnoreComment(node) ||
isOutsideRange(node, options.rangeStart, options.rangeEnd)
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic currently isn't clever enough to isolate formatting to nodes within another node. In other words, formatting is applied to parent nodes until a top-level node is reached. This isn't ideal, but it's a start.

Demo: Formatting this code with prettier --range-start 61 --range-end 81 touches more than just one line:

if ( true ) {
    tooMuchIndentation();
}
if ( true ) {
    tooMuchIndentation();
    // THE ABOVE LINE IS THE ONLY ONE IN THE RANGE 61-81
    // BUT THE LINE ABOVE THAT (`if ( true ) {`) ALSO GETS FORMATTED
}
if ( true ) {
    tooMuchIndentation();
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, it's a little more subtle than that. For example, try formatting the following code with prettier --range-start 25 --range-end 45:

if ( {a:1,
b:2} ) {
    tooMuchIndentation();
    // THE ABOVE LINE IS THE ONLY ONE IN THE RANGE 25-45
}

The result is:

if ({a:1,
b:2}) {
  tooMuchIndentation();
  // THE ABOVE LINE IS THE ONLY ONE IN THE RANGE 25-45
}

which still removes the whitespace around the object literal, but isn't completely formatting it, as a range-less prettier invocation would:

if (
  {
    a: 1,
    b: 2
  }
) {
  tooMuchIndentation();
  // THE ABOVE LINE IS THE ONLY ONE IN THE RANGE 25-45
}

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.
@vjeux
Copy link
Contributor

vjeux commented May 15, 2017

What happens if you have three nested functions and one block of code inside and the range of the block of code. Will it reformat the arguments of the nested functions?

@josephfrazier
Copy link
Collaborator Author

josephfrazier commented May 15, 2017

Well, it reformats the arguments to the extent that concrete syntax tree (CST) information outside the arguments themselves is discarded, so whitespace around the arguments is removed. However, the arguments themselves stay formatted as they were originally. For example, given nested.js consisting of this code:

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 [163, 251) range selects from the innermost function body's opening brace to this closing brace (inclusive). You can verify this with `dd if=nested.js ibs=1 skip=163 count=88`
  }
}

Running prettier nested.js --range-start 163 --range-end 251 yields the following:

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 [163, 251) range selects from the innermost function body's opening brace to this closing brace (inclusive). You can verify this with `dd if=nested.js ibs=1 skip=163 count=88`
  }
}

whereas simply running prettier nested.js yields:

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 [163, 251) range selects from the innermost function body's opening brace to this closing brace (inclusive). You can verify this with `dd if=nested.js ibs=1 skip=163 count=88`
  }
}

I'm not sure if there's a good way to make the arguments completely untouched (and handle other cases like the if one above), other than by going into genericPrintNoParens (and its helpers) and checking the loc of every node before deciding how to print it.

Given that, I could add a disclaimer in the documentation saying that nodes surrounding the given range may suffer some slight reformatting.

@vjeux
Copy link
Contributor

vjeux commented May 15, 2017

It may also change the indentation of the entire code :(

What I had in mind was closer to your original implementation: we look upward to the first statement, check its indentation and re-indent it based on it. If you select more than one statement, then indent all of them.

I think that's a bit more complicated on prettier side but would lead the best results.

@vjeux
Copy link
Contributor

vjeux commented May 15, 2017

What do you think?

@josephfrazier
Copy link
Collaborator Author

It may also change the indentation of the entire code :(

Yeah, it does, unfortunately. That's probably a show-stopper for many use cases.

What I had in mind was closer to your original implementation: we look upward to the first statement, check its indentation and re-indent it based on it. If you select more than one statement, then indent all of them.

Ah, I think I'm starting to see it now. Maybe a good middle ground would be:

  • 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 indents 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

This could be extended later, of course, but it seems like a nice MVP.

@vjeux
Copy link
Contributor

vjeux commented May 15, 2017

Yeah, that's it! Do you want to try it out?

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 prettier#1609 (comment)

---

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
@josephfrazier
Copy link
Collaborator Author

Sure, I just pushed up 44bfd9b trying it out (see the commit message for more details). However, it looks like wrapping a bunch of indents around the doc isn't enough to get printDocToString to actually indent it. Any ideas? I'm not yet familiar enough with how the doc-builders are intended to be assembled.

See
prettier#1609 (comment)

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.
@josephfrazier
Copy link
Collaborator Author

Actually, I spoke too soon. After a bit more debugging, I found that hardlines seem to trigger the indentation, so I added one in printAstToDoc(), then removed the resulting newline in format() (see c1a61eb). I feel like there's probably a better way of doing this, though...

Copy link
Contributor

@vjeux vjeux left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm currently in vacation with spotty internet and only my phone so won't be able to do an indepth review until next week, but some comments.

I think that if you are only doing text based ranges, you should automatically use the beginning of the rangeStart line and same for the end, otherwise it's going to be super annoying to have to select exactly those and throw if not.

I also do think that the ast based one where you group by statements shouldn't be too hard to implement and feel much better as you can select any sub range and it'll do the right thing.

Thanks so much for driving this, it's going to be awesome, it's a much requested feature!

index.js Outdated
return str;
}

function countIndents(text, opts) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you look at template literal code, I have some piece of code that is much more precise.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ooh, that is quite a lot better! Fixed in e1c993e and 77a8fb0

src/printer.js Outdated
@@ -49,18 +49,22 @@ function shouldPrintComma(options, level) {
}
}

function hasPrettierIgnoreComment(node) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't need to extract it anymore right?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, fixed in 1e60895

src/printer.js Outdated
@@ -4256,7 +4262,19 @@ function printAstToDoc(ast, options) {

const doc = printGenerically(FastPath.from(ast));
docUtils.propagateBreaks(doc);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should likely be done after you add hardline as hardline intro a break. This isn't going to do anything wrong here but it would be better to do the "right" thing as if we're adding some more code that relies on this, it's going to break in unexpected ways.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I hadn't considered that (I didn't really think about what propagateBreaks does). Fixed in 070b941

@josephfrazier
Copy link
Collaborator Author

I'm currently in vacation with spotty internet and only my phone so won't be able to do an indepth review until next week, but some comments.

No problem, feel free to ignore this for the rest of your vacation :)

I think that if you are only doing text based ranges, you should automatically use the beginning of the rangeStart line and same for the end, otherwise it's going to be super annoying to have to select exactly those and throw if not.

Good call. I had considered that, but didn't implement it quite yet. It shouldn't be too difficult, though.

I also do think that the ast based one where you group by statements shouldn't be too hard to implement and feel much better as you can select any sub range and it'll do the right thing.

Yeah, that would be ideal. I don't yet understand how that would work with the indentation detection, though, assuming it allows you to format partial lines. Maybe it'll make more sense as I keep working on the line-based version.

Thanks so much for driving this, it's going to be awesome, it's a much requested feature!

Glad to help, I'm looking forward to having it available!

Copy link
Collaborator Author

@josephfrazier josephfrazier left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that if you are only doing text based ranges, you should automatically use the beginning of the rangeStart line and same for the end, otherwise it's going to be super annoying to have to select exactly those and throw if not.

Good call. I had considered that, but didn't implement it quite yet. It shouldn't be too difficult, though.

Now implemented in 2ca9f18 and bec69d0

I also do think that the ast based one where you group by statements shouldn't be too hard to implement and feel much better as you can select any sub range and it'll do the right thing.

Yeah, that would be ideal. I don't yet understand how that would work with the indentation detection, though, assuming it allows you to format partial lines. Maybe it'll make more sense as I keep working on the line-based version.

I'll have to keep thinking on this one.

src/printer.js Outdated
@@ -49,18 +49,22 @@ function shouldPrintComma(options, level) {
}
}

function hasPrettierIgnoreComment(node) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, fixed in 1e60895

src/printer.js Outdated
@@ -4256,7 +4262,19 @@ function printAstToDoc(ast, options) {

const doc = printGenerically(FastPath.from(ast));
docUtils.propagateBreaks(doc);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I hadn't considered that (I didn't really think about what propagateBreaks does). Fixed in 070b941

index.js Outdated
return str;
}

function countIndents(text, opts) {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ooh, that is quite a lot better! Fixed in e1c993e and 77a8fb0

Before, it was incorrectly resulting in 1 when the originally provided
value was 0
@xtuc
Copy link

xtuc commented May 21, 2017

This is a great feature!
My only concern is what should happen when the selected range contains code with an invalid syntax? Most editor integration will show a red message about that.

Would be interesting to discus about the possibility of parsing invalid grammar or syntax. I know there was the discussion for Babylon.

src/printer.js Outdated
@@ -49,6 +49,25 @@ function shouldPrintComma(options, level) {
}
}

function getAlignmentSize(value, tabWidth, startIndex) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you put this inside of util?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, fixed in db0ec7a

src/printer.js Outdated
docUtils.propagateBreaks(doc);
return doc;
}

module.exports = { printAstToDoc };
function addAlignmentToDoc(doc, size, tabWidth) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you put this inside of doc-builder?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, fixed in 149e18c

if (0 < rangeStart || rangeEnd < text.length) {
const rangeString = text.substring(rangeStart, rangeEnd);
const alignmentSize = getAlignmentSize(
rangeString.slice(0, rangeString.search(/[^ \t]/)),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow, I had no idea that search existed!

@vjeux
Copy link
Contributor

vjeux commented May 21, 2017

Code looks really good, thanks! If you move the two little utilities in their respective files, I'll merge this :)

@vjeux vjeux merged commit 5693801 into prettier:master May 21, 2017
@josephfrazier josephfrazier deleted the range branch May 21, 2017 18:12
@josephfrazier
Copy link
Collaborator Author

Thanks for the merge! My work on cursor translation (#1637) has given me some ideas on how to extend this to support formatting any range, without changing the code outside of it, so hopefully I'll have that ready at some point as well.

@vjeux
Copy link
Contributor

vjeux commented May 21, 2017

Yay!

josephfrazier added a commit to josephfrazier/prettier-vscode that referenced this pull request Jun 2, 2017
This fixes prettier#109 by using
the new `rangeStart` and `rangeEnd` options in Prettier v1.4.0 (see here
for details: prettier/prettier#1609)
@ikatyang ikatyang mentioned this pull request Dec 17, 2018
3 tasks
@lock lock bot added the locked-due-to-inactivity Please open a new issue and fill out the template instead of commenting. label Jan 20, 2019
@lock lock bot locked as resolved and limited conversation to collaborators Jan 20, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
locked-due-to-inactivity Please open a new issue and fill out the template instead of commenting.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants