Commit Graph

50 Commits (05b921efdd3e1e63091c0e63e47fe7c013530e7e)

Author SHA1 Message Date
Christopher Chedeau 05b921efdd Build the dist/ with rollup (#1794) 2017-05-28 21:49:41 -07:00
Joseph Frazier 9d7515907e Pass entire text through formatWithShebang() to format() (#1718)
* Verify shebang tests against Babylon as well as Flow/Typescript

* Pass entire text through formatWithShebang() to format()

That way, we won't have to do any arithmetic on range and cursor
locations when there is a shebang. See here for details:

https://github.com/prettier/prettier/pull/1637#issuecomment-303846507

This required changing comment printing such that comments that are
actually shebangs are just ignored.

* Add curly brace after `if`

See https://github.com/prettier/prettier/pull/1718#discussion_r118382574
2017-05-24 18:59:25 -04:00
Christopher Chedeau 78ba808322 Initial CSS support (#1636)
I wanted to see how hard it would be to add support for CSS inside of prettier. Turns out, it's not that hard. I spent a few hours printing post-css values and getting all the stylefmt unit tests to not throw.
2017-05-24 10:52:12 -07:00
Joseph Frazier 330601c77d Find nearest node when formatting range (#1659)
* Move range extension code into helper functions

* Add findNodeByOffset() helper

This was adapted from cbc1929c64

* Test extending formatted range to entire node

* Fix extending formatted range to entire node

* Fix style errors

* Add run_file test function

This makes it possible to use different options on a per-file basis,
which is useful for things like range formatting tests.

* Test extending the format range to nearest parseable node

This means you can select the range of a `catch` clause, attempt to
format it, and have the `try` formatted as well, rather than throwing an
error.

* Fix extending the format range to nearest parseable node

This means you can select the range of a `catch` clause, attempt to
format it, and have the `try` formatted as well, rather than throwing an
error.

* Test that external indentation is left alone when formatting a range

* Preserve external indentation when formatting a range

* Dedupe range formatting traversal callbacks

* Simplify range formatting traversal using ast-types

See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798

* Make range formatting traversal more efficient

There's less unnecessary parsing now.

* Fix style errors

* Add test where range expanding fails

* Fix test where range expanding fails

This makes sure that the range contains the entirety of the nodes
containing each of the range's endpoints.

* Add test for expanding range to beginning of line

* Pass test for expanding range to beginning of line

This makes it so that indentation before the range is added to the
formatted range.

* Don't parse/stringify AST to detect pre-range indentation

See https://github.com/prettier/prettier/pull/1659#discussion_r117790671

* When formatting a range, find closest statement rather than parsing

The `isStatement` implementation came from `docs/prettier.min.js`.

See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770

* Add test for range-formatting a FunctionDeclaration's argument object

* Include FunctionDeclaration when searching for nearest node to range-format

From the spec, a Program is a series of SourceElements, each of which is
either a Statement or a FunctionDeclaration. See
https://www.ecma-international.org/ecma-262/5.1/#sec-A.5

* Remove unnecessary try-catch

See https://github.com/prettier/prettier/pull/1659#discussion_r117810096

* Add tests with multiple statements

See https://github.com/prettier/prettier/pull/1659#discussion_r117810753

* Remove unnecessary arguments from findNodeByOffset()

* Contract format range to ensure it starts/ends on nodes

* Specify test ranges in the fixtures

See https://github.com/prettier/prettier/pull/1659#discussion_r117811186

* Remove unnecessary comments from range fixtures

* Remove run_file test function

It's no longer used. This essentially reverts
8241216e68f2e0da997a4f558b03658d642c89a2

* Update range formatting docs

Clarify that the range expands to the nearest statement, and not to the
end of the line.

* Don't overwrite test options when detecting range

Now that multiple files share the same object again, we shouldn't be
re-assigning to it.

* Reuse already-read fixtures for AST_COMPARE=1 tests

* Remove `run_file` global from test eslintrc

* Undo package.json churn

`yarn` reformatted it before, but the whitespace visually sets off the
comment, so let's put it back how it was before.

See https://github.com/prettier/prettier/pull/1659#discussion_r117864655

* Remove misleading comments from isSourceElement

See https://github.com/prettier/prettier/pull/1659#discussion_r117865196

* Loop backwards through string instead of reversing it

See https://github.com/prettier/prettier/pull/1659#discussion_r117865759

* Don't recompute indent string when formatting range

See https://github.com/prettier/prettier/pull/1659#discussion_r117867268

* Rename findNodeByOffset to findNodeAtOffset

"Find x by y" is the common usage for finding an `x` by a key `y`.
However, since "by" has positional meaning, let's use "at" instead.

See https://github.com/prettier/prettier/pull/1659#discussion_r117865121

* Always trimRight() in formatRange and explain why

See https://github.com/prettier/prettier/pull/1659#discussion_r117864635

* Test formatting a range that crosses AST levels

See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688

* Fix formatting a range that crosses AST levels

See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688

* Remove unnecessary try-catch

See e52db5e9f9 (r117878763)

* Add test demonstrating range formatting indent detection

* Detect alignment from text on line before range, but don't reformat it

This avoids reformatting non-indentation that happens to precede the
range on the same line, while still correctly indenting the range based
on it.

See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 07:43:58 -07:00
Joseph Frazier 569380155b 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
2017-05-21 10:14:13 -07:00
Joseph Frazier 18fd014985 Run AST comparison tests on Travis (#1553)
* Run AST comparison tests on Travis

It looks like some of these currently fail, so we should probably also
sort that out.

Inspired by https://github.com/prettier/prettier/issues/1552

* tests: Use specified parser when AST_COMPARE=1

This fixes some of the tests with AST_COMPARE=1

* Move cleanAST() into prettier.__debug

This makes it available for tests to use.

* AST_COMPARE=1 uses cleanAst() instead of removeEmptyStatements()

Ths fixes some of the tests with AST_COMPARE=1

* Export parse() from src/parser.js

This makes it available for tests to use.

* tests: Use specified parser more when AST_COMPARE=1

This is a continuation of commit 86437a66d326919897fe89891a25824870f5bb79

This fixes some of the tests with AST_COMPARE=1

* massageAST: remove leadingComments/trailingComments

This fixes some of the tests with AST_COMPARE=1

* massageAST: remove `extra`

This fixes some of the tests with AST_COMPARE=1

* tests_config/run_spec.js: Rename variables for clarity

* AST_COMPARE=1 tests compare unstringified objects

This makes the test error output shorter.

* fixup! Export parse() from src/parser.js

* Revert "Run AST comparison tests on Travis"

See https://github.com/prettier/prettier/pull/1553#issuecomment-300027747

This reverts commit 49873a956c532f23fd216551a35ae35c1a18407e.

* fixup! fixup! Export parse() from src/parser.js

* parser: Require babel-code-frame only when needed

This addresses:
* https://github.com/prettier/prettier/pull/1553#discussion_r115386253
* https://github.com/prettier/prettier/pull/1553#discussion_r115386250

* parser: Don't export now-unused parseWith* functions

Addresses https://github.com/prettier/prettier/pull/1553#discussion_r115386964

* Move cleanAST/massageAST into own file, don't export

This addresses:
* https://github.com/prettier/prettier/pull/1553#discussion_r115386993
* https://github.com/prettier/prettier/pull/1553#discussion_r115386611

* Don't destructure require() result (Node v4 compat.)

* Fix copy/paste error
2017-05-08 18:16:35 -07:00
lamo2k123 4b3835925e fixed method 'check' error 'format' of undefined (#1424)
* fixed method 'check' error 'format' of undefined

* Added normalizeOptions
2017-04-26 11:02:53 -07:00
Christopher Chedeau 7a8380772d Have --debug-check also run ast verification (#1337) 2017-04-21 16:09:33 -07:00
Christopher Chedeau 08e4e2c04c Do not print the sub-tree when using prettier-ignore (#1286)
In #1250, @jeresig reported that adding // prettier-ignore on a file that has a ton of conditional group still took 1.7s. The issue is that we're printing before checking for the comment. Swaping the two had the unfortunate side effect of not marking the comments as being printed, so I had to skip that safety check if there's a prettier-ignore.

With this change, adding prettier-ignore makes the file be printed instantly!
2017-04-18 07:51:50 -07:00
Christopher Chedeau 8e1583fd16 Format the codebase using the pre-1.0 release (#1194) 2017-04-12 10:16:11 -07:00
Rafael Hengles 170e4d558a Refactored option to indent with tabs (#1026)
Refactored option to indent with tabs
2017-04-06 22:49:37 -04:00
Brian Holt eff5af6ca9 Add check method to Prettier Node API. (#1104)
* Add check method to Prettier. Make CLI use that method for list-different

* Catch in check and return false if it throws

* Remove catch/finally from Prettier list-different bin

* remove try catch in prettier bin for list-different
2017-04-03 09:54:10 -07:00
James Henry 72456bf06f [WIP] TypeScript Parser (#915)
* WIP immediate feedback

* typescript parser is drop-in replacement for flow parser

* Add new TypeScript Parser snapshots where drop-in replacement possible

* Snapshot updates after rebasing

* Remove unnecessary stripping of properties on TypeScript parser AST

* Remove annotated issues

* Move TS dependencies to dev for now
2017-03-08 13:18:13 -08:00
Davy Duperron 260a141dbe [WIP] Fix comments in template literals (#643)
* Add handleTemplateLiteralComment helper function.

* Fix handleTemplateLiteralComment function.

* Extend handleTemplateLiteralComment to deal with trailing comments 🚀.

* Add test.

* Make handle comments function naming more consistent, fix merge conflicts.

* Update tests.

* Add better comment injection in Template Literal.

* Pass options to attach function.

* Update tests to match new implementation.

* Fix let -> var in findExpressionIndexForComment for NodeJS v4.

* Reorder after merge conflicts.

* Drop old tests for dangling arrays.

* Replace redundant conditional by a boolean 🚀.

* Refactor implementation.
2017-02-23 09:23:56 -08:00
Christopher Chedeau b93a207bb2 Run prettier on 0.17.0 2017-02-15 19:56:11 -08:00
Christopher Chedeau c4b83c7653 Ensure that all comments are printed (#571)
This currently fails for 20 tests. I'm putting this up as a pull request so we can merge it once all the comments are properly printed :)
2017-02-13 09:04:21 -08:00
Christopher Chedeau 6a05a55852 Remove last trailing line for directives-only files (#609)
* Remove last trailing line for directives-only files

There are two hardlines that are added that do not need to.

- The first one is when there's an empty line afterwards, we want to remove it. The solution I opted for to fix this one is to trimRight the originalText so that globally it's never going to return yes for the isNextLineEmpty.
- The second one is at the end of Program, but we already printed it inside of the directive itself, so we can just add a condition to make sure it's only printed when there's a body or a comment, but not a directive.

Fixes #527

* Add comment
2017-02-07 10:39:04 -05:00
Christopher Chedeau df831d7b59 Fix files with only comments on the flow parser (#598)
Babylon has a two top level nodes: File and Program whereas flow just has Program. This causes two things two happen that prevents comments from being displayed:

1) Because there's a single node, none of following/preceding/enclosing exist. We ran into a TOOD case that we now need to fill. We just need to attach comments to the only node we have: the ast.

2) Both the raw comments and the computed comments are set on the `.comments` field of the object, however, it is being reset after calling `attach`, so we lose the computed comments :( The fix is to use a local variable and delete the comments before calling `attach`.
2017-02-04 21:36:29 -05:00
Christopher Chedeau c34013b1ee Run prettier on 0.13.0 (#497) 2017-01-28 07:50:22 -08:00
Christopher Chedeau 6ade2a1e4a Maintain windows line ending (#472)
It's nice that we print line endings in a single place, it was super easy to preserve them :)

Fixes #92
2017-01-26 14:16:42 -08:00
Simon Lydell bb1884320b Use babel-code-frame for syntax errors (#367)
* Use babel-code-frame for syntax errors

* Support the `--color` option more explicitly

* Update rollup config to handle babel-code-frame

* Use exact dependencies
2017-01-23 09:10:51 -08:00
Charles Pick 9a71a907e5 add formatAST() for formatting ASTs directly (#393) 2017-01-22 14:00:23 -08:00
Christopher Chedeau d20a580655 Run prettier on the codebase (#354) 2017-01-20 10:12:37 -08:00
Christopher Chedeau c468fde106 Add debugging support for doc IR (#347)
This PR adds two things:

`--debug-print-doc` command that prints the formatted doc

```js
echo "<div>&lt;</div>" | ./bin/prettier.js --stdin --debug-print-doc
[
  groupConditional(
    group([
      group([ "<", "div", group([ indent(2, []), softline() ]), ">" ]),
      "&lt;",
      "</",
      "div",
      ">"
    ]),
    [
      group([
        group([ "<", "div", group([ indent(2, []), softline() ]), ">" ]),
        "&lt;",
        "</",
        "div",
        ">"
      ]),
      group([
        group([ "<", "div", group([ indent(2, []), softline() ]), ">" ]),
        indent(2, groupBreak([ hardline(), "&lt;" ])),
        hardline(),
        "</",
        "div",
        ">"
      ])
    ]
  ),
  ";",
  hardline()
];
```

The ability to view the IR in real time on the browser display:

![image](https://cloud.githubusercontent.com/assets/197597/22134741/4f172f20-de7e-11e6-84bc-5f813976dc19.png)

The way it works is pretty cool, we take the doc IR and print a valid JavaScript string out of it, that we then send to prettier in order to make it look good :)
2017-01-20 09:54:32 -08:00
Christopher Chedeau d8d5c7bc55 Introduce --parser/parser option and deprecate --flow-parser/useFlowParser (#342)
The previous API was inconsistent. The new one is

```js
--parser flow
--parser babylon

{parser: 'flow'}
{parser: 'babylon'}
```

if we ever want to add new parsers in the future it'll allow that more easily.

I put a console.log in parser.js in both functions and tested that the test suite worked both with and without the change in run_spec. I also tested that both the previous and new command line options are working.

At some point in the future we'll likely want to get rid of the old api but might as well keep supporting it so we don't break anyone for now.
2017-01-19 14:35:12 -08:00
Christopher Chedeau 658998c5b1 Refactor index.js (#340)
Extracted out parse and attachComments. Moved the options normalization in the exported function.

This way, we have a super clean format function :)

```js
function format(text, opts) {
  const ast = parse(text, opts);
  attachComments(text, ast, opts)
  const doc = printAstToDoc(ast, opts)
  const str = printDocToString(doc, opts.printWidth)
  return str;
}
```
2017-01-19 14:18:22 -08:00
Christopher Chedeau aef3e387f8 Extract parser.js (#338)
Before, we would parse things inline in both index.js and run_spec. Extracting it should make it easier to manage and understand what is going on.
2017-01-19 13:23:04 -08:00
Christopher Chedeau ad96fce6c2 Split pp.js into doc-{printer,builders,utils}.js (#334)
- doc-printer.js is now the direct implementation of the Wadler paper
- doc-builders.js are a lot of utils to generate the IR the above file needs
- doc-utils.js are small utils to traverse list of docs.
2017-01-19 12:46:57 -08:00
Christopher Chedeau ab046c6850 Remove Printer module in favor of single function (#333)
I pushed the options handling and doc->string process one level above.
2017-01-19 12:43:10 -08:00
Christopher Chedeau 0f54791582 Run prettier through the codebase (#316)
It's a good idea to run it right after we do a release when the number of outstanding pull requests is low :)
2017-01-18 15:31:46 -08:00
Jeffrey Horn 40973641a3 add version flag (#294)
* add version flag

* set version on the api
2017-01-18 15:45:44 -05:00
Benjamin Tan bc9b1fde19 Add newline after shebang if necessary. (#215) 2017-01-17 17:16:40 -05:00
Christopher Chedeau 05be0eb31b Add flow parser experimental options (#221)
The Nuclide codebase uses features that are still proposals which require a flag to be enabled. Babylon parses them fine without any flags.

Let's enable them by default as it doesn't cost much, you either are using those features and you don't want the parser to break, or you are not and you don't care.

After this and #218, none of the nuclide files are throwing exceptions! (yay!)
2017-01-15 23:46:27 -05:00
Benjamin Tan 3f31a87da1 Remove legacy Recast code and simplify API. (#191) 2017-01-14 23:25:30 -05:00
James Long 3af7da5748 Reprint all the files! 2017-01-13 15:03:53 -05:00
Christopher Chedeau df99ae56b0 Add test for shebang and move to index.js (#170)
When looking into adding a test, I realized that the logic was inside of bin/prettier.js and therefore only applying to the cli. Moving it to index.js and adding a test so that it's more robust :)
2017-01-13 13:39:07 -05:00
James Long 56abf5fc46 Update options to babylon 2017-01-10 17:30:17 -05:00
James Long 4abb8ce544 Support back to node v4 2017-01-10 12:18:22 -05:00
James Long 5c53a2d59c Use babylon directly and convert recast's comment algorith to use our own API 2017-01-09 17:37:45 -05:00
James Long bcd44b4368 Keep blank lines from original source 2017-01-09 09:46:09 -05:00
James Long 7b0ec6d935 Break ternary ops across newlines if needed 2017-01-05 12:32:56 -05:00
James Long 67e2f6d482 Simplify how options are normalized (fixes default options) 2017-01-04 20:45:28 -05:00
James Long 8326963f2d Add option to include spaces inside object/array literals, default to false 2017-01-04 17:23:07 -05:00
James Long c9e24eb477 Add spaces around certain statements, add --write option, and more 2016-12-30 23:01:07 -05:00
James Long 0465bb5790 Add flow parser as an option, default to babylon 2016-12-30 21:23:50 -05:00
James Long e972a7f0b6 Fix object and predicate annotations 2016-12-30 13:32:43 -05:00
James Long 599e5821c1 Optimize jest testing and implement more fixes 2016-12-27 13:28:04 -05:00
James Long 9b4535e9f8 Merge in forked recast printer that uses Wadler's algorithm 2016-12-23 13:38:10 -05:00
James Long 35d8546d27 Add Atom support 2016-11-30 10:05:38 -05:00
James Long d8313b03ce Add ability to call as API 2016-11-29 15:23:00 -05:00