* test: add test cases
* test: add test cases
* fix(javascript): indentation for sub-ternaries
* test: update test cases
* fix: no extra tab for `tabWidth: 4`
* Added prettier layout for class extends and implements
* Added prettier layout for class extends and implements, fix with keeping it in online if it fits
* Added prettier layout for class extends and implements, fixed tests as a side change
* Extends implements comments in same line fix
* Extends implements comments in same line without ugly workaround
* added empty line to test typescript_class/extends_implements.ts
* If only one extends keep old behaviour
* Removed console logs
* Update GraphQL parser
Fixes#3601
This adds support for
- description as strings
- extending all the possible types
- block strings
- allow removing {} if there's no implementation for all graphql types
This is a breaking change but shouldn't be a big issue.
- Empty types are no longer allowed (there's an option to enable it but it hasn't been released yet). The fix is to remove `{}`
Something that hasn't been changed because not released:
- Doesn't support the new `&` separator for implementing multiple interfaces
A bug has been fixed:
- Now properly prints @directives for unions.
* Properly handle triple quotes
* feat(glimmer): initial HTML/Handlebars/Glimmer support
* feat(glimmer): support un-escaped mustache expressions
* fix(glimmer): add 'as |foo|' syntax
* fix(glimmer): support {{foo bar}} syntax
* feat(glimmer): implement all AST types
* feat(glimmer): implement if/else if/else
* test(glimmer): ignore leading/trailing whitespace from AST_COMPARE
* fix(glimmer): do not use trailing slash for void self-closing elements
* chore(build): disable html tests until we can sort out the glimmer dependency
* feat(html): complete rebase on parse5 addition
* Prettier Support For Glimmer VM/Handlebars
Polished Support for Sub Expressions
Added test cases for glimmer primitives
Added support for concat statements
Attempted to make element nodes work
Attempted block statements
Element Nodes are OK
Added support for block elements that are not else-if related
Added support for Else/If
Cleaning up
Rebase
Switch node 4 syntax
Update build
* Removed dead code/partials
* Added new lines to end of test files.
* Rebase after plugin change
* Added ignores to code coverage
There's a lot of demand for vue sfc (#2097). This introduces partial support for them: all the html is printed as is, except for the script and style tags which are printed using prettier. I believe that this should cover a lot of the use cases while being simple to support and if we want we can extend to more in the future.
I copy pasted the html parser used by vue (it's just a single 400 lines file) so that we don't run the chancesof conflicts. I'm also very conservative: I only print the style and script at the top level and for the lang attributes we support.
I expect this to be landable as is and provide value, review welcome :)
* Add an option to utils.printString to use the passed string as-is
* Conform the quotes in Markdown link titles to the singleQuote option
* Don’t use destructuring
* Add some tests
* Format util.js
* Use custom string-printing logic
* Add some more tests
* Fix tests
* Address review comments
* Revert "Format util.js"
This reverts commit d2533ef7fb9231e2f733ece7decac9b923cf6941.
* Revert "Don’t use destructuring"
This reverts commit a5d3b0ac76a076e9a89cffc8cec396cabeacd1ee.
* Revert "Add an option to utils.printString to use the passed string as-is"
This reverts commit ef8e8322609ca3c2808885f3fadcd03f0790078c.
* Even more tests
Based on https://github.com/prettier/prettier/pull/2676
* Thread `path` and `options` through helpers so we don't need to add `needsParens` onto the AST node anymore (mutation)
* Pull test call detection logic out into helper method so it can be re-used for arrow function parens
* Add arrow function parens option implementation (avoid/always)
* Don't break arrow function parens around (done) in test call
* Do not prepend / append with a semicolon the only JSX element in a program
Fixes#3196
* Limit single JSX element without semicolon to Markdown only
* Fix tests
* Don't lowercase element names and attribute names in selectors
https://www.w3.org/TR/css3-selectors/#casesens
> All Selectors syntax is case-insensitive within the ASCII range (i.e.
> [a-z] and [A-Z] are equivalent), except for parts that are not under the
> control of Selectors. The case sensitivity of document language element
> names, attribute names, and attribute values in selectors depends on the
> document language. For example, in HTML, element names are
> case-insensitive, but in XML, they are case-sensitive.
Fixes#3304.
* Fix number normalization in selector interpolation
* Adding --stdin-filepath option in order to enable filetype inference from
stdin
* Fixing typo on the documentation
* Fixing typos - fixing some typos
* Restoring static lib files back since they are artifacts
* fix(jsx): Break opening elements with single text attribute if there's a comment
* Single text attribute with a comment on the JSXElement name
* Consolidate rules of comments in JSX
This was only accounting for a single element in the first group. Now it handles arbitrary elements. Only the last element being capitalized matters.
This fixes one issue in #3107
* Split source elements relative to their language.
Colliding node types which are not source elements in every language.
Example ObjectExpression in JSON / JS
* Node4's Array.prototype.includes
* Ensure there is no confusion
ObjectExpression vs BlockStatement & LabeledStatement
* fixing issue #2984
* removed typescript from test #2984
* prettier
* removed obsolete test copied from another
* added verification parsers
* added new line
* Account for empty lines in member chain
* Add tests
* Account for parens
* Improve tests
* Add some comments
* Remove an outdated comment
* Fix lint errors
* Refactor a line of code
* Add one more comment for clarification
* refactor: extract `splitText`
* fix: respcet CJK width in table
* test: add failing test
* fix: support emoji
* test: add failing test
* feat: support CJK character
* feat: enable adding whitespace between non-CJK/CJK-character by default
* fix: do not print softline at node that is sensitive to its identifier
* fix: treat full-width whitespace as CJK punctuation
* disallow leading/trailing full-width whitespace
* feat: remove `--split-cjk-text` option and enable it by default
* refactor: simplify regex and remove unnecessary `g` flag
* feat(markdown): inital implementation
* feat(markdown): support strong
* fix: add missing default value
* feat(markdown): support inlineCode
* feat: support delete
* feat: support link
* feat: support image
* feat: support blockquote
* feat: support heading
* feat: support code
* feat: support yaml
* feat: support html
* feat: support list
* feat: support thematicBreak
* feat: support table
* feat: support linkReference
* feat: support imageReference
* feat: support definition
* feat: support footnote
* feat: support footnoteReference
* feat: support footnoteDefinition
* test(cli): update snapshots
* refactor: extract SINGLE_LINE_NODE_TYPES
* refactor: printChildren
* fix: correct newlines
* test: add trailing newline
* fix: blockquote formatting
* fix: node types
* fix: break line correctly
* fix: remove unnecessary properties to make AST_COMPARE happy
* fix: escape `|` in tableCell content
* fix: unexpected line break
* fix: ast difference from loose list
* fix: html break lines
* refactor: fix linting
* fix: normalize ast
* fix: escape specific chars
* test: add more tests
* fix: build markdown parser
* chore: remove unnecessary *.log
* fix: escape html entity
* feat: support prettier-ignore
* fix: line break for non-loose listItem
* feat: support formatting `code` based on `lang`
* fix: add `jsx` and `tsx`
* fix: use multiparser
* refactor: fix linting
* test: update test case 😉
* feat: switch to `_` style emphasis
* fix: sequence list should use different prefix
* test: add tests
* fix: do not print additional new line after `prettier-ignore`
* fix(list): enforce `1.` to avoid unnecessary git diff
* feat: enable `commonmark` option
* feat: support `break`
* fix: escape backslash
* refactor: escape html entity using backslash
* fix: respect autolink-style link
* feat: support md`...` and markdown`...`
* docs: replace ands with commas
* fix: respect indented code block
* fix: respect html entity
* docs: add docs for modified MDAST
* fix: inlineCode is breakline-able
* feat: support backtick in inlineCode
* feat: support a-lot-of-backtick in fenced code block
* feat: use `~~~`-style code block in js template
* fix: respect escaped chars
* fix: use `*`-style emphasis for invalid `_`-style output
* test: add test cases
* fix: use `- - -`-style thematicBreak to avoid conflict with yaml
* fix: remain the same content for linkReference identifier
* fix: `inlineCode` gap can be a line break
* fix: `html` should not print trailing spaces if it's in root
* refactor: fix typo
* fix: wrap `definition`'s url if there's whitespace
* fix: remove unnecessary whitespace at the end of paragraph
* fix: fix: remove unnecessary whitespace at the start of paragraph
* fix: setence children length is possible 0
* fix: support continuous ordered list
* fix: do not print addtional hardline after loose list
* fix: use double-backtick style for single-backtick value in inlineCode
* fix: support nested emphasis
* fix: support space-url in link/image
* fix: escape `)` in link/image url
* fix: support single-quote in link/image/definition title
* fix: respect alt in image/imageReference
* fix: use `*`-style thematicBreak in list
* fix: loose/tight list linebreaks
* fix: print third linebreak before indented code block with a tight list in the previous
* test: move bug cases
* fix: remove unnecessary linebreaks
* refactor: fix typo
* Fix TypeScript comment snapshot
* Add failing test for TypeScript method comments
* Remove trailing space in comment
* Add snapshot for comment with many lines
* Add TODO marking potential location for comment re-indentation
* Update snapshot
* Indent comments based on the parent node
* Only adjust indentation if the comment looks like a JSDoc comment
* Only strip leading spaces when adjusting comment indentation
* Update snapshot
* Add test to show incorrect indentation based on parent node
* Update snapshot
* Update snapshot
* Update comment indentation to not rely on the parent node
* Extract code for getting the indent size
* Add test where the parent indentation changes as well
* Fix lint warning regarding lexical declarations within case block
* Update lockfile
* Update snapshot
* Add test case for block comment inside of a method
* Replace spread operator with `concat`
* Use `align` instead of `addAlignmentToDoc`
* Add test for mismatched indentation within JSDoc comment
* Always add a leading space to subsequent lines in a JSDoc comment
* Refactor JSDoc comment printing into a separate function
* Remove unneeded `align`
* Replace `forEach` with `map` for better style
* Only `trimLeft` when the end comment token is on the last line of the comment
* Remove unneeded `docBuilders`
* Add tests for JSDoc comments in JSX
* Update snapshots
* fix: support sequential CallExpressions in member chains
fixes#2832
* test: add additional test cases for sequential CallExpressions
* test: regenerate method-chain snapshot
* Add option to insert @format pragma if absent
prependPragma --> insertPragma
add tst dir, move stripBom, add to README, update snapshots
remove noise from test + update snapshots
use jest@test new functions, update docs, rerun snapshots
fix accidental upgrade to jest@test
update jest-docblock again to latest with strip()
updated snapshot
* updated snapshots
* revert jest dep change
* apply a trim to parsed comments
* remove empty object
* Revert "apply a trim to parsed comments"
This reverts commit 467f71ce5f4b4f8a1b5c4474ee0484bc96c92141.
* rerun snapshots with proper jest version
* pin jest-docblock to latest @test release
* comment out docs for new feature from readme
* remove leading newlines
* ensure blank line between docblock and rest of file
* remove backtick string
* Make production tests always run against dist/
* Try to mock process.stdin instead of get-stream
* fix: mock `get-stream` from `index.js`
* refactor: remove unnecessary variable
* Try `transform: {}` in jest.config.js
* Add comment explaining the unusual get-stream mocking
* Account for empty lines in argument list in typical cases
* Fix build errors
* Fix one more build error
* Refactor
* Have better variable names for printing argument list
* Account for feedback on argument list empty lines
* Improve expanion argument logics
* Add a lot more tests
* Improve a test
* Make code cleaner
* Fix a lint error
* Refactor
* Add one last check
* Refactor
* Split Less and SCSS parsing into different parsers
Now, .less files are always parsed with postcss-less, and .scss files
areare always parsed with postcss-scss. This:
- Is less hacky.
- Is meant to avoid issues like #2829.
- Is probably more performant.
`parser: "postcss"` and `--parser postcss` continue to work like before:
First trying postcss-less, and if that fails, postcss-scss, unless a
regex says that we should try in the opposite order. The new values for
the parser option are "postcss-less" and "postcss-scss".
* Remove postcss from package.json since it is not used
* Rename parser-less to less and parser-scss to scss
* Deprecate parser:postcss in favor of parser:css
* Fix CSS tests
Fixes#2820. While that issue is about `@media (--fooBar)` in
particular, this commit changes to never lowercase stuff starting with
`--` in general, as it seems like those `--customStuff` things can pop
up kind of anywhere.
* Add option to require @prettier or @format pragma
Fixes#2397.
Inspired by `eslint-plugin-prettier` and the discussion in #2397, this
implements requiring a special comment pragma to be present in a file's
first comment in order to be formatted.
This will help large codebases gradually transition to prettier over
time without tons of churn or large code reviews.
I implemented this as a standard prettier "option", not just a typical
`argv` flag, as it is relevant in both the cli and the api. This way it
can be provided programmatically, on the command line, or standardized
in a prettierrc file so like the style options, every user can use this
setting consistently and only apply prettier to relevant files, no
mattier their editor integration.
This requires the pragma begin with `@` (in fact it's inserted if the
user doesn't provide it). Currently the usage implies it must be
"prettier" or "format", but it can technically be any value other than
"none", which is similar to the `trailingCommas` option.
cc @vjeux
* Don't quote anything in runPrettier; this is usually handled by a shell
* Make --require-pragma a boolean option
* Use jest-docblock to find pragmas without parsing the ast
* Clarify docs
* includes -> indexOf
* Move test out of integration
Fixes#2775.
This commit will make conditional expressions to match the behavior of
logical expression in method chains:
```js
(a ? b : c).map()
// if the conditional fits in oneline
(a ? b : c)
.map()
// if the conditional doesn't fit
(a
? b
: c)
.map()
```
Fixes#2777
Since we can't break after `return` and don't add `()` around
ConditionalExpressions' tests, we end up with some weird indentation when
breaking.
* Fix comment style when placed after the test of an if statement
* Add tests
* Do a bit of refactoring
* Fix lint errors
* Handle skipping comments
* Account for multiple-line comments
* Add more tests
* Change function name
* Add more tests
* Refactor
* Add some comments
* Do away with getPreviousNonSpaceNonCommentCharacter
* Improve comment and code on handling if statement comments
* Refactor
* Fix a bug
* src/util: Fix negative number handling
* src/util: Handle decimal numbers with leading plus sign
* src/util: Handle sign symbols before numbers in scientific notation
We used to be very naive and just push all the comments at the top of the class, but it's very brute force (and breaks some flow annotations inside of fb) so we can do better :)
parser-postcss parses `@import` at-rules specially, and unfortunately
buggily. This monkey-patches parser-postcss to parse all at-rules the
same way.
Fixes#2584.
postcss-less bug: https://github.com/shellscape/postcss-less/issues/88
* Use printPropertyKey function to print keys in object type property in TS and Flow
* Remove flow test modification
* Add tests for new object key cases
* Add new test file
* Fix some styles
* Handle closure compiler type cast syntax correctly
Fixes https://github.com/prettier/prettier/issues/1445
* Move closure type cast detection to needParens in fast-path.js
* every => some and added additional check for leading comment
* Add comments showing parser arguments
Since this is how they are invoked, the comments make it easier to maintain.
* Use babylon.parseExpression for JSON
See https://github.com/prettier/prettier/issues/2378#issuecomment-314600778
Note that this doesn't yet print comments:
echo '{/*comment*/"K":"V"}' | ./bin/prettier.js --parser json
* Remove parser-json.js
This reduces duplicate code in the built package.
See https://github.com/prettier/prettier/pull/2476#pullrequestreview-50181398
* Add test with block comment in JSON
* Fix test with block comment in JSON
* Add test with line comment in JSON
* Don't build now-redundant parser-json.js
* Now JSX-mode ternaries only break if they need to.
* Only the outermost ternary in a chain of JSX-mode ternaries will become a group.
* We don't wrap null in parens when breaking JSX-mode ternaries.
This commit also improves the test coverage and explanation in tests/jsx/conditional-expression.js.
* Arrow Function Expressions returning JSX will now add parens when the JSX breaks
* Conditional expressions within (or containing) JSX are formatted in a more natural way (for JSX), especiall when chained
* JSX in logical expressions (|| or &&) is always wrapped in parens
Fixes#2208
Fixes#2353. Use the same printing code for both `WhileStatement` and `DoWhileStatement`.
Fix calculation of `isInsideParenthesis` when printing a `LogicalExpression`. There is
no such thing as `DoStatement` -- it should be `DoWhileStatement`.
* styled components now support css keyword
* added support also for keyframes
* added comment to reflect the new keywords
* modified comment
* ignore css and keyframes when testing ast manipulations
* added also injectGlobal
"Daniel Schafer: Yeah, that's definitely what I'd describe as the canonical style; anytime you have two "things" on a line, use commas, but if you have a newline it's not needed."
The tokens are attached to the location via the prototype (so they are not visible when you JSON.stringify) but the various places where we traverse the ast see them. It causes stack overflows and comments that are not printed because they are attached to tokens instead of real nodes.
Fixes#2302
We had two occurrences on fb codebase where people attached comments on `{' '}` which would be swallowed. Instead of dropping the comments, let's make the algorithm a bit less naive.
It outputted which is completely wrong
```js
<FlatList
renderItem={info => <span>{info.item.widget.missingProp // $FlowExpectedError - bad widgetCount type 6, should be Object
}</span>}
/>;
```
* Add caching for printing
For printing the last argument expansion, we need to print the same node a bit differently with a flag. It's not easy to re-print just the node that is different so we end up printing all the sub-tree twice. Since it is often nested, it means that we run into an exponential complexity.
I finally found a simple solution: we can use a Map to store the nodes and their printed values. It is really cheap to do so (I can't notice a time difference with or without on normal code) and allows us to stop going through the two sub-trees in the bad case.
Fixes#1250
* Update printer.js
* Allow JSX lines to be recombined
* Add test case for `<br />` breaking expression
* Fix issue where JSX whitespace could be dropped
* Newlines were incorrectly being preserved when JSX contained text
* save point
* prettier
* Reverting change to check SOF and EOF
* Removing console.log
* Fixing grouping
* Adding comment output
* Basic comments
* Printing comments
* Getting comments to work
* Adding in basic handling of graphql comments
* Removing parser normalization (i assume it'll be added with language support)
* Lint error
* Reverting special cases
* Dealing with off-by-one error
* Format JSON literals like object literals
Following up on commit a42db30 (https://github.com/prettier/prettier/issues/2173),
this change makes it so that literals in JSON files are formatted as
they would be in an object literal. This normalizes trailing zeroes,
exponential notation, unnecessarily escaped characters, etc.
It works by using babylon to parse literals as expressions, and putting
the result in the AST instead of a `json-literal` node. Since JSON
string literals have to be double-quoted, there's a new
`__prettier__isJson` flag on each node, which is used by the printer to
force double-quotes.
* json: Check options.parser when formatting StringLiteral
This is instead of having a custom AST property. See
https://github.com/prettier/prettier/pull/2181#discussion_r122578251
* multiparser: Use babylon.parseExpression
See https://github.com/prettier/prettier/pull/2181#discussion_r122578354
* json: Don't split result AST node into two
See https://github.com/prettier/prettier/pull/2181#discussion_r122578499
* json: Don't use babylon parser to build expression nodes
See https://github.com/prettier/prettier/pull/2181#discussion_r122579052
* Revert "multiparser: Use babylon.parseExpression"
This reverts commit 3d7a4362880d39fac0cea88b5d0186a29538cf6f.
* Remove unused parameter from babylon parser
* json: Remove unused constructorTypes
* Add support for styled-jsx with expressions
* Lint
* Fix require for Node 4
* Re-create template-literal document when replacing placeholders
* Add support for styled-components with expressions
* Fix merge
* Move css library detection to functions
It turns out that by returning there, we didn't go through the line `delete ast.tokens` and the comments attachment logic would attach it to a random token. It's great that this fail-safe caught this bug!
Fixes#2111
* fix(typescript): remove parens from union types where possible, fixes#1885
* fix(typescript): ensure parenthesis removal is stable
* fix(typescript): don't strip parens around function type
* Add basic styled-jsx parsing
* Use eval("require")
* Remove template literal raw and cooked values when it contains CSS
* Set postcss parser to options and group subtree parts
* Gracefully give up TemplateLiteral formatting when it fails
* Position JSX whitespace at the end of lines
Currently we place JSX whitespace at the beginning of lines.
* Use `isLiteral` when determining JSX whitespace
* Initial GraphQL implementation
This is the bare minimum amount of code to make graphql work. Turns out it's pretty easy to add support for other languages :)
* Fixing support for `graphql` parsing
There was a few structural changes with the addition of CSS and Typescript that we had to take into account.
* Fixing file glob, adding `graphql` to yarn.lock
* Removing extraneous file
* Adding `graphql` parser, style changes
* Splitting out graphql printer
* Removing merge conflict
* Fixing yarn.lock
* Addressing code review, using `createError`
* Adding release config
* Using exact version
* Removing destructuring
It turns out that leading comment is attached to the CallExpression which is the last one and not the first one if they fit in a single line, so we want to not check that one.
Fixes#1892
* 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
This tweaks our JSX formatting to only put a JSX whitespace `{" "}` on a line by itself when it comes before or after a multiline element.
When preceding a text or single line element it appear on the same line as that element.
* Fix unstable JSX output by ensuring we follow `fill` rules.
This changes makes us more strict about ensuring our JSX children follow the alternating content/whitespace format expected by the `fill` primitive.
Previously there were some cases where could get out of sync which would throw out the formatting.
* Simplify whitespace wrangling
# Conflicts:
# src/printer.js
This avoids making it seems like it is indented by 4 characters instead of two. The downside is that if the condition is multi-line it's not going to be properly aligned, but I feel it's a better trade-offs. If you are doing nested ternaries, you usually have small conditions.