feat: support markdown (#2943)

* 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
master
Ika 2017-10-11 17:46:44 -05:00 committed by Lucas Azzola
parent fa62a438a5
commit 9f6f3e7355
748 changed files with 12856 additions and 25 deletions

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
/node_modules
npm-debug.log
*.log
/errors
/test.js
/test.ts

View File

@ -21,6 +21,7 @@
"cosmiconfig": "3.1.0",
"dashify": "0.2.2",
"diff": "3.2.0",
"escape-string-regexp": "1.0.5",
"esutils": "2.0.2",
"flow-parser": "0.51.0",
"get-stream": "3.0.0",
@ -40,9 +41,12 @@
"postcss-scss": "1.0.0",
"postcss-selector-parser": "2.2.3",
"postcss-values-parser": "1.3.1",
"remark-frontmatter": "1.1.0",
"remark-parse": "4.0.0",
"strip-bom": "3.0.0",
"typescript": "2.5.3",
"typescript-eslint-parser": "git://github.com/eslint/typescript-eslint-parser.git#9c71a627da36e97da52ed2731d58509c952b67ae"
"typescript-eslint-parser": "git://github.com/eslint/typescript-eslint-parser.git#9c71a627da36e97da52ed2731d58509c952b67ae",
"unified": "6.1.5"
},
"devDependencies": {
"babel-cli": "6.24.1",

View File

@ -15,7 +15,8 @@ const parsers = [
"typescript",
"graphql",
"postcss",
"parse5"
"parse5",
"markdown"
];
process.env.PATH += path.delimiter + path.join(rootDir, "node_modules", ".bin");

View File

@ -53,11 +53,17 @@ function massageAST(ast, parent) {
"after",
"trailingComma",
"parent",
"prev"
"prev",
"position"
].forEach(name => {
delete newObj[name];
});
// for markdown codeblock
if (ast.type === "code") {
delete newObj.value;
}
if (
ast.type === "media-query" ||
ast.type === "media-query-list" ||
@ -222,14 +228,15 @@ function massageAST(ast, parent) {
quasis.forEach(q => delete q.value);
}
// styled-components and graphql
// styled-components, graphql, markdown
if (
ast.type === "TaggedTemplateExpression" &&
(ast.tag.type === "MemberExpression" ||
(ast.tag.type === "Identifier" &&
(ast.tag.name === "gql" ||
ast.tag.name === "graphql" ||
ast.tag.name === "css")) ||
ast.tag.name === "css" ||
ast.tag.name === "md")) ||
ast.tag.type === "CallExpression")
) {
newObj.quasi.quasis.forEach(quasi => delete quasi.value);

View File

@ -201,7 +201,8 @@ const detailedOptions = normalizeDetailedOptions({
"less",
"scss",
"json",
"graphql"
"graphql",
"markdown"
],
description: "Which parser to use.",
getter: (value, argv) => (argv["flow-parser"] ? "flow" : value)

View File

@ -14,8 +14,8 @@ function rootIndent() {
return {
indent: 0,
align: {
spaces: 0,
tabs: 0
spaces: "",
tabs: ""
}
};
}
@ -32,8 +32,8 @@ function makeAlign(ind, n) {
return {
indent: 0,
align: {
spaces: 0,
tabs: 0
spaces: "",
tabs: ""
}
};
}
@ -41,8 +41,8 @@ function makeAlign(ind, n) {
return {
indent: ind.indent,
align: {
spaces: ind.align.spaces + n,
tabs: ind.align.tabs + (n ? 1 : 0)
spaces: ind.align.spaces + (typeof n === "number" ? " ".repeat(n) : n),
tabs: ind.align.tabs + (n ? "\t" : "")
}
};
}
@ -401,12 +401,12 @@ function printDocToString(doc, options) {
}
}
const length = ind.indent * options.tabWidth + ind.align.spaces;
const indentLength = ind.indent * options.tabWidth;
const indentString = options.useTabs
? "\t".repeat(ind.indent + ind.align.tabs)
: " ".repeat(length);
? "\t".repeat(ind.indent) + ind.align.tabs
: " ".repeat(indentLength) + ind.align.spaces;
out.push(newLine + indentString);
pos = length;
pos = indentLength + ind.align.spaces.length;
}
break;
}

View File

@ -33,6 +33,59 @@ function getSubtreeParser(path, options) {
case "flow":
case "typescript":
return fromBabylonFlowOrTypeScript(path, options);
case "markdown":
return fromMarkdown(path, options);
}
}
function fromMarkdown(path, options) {
const node = path.getValue();
if (node.type === "code") {
const parser = getParserName(node.lang);
if (parser) {
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(
Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1)
);
return {
options: { parser },
transformDoc: doc => concat([style, node.lang, hardline, doc, style]),
text: node.value
};
}
}
return null;
function getParserName(lang) {
switch (lang) {
case "js":
case "jsx":
case "javascript":
return "babylon";
case "ts":
case "tsx":
case "typescript":
return "typescript";
case "gql":
case "graphql":
return "graphql";
case "css":
return "css";
case "less":
return "less";
case "scss":
return "scss";
case "json":
case "json5":
return "json";
case "md":
case "markdown":
return "markdown";
default:
return null;
}
}
}
@ -92,11 +145,62 @@ function fromBabylonFlowOrTypeScript(path) {
};
}
/**
* md`...`
* markdown`...`
*/
if (
parentParent &&
(parentParent.type === "TaggedTemplateExpression" &&
parent.quasis.length === 1 &&
(parentParent.tag.type === "Identifier" &&
(parentParent.tag.name === "md" ||
parentParent.tag.name === "markdown")))
) {
return {
options: { parser: "markdown", __inJsTemplate: true },
transformDoc: doc =>
concat([
indent(
concat([softline, stripTrailingHardline(escapeBackticks(doc))])
),
softline
]),
// leading whitespaces matter in markdown
text: dedent(parent.quasis[0].value.cooked)
};
}
break;
}
}
}
function dedent(str) {
const spaces = str.match(/\n^( *)/m)[1].length;
return str.replace(new RegExp(`^ {${spaces}}`, "gm"), "").trim();
}
function escapeBackticks(doc) {
return util.mapDoc(doc, currentDoc => {
if (!currentDoc.parts) {
return currentDoc;
}
const parts = [];
currentDoc.parts.forEach(part => {
if (typeof part === "string") {
parts.push(part.replace(/`/g, "\\`"));
} else {
parts.push(part);
}
});
return Object.assign({}, currentDoc, { parts });
});
}
function fromHtmlParser2(path, options) {
const node = path.getValue();

View File

@ -45,6 +45,8 @@ function normalize(options) {
normalized.parser = "graphql";
} else if (/\.json$/.test(filepath)) {
normalized.parser = "json";
} else if (/\.(md|markdown)$/.test(filepath)) {
normalized.parser = "markdown";
}
if (normalized.parser === "json") {

161
src/parser-markdown.js Normal file
View File

@ -0,0 +1,161 @@
"use strict";
const remarkFrontmatter = require("remark-frontmatter");
const remarkParse = require("remark-parse");
const unified = require("unified");
/**
* based on [MDAST](https://github.com/syntax-tree/mdast) with following modifications:
*
* 1. restore unescaped character (Text)
* 2. merge continuous Texts
* 3. transform InlineCode#value into InlineCode#children (Text)
* 4. split Text into Sentence
*
* interface Word { value: string }
* interface Whitespace { value: string }
* interface Sentence { children: Array<Word | Whitespace> }
* interface InlineCode { children: Array<Sentence> }
*/
function parse(text /*, parsers, opts*/) {
const processor = unified()
.use(remarkParse, { footnotes: true, commonmark: true })
.use(remarkFrontmatter, ["yaml"])
.use(restoreUnescapedCharacter(text))
.use(mergeContinuousTexts)
.use(transformInlineCode(text))
.use(splitText);
return processor.runSync(processor.parse(text));
}
function map(ast, handler) {
return (function preorder(node, index, parentNode) {
const newNode = Object.assign({}, handler(node, index, parentNode));
if (newNode.children) {
newNode.children = newNode.children.map((child, index) => {
return preorder(child, index, newNode);
});
}
return newNode;
})(ast, null, null);
}
function transformInlineCode(originalText) {
return () => ast =>
map(ast, node => {
if (node.type !== "inlineCode") {
return node;
}
const rawContent = originalText.slice(
node.position.start.offset,
node.position.end.offset
);
const style = rawContent.match(/^`+/)[0];
return Object.assign({}, node, {
value: node.value.replace(/\s+/g, " "),
children: [
{
type: "text",
value: node.value,
position: {
start: {
line: node.position.start.line,
column: node.position.start.column + style.length,
offset: node.position.start.offset + style.length
},
end: {
line: node.position.end.line,
column: node.position.end.column - style.length,
offset: node.position.end.offset - style.length
}
}
}
]
});
});
}
function restoreUnescapedCharacter(originalText) {
return () => ast =>
map(ast, node => {
return node.type !== "text"
? node
: Object.assign({}, node, {
value:
node.value !== "*" &&
node.value !== "_" && // handle these two cases in printer
node.value.length === 1 &&
node.position.end.offset - node.position.start.offset > 1
? originalText.slice(
node.position.start.offset,
node.position.end.offset
)
: node.value
});
});
}
function mergeContinuousTexts() {
return ast =>
map(ast, node => {
if (!node.children) {
return node;
}
const children = node.children.reduce((current, child) => {
const lastChild = current[current.length - 1];
if (lastChild && lastChild.type === "text" && child.type === "text") {
current.splice(-1, 1, {
type: "text",
value: lastChild.value + child.value,
position: {
start: lastChild.position.start,
end: child.position.end
}
});
} else {
current.push(child);
}
return current;
}, []);
return Object.assign({}, node, { children });
});
}
function splitText() {
return ast =>
map(ast, (node, index, parentNode) => {
if (node.type !== "text") {
return node;
}
let value = node.value;
if (parentNode.type === "paragraph") {
if (index === 0) {
value = value.trimLeft();
}
if (index === parentNode.children.length - 1) {
value = value.trimRight();
}
}
return {
type: "sentence",
position: node.position,
children: value
.split(/(\s+)/g)
.map(
(text, index) =>
index % 2 === 0
? { type: "word", value: text }
: { type: "whitespace", value: " " }
)
.filter(node => node.value !== "")
};
});
}
module.exports = parse;

View File

@ -30,6 +30,9 @@ const parsers = {
},
get json() {
return eval("require")("./parser-babylon");
},
get markdown() {
return eval("require")("./parser-markdown");
}
};

537
src/printer-markdown.js Normal file
View File

@ -0,0 +1,537 @@
"use strict";
const util = require("./util");
const docBuilders = require("./doc-builders");
const concat = docBuilders.concat;
const join = docBuilders.join;
const line = docBuilders.line;
const hardline = docBuilders.hardline;
const fill = docBuilders.fill;
const align = docBuilders.align;
const docPrinter = require("./doc-printer");
const printDocToString = docPrinter.printDocToString;
const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "footnoteDefinition"];
const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
const INLINE_NODE_TYPES = [
"inlineCode",
"emphasis",
"strong",
"delete",
"link",
"linkReference",
"image",
"imageReference",
"footnote",
"footnoteReference",
"sentence",
"whitespace",
"word",
"break"
];
const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat([
"tableCell",
"paragraph"
]);
function genericPrint(path, options, print) {
const node = path.getValue();
if (shouldRemainTheSameContent(path)) {
return concat(
options.originalText
.slice(node.position.start.offset, node.position.end.offset)
.split(/(\s+)/g)
.map((text, index) => (index % 2 === 0 ? text : line))
.filter(doc => doc !== "")
);
}
switch (node.type) {
case "root":
return normalizeDoc(
concat([printChildren(path, options, print), hardline])
);
case "paragraph":
return printChildren(path, options, print, {
postprocessor: fill
});
case "sentence":
return printChildren(path, options, print);
case "word":
return getAncestorNode(path, "inlineCode")
? node.value
: node.value
.replace(/(^|[^\\])\*/g, "$1\\*") // escape all unescaped `*` and `_`
.replace(/\b(^|[^\\])_\b/g, "$1\\_"); // `1_2_3` is not considered emphasis
case "whitespace":
return getAncestorNode(path, SINGLE_LINE_NODE_TYPES) ? " " : line;
case "emphasis": {
const parentNode = path.getParentNode();
const index = parentNode.children.indexOf(node);
const prevNode = parentNode.children[index - 1];
const nextNode = parentNode.children[index + 1];
const hasPrevOrNextWord = // `1*2*3` is considered emphais but `1_2_3` is not
(prevNode &&
prevNode.type === "sentence" &&
prevNode.children.length > 0 &&
prevNode.children[prevNode.children.length - 1].type === "word") ||
(nextNode &&
nextNode.type === "sentence" &&
nextNode.children.length > 0 &&
nextNode.children[0].type === "word");
const style =
hasPrevOrNextWord || getAncestorNode(path, "emphasis") ? "*" : "_";
return concat([style, printChildren(path, options, print), style]);
}
case "strong":
return concat(["**", printChildren(path, options, print), "**"]);
case "delete":
return concat(["~~", printChildren(path, options, print), "~~"]);
case "inlineCode": {
const backtickCount = util.getMaxContinuousCount(node.value, "`");
const style = backtickCount === 1 ? "``" : "`";
const gap = backtickCount ? line : "";
return concat([
style,
gap,
printChildren(path, options, print),
gap,
style
]);
}
case "link":
return options.originalText[node.position.start.offset] === "<"
? concat(["<", node.url, ">"])
: concat([
"[",
printChildren(path, options, print),
"](",
printUrl(node.url, ")"),
node.title ? ` ${printTitle(node.title)}` : "",
")"
]);
case "image":
return concat([
"![",
node.alt || "",
"](",
printUrl(node.url, ")"),
node.title ? ` ${printTitle(node.title)}` : "",
")"
]);
case "blockquote":
return concat(["> ", align("> ", printChildren(path, options, print))]);
case "heading":
return concat([
"#".repeat(node.depth) + " ",
printChildren(path, options, print)
]);
case "code": {
if (/\s/.test(options.originalText[node.position.start.offset])) {
// indented code block
return align(
4,
concat([" ".repeat(4), join(hardline, node.value.split("\n"))])
);
}
// fenced code block
const styleUnit = options.__inJsTemplate ? "~" : "`";
const style = styleUnit.repeat(
Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1)
);
return concat([
style,
node.lang || "",
hardline,
join(hardline, node.value.split("\n")),
hardline,
style
]);
}
case "yaml":
return concat(["---", hardline, node.value, hardline, "---"]);
case "html": {
const parentNode = path.getParentNode();
return parentNode.type === "root" &&
parentNode.children[parentNode.children.length - 1] === node
? node.value.trimRight()
: node.value;
}
case "list": {
const nthSiblingIndex = getNthSiblingIndex(
path,
siblingNode => siblingNode.ordered === node.ordered
);
return printChildren(path, options, print, {
processor: (childPath, index) => {
const prefix = node.ordered
? (index === 0 ? node.start : 1) +
(nthSiblingIndex % 2 === 0 ? ". " : ") ")
: nthSiblingIndex % 2 === 0 ? "- " : "+ ";
return concat([prefix, align(prefix.length, childPath.call(print))]);
}
});
}
case "listItem": {
const prefix =
node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
return concat([
prefix,
align(prefix.length, printChildren(path, options, print))
]);
}
case "thematicBreak":
return getAncestorNode(path, "list") ? "* * *" : "- - -";
case "linkReference":
return concat([
"[",
printChildren(path, options, print),
"]",
node.referenceType === "full"
? concat(["[", node.identifier, "]"])
: node.referenceType === "collapsed" ? "[]" : ""
]);
case "imageReference":
switch (node.referenceType) {
case "full":
return concat(["![", node.alt, "][", node.identifier, "]"]);
default:
return concat([
"![",
node.alt,
"]",
node.referenceType === "collapsed" ? "[]" : ""
]);
}
case "definition":
return concat([
"[",
node.identifier,
"]: ",
printUrl(node.url),
node.title === null ? "" : ` ${printTitle(node.title)}`
]);
case "footnote":
return concat(["[^", printChildren(path, options, print), "]"]);
case "footnoteReference":
return concat(["[^", node.identifier, "]"]);
case "footnoteDefinition":
return concat([
"[^",
node.identifier,
"]: ",
printChildren(path, options, print)
]);
case "table":
return printTable(path, options, print);
case "tableCell":
return printChildren(path, options, print);
case "break":
return concat(["\\", hardline]);
case "tableRow": // handled in "table"
default:
throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
}
}
function getNthSiblingIndex(path, condition) {
condition = condition || (() => true);
const node = path.getValue();
const parentNode = path.getParentNode();
let index = -1;
for (const childNode of parentNode.children) {
if (childNode.type === node.type && condition(childNode)) {
index++;
} else {
index = -1;
}
if (childNode === node) {
return index;
}
}
}
function getAncestorNode(path, typeOrTypes) {
const types = [].concat(typeOrTypes);
let counter = 0;
let ancestorNode;
while ((ancestorNode = path.getParentNode(counter++))) {
if (types.indexOf(ancestorNode.type) !== -1) {
return ancestorNode;
}
}
return null;
}
function printTable(path, options, print) {
const node = path.getValue();
const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
path.map(rowPath => {
const rowContents = [];
rowPath.map(cellPath => {
rowContents.push(
printDocToString(cellPath.call(print), options).formatted
);
}, "children");
contents.push(rowContents);
}, "children");
const columnMaxWidths = contents.reduce(
(currentWidths, rowContents) =>
currentWidths.map((width, columnIndex) =>
Math.max(width, rowContents[columnIndex].length)
),
contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
);
return join(hardline, [
printRow(contents[0]),
printSeparator(),
join(hardline, contents.slice(1).map(printRow))
]);
function printSeparator() {
return concat([
"| ",
join(
" | ",
columnMaxWidths.map((width, index) => {
switch (node.align[index]) {
case "left":
return ":" + "-".repeat(width - 1);
case "right":
return "-".repeat(width - 1) + ":";
case "center":
return ":" + "-".repeat(width - 2) + ":";
default:
return "-".repeat(width);
}
})
),
" |"
]);
}
function printRow(rowContents) {
return concat([
"| ",
join(
" | ",
rowContents.map((rowContent, columnIndex) => {
switch (node.align[columnIndex]) {
case "right":
return alignRight(rowContent, columnMaxWidths[columnIndex]);
case "center":
return alignCenter(rowContent, columnMaxWidths[columnIndex]);
default:
return alignLeft(rowContent, columnMaxWidths[columnIndex]);
}
})
),
" |"
]);
}
function alignLeft(text, width) {
return concat([text, " ".repeat(width - text.length)]);
}
function alignRight(text, width) {
return concat([" ".repeat(width - text.length), text]);
}
function alignCenter(text, width) {
const spaces = width - text.length;
const left = Math.floor(spaces / 2);
const right = spaces - left;
return concat([" ".repeat(left), text, " ".repeat(right)]);
}
}
function printChildren(path, options, print, events) {
events = events || {};
const postprocessor = events.postprocessor || concat;
const processor = events.processor || (childPath => childPath.call(print));
const node = path.getValue();
const parts = [];
let counter = 0;
let lastChildNode;
let prettierIgnore = false;
path.map((childPath, index) => {
const childNode = childPath.getValue();
const result = prettierIgnore
? options.originalText.slice(
childNode.position.start.offset,
childNode.position.end.offset
)
: processor(childPath, index);
prettierIgnore = false;
if (result !== false) {
prettierIgnore = isPrettierIgnore(childNode);
const data = {
parts,
index: counter++,
prevNode: lastChildNode,
parentNode: node,
options
};
if (!shouldNotPrePrintHardline(childNode, data)) {
parts.push(hardline);
if (
shouldPrePrintDoubleHardline(childNode, data) ||
shouldPrePrintTripleHardline(childNode, data)
) {
parts.push(hardline);
}
if (shouldPrePrintTripleHardline(childNode, data)) {
parts.push(hardline);
}
}
parts.push(result);
lastChildNode = childNode;
}
}, "children");
return postprocessor(parts);
}
function isPrettierIgnore(node) {
return (
node.type === "html" && /^<!--\s*prettier-ignore\s*-->$/.test(node.value)
);
}
function shouldNotPrePrintHardline(node, data) {
const isFirstNode = data.parts.length === 0;
const isInlineNode = INLINE_NODE_TYPES.indexOf(node.type) !== -1;
const isInlineHTML =
node.type === "html" &&
INLINE_NODE_WRAPPER_TYPES.indexOf(data.parentNode.type) !== -1;
return isFirstNode || isInlineNode || isInlineHTML;
}
function shouldPrePrintDoubleHardline(node, data) {
const isSequence = (data.prevNode && data.prevNode.type) === node.type;
const isSiblingNode =
isSequence && SIBLING_NODE_TYPES.indexOf(node.type) !== -1;
const isInTightListItem =
data.parentNode.type === "listItem" && !data.parentNode.loose;
const isPrevNodeLooseListItem =
data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode);
return (
isPrevNodeLooseListItem ||
!(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore)
);
}
function shouldPrePrintTripleHardline(node, data) {
const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
const isIndentedCode =
node.type === "code" &&
/\s/.test(data.options.originalText[node.position.start.offset]);
return isPrevNodeList && isIndentedCode;
}
function shouldRemainTheSameContent(path) {
const ancestorNode = getAncestorNode(path, [
"linkReference",
"imageReference"
]);
return (
ancestorNode &&
(ancestorNode.type !== "linkReference" ||
ancestorNode.referenceType !== "full")
);
}
function normalizeDoc(doc) {
return util.mapDoc(doc, currentDoc => {
if (!currentDoc.parts) {
return currentDoc;
}
if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
return currentDoc.parts[0];
}
const parts = [];
currentDoc.parts.forEach(part => {
if (part.type === "concat") {
parts.push.apply(parts, part.parts);
} else if (part !== "") {
parts.push(part);
}
});
return Object.assign({}, currentDoc, {
parts: normalizeParts(parts)
});
});
}
function printUrl(url, dangerousCharOrChars) {
const dangerousChars = [" "].concat(dangerousCharOrChars || []);
return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url)
? `<${url}>`
: url;
}
function printTitle(title) {
return title.includes('"') && !title.includes("'")
? `'${title}'`
: `"${title.replace(/"/g, '\\"')}"`;
}
function normalizeParts(parts) {
return parts.reduce((current, part) => {
const lastPart = current[current.length - 1];
if (typeof lastPart === "string" && typeof part === "string") {
current.splice(-1, 1, lastPart + part);
} else {
current.push(part);
}
return current;
}, []);
}
module.exports = genericPrint;

View File

@ -60,6 +60,8 @@ function getPrintFunction(options) {
case "less":
case "scss":
return require("./printer-postcss");
case "markdown":
return require("./printer-markdown");
default:
return genericPrintNoParens;
}

View File

@ -1,5 +1,7 @@
"use strict";
const escapeStringRegexp = require("escape-string-regexp");
function isExportDeclaration(node) {
if (node) {
switch (node.type) {
@ -605,7 +607,38 @@ function printNumber(rawNumber) {
);
}
function getMaxContinuousCount(str, target) {
const results = str.match(
new RegExp(`(${escapeStringRegexp(target)})+`, "g")
);
if (results === null) {
return 0;
}
return results.reduce(
(maxCount, result) => Math.max(maxCount, result.length / target.length),
0
);
}
function mapDoc(doc, callback) {
if (doc.parts) {
const parts = doc.parts.map(part => mapDoc(part, callback));
return callback(Object.assign({}, doc, { parts }));
}
if (doc.contents) {
const contents = mapDoc(doc.contents, callback);
return callback(Object.assign({}, doc, { contents }));
}
return callback(doc);
}
module.exports = {
mapDoc,
getMaxContinuousCount,
getPrecedence,
shouldFlatten,
isBitwiseOperator,

897
tests/markdown/README.md Normal file
View File

@ -0,0 +1,897 @@
# Prettier
[![Gitter](https://badges.gitter.im/gitterHQ/gitter.svg)](https://gitter.im/jlongster/prettier)
[![Build Status](https://travis-ci.org/prettier/prettier.svg?branch=master)](https://travis-ci.org/prettier/prettier)
[![Codecov](https://img.shields.io/codecov/c/github/prettier/prettier.svg)](https://codecov.io/gh/prettier/prettier)
[![NPM version](https://img.shields.io/npm/v/prettier.svg)](https://www.npmjs.com/package/prettier)
[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](#badge)
Prettier is an opinionated code formatter with support for:
* JavaScript, including [ES2017](https://github.com/tc39/proposals/blob/master/finished-proposals.md)
* [JSX](https://facebook.github.io/jsx/)
* [Flow](https://flow.org/)
* [TypeScript](https://www.typescriptlang.org/)
* CSS, [LESS](http://lesscss.org/), and [SCSS](http://sass-lang.com)
* [JSON](http://json.org/)
* [GraphQL](http://graphql.org/)
It removes all original styling[\*](#styling-footnote) and ensures that all outputted code
conforms to a consistent style. (See this [blog post](http://jlongster.com/A-Prettier-Formatter))
<details>
<summary><strong>Table of Contents</strong></summary>
<!-- Do not edit TOC, regenerate with `yarn toc` -->
<!-- toc -->
* [What does Prettier do?](#what-does-prettier-do)
* [Why Prettier?](#why-prettier)
+ [Building and enforcing a style guide](#building-and-enforcing-a-style-guide)
+ [Helping Newcomers](#helping-newcomers)
+ [Writing code](#writing-code)
+ [Easy to adopt](#easy-to-adopt)
+ [Clean up an existing codebase](#clean-up-an-existing-codebase)
+ [Ride the hype train](#ride-the-hype-train)
* [How does it compare to ESLint (or TSLint, stylelint...)?](#how-does-it-compare-to-eslint-or-tslint-stylelint)
* [Usage](#usage)
+ [CLI](#cli)
+ [ESLint](#eslint)
+ [Pre-commit Hook](#pre-commit-hook)
+ [API](#api)
+ [Excluding code from formatting](#excluding-code-from-formatting)
* [Options](#options)
+ [Print Width](#print-width)
+ [Tab Width](#tab-width)
+ [Tabs](#tabs)
+ [Semicolons](#semicolons)
+ [Quotes](#quotes)
+ [Trailing Commas](#trailing-commas)
+ [Bracket Spacing](#bracket-spacing)
+ [JSX Brackets](#jsx-brackets)
+ [Range](#range)
+ [Parser](#parser)
+ [Filepath](#filepath)
* [Configuration File](#configuration-file)
+ [Basic Configuration](#basic-configuration)
+ [Configuration Overrides](#configuration-overrides)
+ [Configuration Schema](#configuration-schema)
* [Editor Integration](#editor-integration)
+ [Atom](#atom)
+ [Emacs](#emacs)
+ [Vim](#vim)
+ [Visual Studio Code](#visual-studio-code)
+ [Visual Studio](#visual-studio)
+ [Sublime Text](#sublime-text)
+ [JetBrains WebStorm, PHPStorm, PyCharm...](#jetbrains-webstorm-phpstorm-pycharm)
* [Language Support](#language-support)
* [Related Projects](#related-projects)
* [Technical Details](#technical-details)
* [Badge](#badge)
* [Contributing](#contributing)
<!-- tocstop -->
</details>
--------------------------------------------------------------------------------
## What does Prettier do?
Prettier takes your code and reprints it from scratch by taking the line length into account.
For example, take the following code:
```js
foo(arg1, arg2, arg3, arg4);
```
It fits in a single line so it's going to stay as is. However, we've all run into this situation:
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
Suddenly our previous format for calling function breaks down because this is too long. Prettier is going to do the painstaking work of reprinting it like that for you:
```js
foo(
reallyLongArg(),
omgSoManyParameters(),
IShouldRefactorThis(),
isThereSeriouslyAnotherOne()
);
```
Prettier enforces a consistent code **style** (i.e. code formatting that won't affect the AST) across your entire codebase because it disregards the original styling[\*](#styling-footnote) by parsing it away and re-printing the parsed AST with its own rules that take the maximum line length
into account, wrapping code when necessary.
<a href="#styling-footnote" name="styling-footnote">\*</a>_Well actually, some
original styling is preserved when practical—see [empty lines] and [multi-line
objects]._
[empty lines]:Rationale.md#empty-lines
[multi-line objects]:Rationale.md#multi-line-objects
If you want to learn more, these two conference talks are great introductions:
<a href="https://www.youtube.com/watch?v=hkfBvpEfWdA"><img width="298" src="https://cloud.githubusercontent.com/assets/197597/24886367/dda8a6f0-1e08-11e7-865b-22492450f10f.png"></a> <a href="https://www.youtube.com/watch?v=0Q4kUNx85_4"><img width="298" src="https://cloud.githubusercontent.com/assets/197597/24886368/ddacd6f8-1e08-11e7-806a-9febd23cbf47.png"></a>
## Why Prettier?
### Building and enforcing a style guide
By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. It is generally accepted that having a common style guide is valuable for a project and team but getting there is a very painful and unrewarding process. People get very emotional around particular ways of writing code and nobody likes spending time writing and receiving nits.
- “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
- “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going "great debate" that wasted lots of little back and forth bits. It's far easier for us all to agree now: just run Prettier, and go with that style.”
- “Getting tired telling people how to style their product code.”
- “Our top reason was to stop wasting our time debating style nits.”
- “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
- “I don't want anybody to nitpick any other person ever again.”
- “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn't want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
### Helping Newcomers
Prettier is usually introduced by people with experience in the current codebase and JavaScript but the people that disproportionally benefit from it are newcomers to the codebase. One may think that it's only useful for people with very limited programming experience, but we've seen it quicken the ramp up time from experienced engineers joining the company, as they likely used a different coding style before, and developers coming from a different programming language.
- “My motivations for using Prettier are: appearing that I know how to write JavaScript well.”
- “I always put spaces in the wrong place, now I don't have to worry about it anymore.”
- “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.”
- “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.”
### Writing code
What usually happens once people are using Prettier is that they realize that they actually spend a lot of time and mental energy formatting their code. With Prettier editor integration, you can just press that magic key binding and poof, the code is formatted. This is an eye opening experience if anything else.
- “I want to write code. Not spend cycles on formatting.”
- “It removed 5% that sucks in our daily life - aka formatting”
- “We're in 2017 and it's still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“
### Easy to adopt
We've worked very hard to use the least controversial coding styles, went through many rounds of fixing all the edge cases and polished the getting started experience. When you're ready to push Prettier into your codebase, not only should it be painless for you to do it technically but the newly formatted codebase should not generate major controversy and be accepted painlessly by your co-workers.
- “It's low overhead. We were able to throw Prettier at very different kinds of repos without much work.”
- “It's been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I'm happy to say that's not the case.”
- “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.”
- “It's fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.”
- “The biggest benefit for Prettier for us was being able to format the entire code base at once.”
### Clean up an existing codebase
Since coming up with a coding style and enforcing it is a big undertaking, it often slips through the cracks and you are left working on inconsistent codebases. Running Prettier in this case is a quick win, the codebase is now uniform and easier to read without spending hardly any time.
- “Take a look at the code :) I just need to restore sanity.”
- “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.”
### Ride the hype train
Purely technical aspects of the projects aren't the only thing people look into when choosing to adopt Prettier. Who built and uses it and how quickly it spreads through the community has a non-trivial impact.
- “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo”
- “Was built by the same people as React & React Native.”
- “I like to be part of the hot new things.”
- “Because soon enough people are gonna ask for it.”
A few of the [many projects](https://www.npmjs.com/browse/depended/prettier) using Prettier:
<table>
<tr>
<td><p align="center"><a href="https://facebook.github.io/react/"><img src="website/static/images/react-200x100.png" alt="React" width="200" height="100"><br>React</a></p></td>
<td><p align="center"><a href="https://facebook.github.io/jest/"><img src="website/static/images/jest-200x100.png" alt="Jest" width="200" height="100"><br>Jest</a></p></td>
<td><p align="center"><a href="https://yarnpkg.com"><img src="website/static/images/yarn-200x100.png" alt="Yarn" width="200" height="100"><br>Yarn</a></p></td>
</tr>
<tr>
<td><p align="center"><a href="https://babeljs.io/"><img src="website/static/images/babel-200x100.png" alt="Babel" width="200" height="100"><br>Babel</a></p></td>
<td><p align="center"><a href="https://zeit.co/"><img src="website/static/images/zeit-200x100.png" alt="Zeit" width="200" height="100"><br>Zeit</a></p></td>
<td><p align="center"><a href="https://webpack.js.org/api/cli/"><img src="website/static/images/webpack-200x100.png" alt="Webpack-cli" width="200" height="100"><br>Webpack-cli</a></p></td>
</tr>
</table>
## How does it compare to ESLint (or TSLint, stylelint...)?
Linters have two categories of rules:
**Formatting rules**: eg: [max-len](http://eslint.org/docs/rules/max-len), [no-mixed-spaces-and-tabs](http://eslint.org/docs/rules/no-mixed-spaces-and-tabs), [keyword-spacing](http://eslint.org/docs/rules/keyword-spacing), [comma-style](http://eslint.org/docs/rules/comma-style)...
Prettier alleviates the need for this whole category of rules! Prettier is going to reprint the entire program from scratch in a consistent way, so it's not possible for the programmer to make a mistake there anymore :)
**Code-quality rules**: eg [no-unused-vars](http://eslint.org/docs/rules/no-unused-vars), [no-extra-bind](http://eslint.org/docs/rules/no-extra-bind), [no-implicit-globals](http://eslint.org/docs/rules/no-implicit-globals), [prefer-promise-reject-errors](http://eslint.org/docs/rules/prefer-promise-reject-errors)...
Prettier does nothing to help with those kind of rules. They are also the most important ones provided by linters as they are likely to catch real bugs with your code!
## Usage
Install:
```
yarn add prettier --dev --exact
```
You can install it globally if you like:
```
yarn global add prettier
```
*We're using `yarn` but you can use `npm` if you like:*
```
npm install --save-dev --save-exact prettier
# or globally
npm install --global prettier
```
> We recommend pinning an exact version of prettier in your `package.json`
> as we introduce stylistic changes in patch releases.
### CLI
Run Prettier through the CLI with this script. Run it without any
arguments to see the [options](#options).
To format a file in-place, use `--write`. You may want to consider
committing your code before doing that, just in case.
```bash
prettier [opts] [filename ...]
```
In practice, this may look something like:
```bash
prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"
```
Don't forget the quotes around the globs! The quotes make sure that Prettier
expands the globs rather than your shell, for cross-platform usage.
The [glob syntax from the glob module](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer)
is used.
#### `--debug-check`
If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command.
This will cause Prettier to print an error message if it detects that code correctness might have changed.
Note that `--write` cannot be used with `--debug-check`.
#### `--find-config-path` and `--config`
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost
when prettier attempts to look up a [configuration file](#configuration-file). In order to skip this, you may
ask prettier to find the config file once, and re-use it later on.
```bash
prettier --find-config-path ./my/file.js
./my/.prettierrc
```
This will provide you with a path to the configuration file, which you can pass to `--config`:
```bash
prettier --config ./my/.prettierrc --write ./my/file.js
```
You can also use `--config` if your configuration file lives somewhere where prettier cannot find it,
such as a `config/` directory.
If you don't have a configuration file, or want to ignore it if it does exist,
you can pass `--no-config` instead.
#### `--ignore-path`
Path to a file containing patterns that describe files to ignore. By default, prettier looks for `./.prettierignore`.
#### `--require-pragma`
Require a special comment, called a pragma, to be present in the file's first docblock comment in order for prettier to format it.
```js
/**
* @prettier
*/
```
Valid pragmas are `@prettier` and `@format`.
#### `--list-different`
Another useful flag is `--list-different` (or `-l`) which prints the filenames of files that are different from Prettier formatting. If there are differences the script errors out, which is useful in a CI scenario.
```bash
prettier --single-quote --list-different "src/**/*.js"
```
#### `--no-config`
Do not look for a configuration file. The default settings will be used.
#### `--config-precedence`
Defines how config file should be evaluated in combination of CLI options.
**cli-override (default)**
CLI options take precedence over config file
**file-override**
Config file take precedence over CLI options
**prefer-file**
If a config file is found will evaluate it and ignore other CLI options. If no config file is found CLI options will evaluate as normal.
This option adds support to editor integrations where users define their default configuration but want to respect project specific configuration.
#### `--with-node-modules`
Prettier CLI will ignore files located in `node_modules` directory. To opt-out from this behavior use `--with-node-modules` flag.
#### `--write`
This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow.
### ESLint
If you are using ESLint, integrating Prettier to your workflow is straightforward:
Just add Prettier as an ESLint rule using [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier).
```js
yarn add --dev prettier eslint-plugin-prettier
// .eslintrc.json
{
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": "error"
}
}
```
We also recommend that you use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) to disable all the existing formatting rules. It's a one liner that can be added on-top of any existing ESLint configuration.
```
$ yarn add --dev eslint-config-prettier
```
.eslintrc.json:
```json
{
"extends": [
"prettier"
]
}
```
### Pre-commit Hook
You can use Prettier with a pre-commit tool. This can re-format your files that are marked as "staged" via `git add` before you commit.
##### Option 1. [lint-staged](https://github.com/okonet/lint-staged)
Install it along with [husky](https://github.com/typicode/husky):
```bash
yarn add lint-staged husky --dev
```
and add this config to your `package.json`:
```json
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.{js,json,css}": [
"prettier --write",
"git add"
]
}
}
```
There is a limitation where if you stage specific lines this approach will stage the whole file after regardless. See this [issue](https://github.com/okonet/lint-staged/issues/62) for more info.
See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.
##### Option 2. [pre-commit](https://github.com/pre-commit/pre-commit)
Copy the following config into your `.pre-commit-config.yaml` file:
```yaml
- repo: https://github.com/prettier/prettier
sha: '' # Use the sha or tag you want to point at
hooks:
- id: prettier
```
Find more info from [here](http://pre-commit.com).
##### Option 3. bash script
Alternately you can save this script as `.git/hooks/pre-commit` and give it execute permission:
```bash
#!/bin/sh
jsfiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.jsx\?$' | tr '\n' ' ')
[ -z "$jsfiles" ] && exit 0
# Prettify all staged .js files
echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write
# Add back the modified/prettified files to staging
echo "$jsfiles" | xargs git add
exit 0
```
### API
```js
const prettier = require("prettier");
```
#### `prettier.format(source [, options])`
`format` is used to format text using Prettier. [Options](#options) may be provided to override the defaults.
```js
prettier.format("foo ( );", { semi: false });
// -> "foo()"
```
#### `prettier.check(source [, options])`
`check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
#### `prettier.formatWithCursor(source [, options])`
`formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code.
This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
```js
prettier.formatWithCursor(" 1", { cursorOffset: 2 });
// -> { formatted: '1;\n', cursorOffset: 1 }
```
#### `prettier.resolveConfig([filePath [, options]])`
`resolveConfig` can be used to resolve configuration for a given source file.
The function optionally accepts an input file path as an argument, which defaults to the current working directory.
A promise is returned which will resolve to:
* An options object, providing a [config file](#configuration-file) was found.
* `null`, if no file was found.
The promise will be rejected if there was an error parsing the configuration file.
If `options.useCache` is `false`, all caching will be bypassed.
```js
const text = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then(options => {
const formatted = prettier.format(text, options);
})
```
Use `prettier.resolveConfig.sync([filePath [, options]])` if you'd like to use sync version.
#### `prettier.clearConfigCache()`
As you repeatedly call `resolveConfig`, the file system structure will be cached for performance.
This function will clear the cache. Generally this is only needed for editor integrations that
know that the file system has changed since the last format took place.
#### Custom Parser API
If you need to make modifications to the AST (such as codemods), or you want to provide an alternate parser, you can do so by setting the `parser` option to a function. The function signature of the parser function is:
```js
(text: string, parsers: object, options: object) => AST;
```
Prettier's built-in parsers are exposed as properties on the `parsers` argument.
```js
prettier.format("lodash ( )", {
parser(text, { babylon }) {
const ast = babylon(text);
ast.program.body[0].expression.callee.name = "_";
return ast;
}
});
// -> "_();\n"
```
The `--parser` CLI option may be a path to a node.js module exporting a parse function.
### Excluding code from formatting
A JavaScript comment of `// prettier-ignore` will exclude the next node in the abstract syntax tree from formatting.
For example:
```js
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
will be transformed to:
```js
matrix(1, 0, 0, 0, 1, 0, 0, 0, 1);
// prettier-ignore
matrix(
1, 0, 0,
0, 1, 0,
0, 0, 1
)
```
## Options
Prettier ships with a handful of customizable format options, usable in both the CLI and API.
### Print Width
Specify the line length that the printer will wrap on.
> **For readability we recommend against using more than 80 characters:**
>
>In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don't strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.
>
> Prettier, on the other hand, strives to fit the most code into every line. With the print width set to 120, prettier may produce overly compact, or otherwise undesirable code.
Default | CLI Override | API Override
--------|--------------|-------------
`80` | `--print-width <int>` | `printWidth: <int>`
### Tab Width
Specify the number of spaces per indentation-level.
Default | CLI Override | API Override
--------|--------------|-------------
`2` | `--tab-width <int>` | `tabWidth: <int>`
### Tabs
Indent lines with tabs instead of spaces
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--use-tabs` | `useTabs: <bool>`
### Semicolons
Print semicolons at the ends of statements.
Valid options:
* `true` - Add a semicolon at the end of every statement.
* `false` - Only add semicolons at the beginning of lines that may introduce ASI failures.
Default | CLI Override | API Override
--------|--------------|-------------
`true` | `--no-semi` | `semi: <bool>`
### Quotes
Use single quotes instead of double quotes.
Notes:
* Quotes in JSX will always be double and ignore this setting.
* If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: `"I'm double quoted"` results in `"I'm double quoted"` and `"This \"example\" is single quoted"` results in `'This "example" is single quoted'`.
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--single-quote` | `singleQuote: <bool>`
### Trailing Commas
Print trailing commas wherever possible when multi-line. (A single-line array,
for example, never gets trailing commas.)
Valid options:
* `"none"` - No trailing commas.
* `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.)
* `"all"` - Trailing commas wherever possible (including function arguments). This requires node 8 or a [transform](https://babeljs.io/docs/plugins/syntax-trailing-function-commas/).
Default | CLI Override | API Override
--------|--------------|-------------
`"none"` | <code>--trailing-comma <none&#124;es5&#124;all></code> | <code>trailingComma: "<none&#124;es5&#124;all>"</code>
### Bracket Spacing
Print spaces between brackets in object literals.
Valid options:
* `true` - Example: `{ foo: bar }`.
* `false` - Example: `{foo: bar}`.
Default | CLI Override | API Override
--------|--------------|-------------
`true` | `--no-bracket-spacing` | `bracketSpacing: <bool>`
### JSX Brackets
Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line (does not apply to self closing elements).
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>`
### Range
Format only a segment of a file.
These two options can be used to format code starting and ending at a given character offset (inclusive and exclusive, respectively). The range will extend:
* Backwards to the start of the first line containing the selected statement.
* Forwards to the end of the selected statement.
These options cannot be used with `cursorOffset`.
Default | CLI Override | API Override
--------|--------------|-------------
`0` | `--range-start <int>`| `rangeStart: <int>`
`Infinity` | `--range-end <int>` | `rangeEnd: <int>`
### Parser
Specify which parser to use.
Both the `babylon` and `flow` parsers support the same set of JavaScript features (including Flow). Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting.
Built-in parsers:
* [`babylon`](https://github.com/babel/babylon/)
* [`flow`](https://github.com/facebook/flow/tree/master/src/parser)
* [`typescript`](https://github.com/eslint/typescript-eslint-parser) _Since v1.4.0_
* [`postcss`](https://github.com/postcss/postcss) _Since v1.4.0_
* [`json`](https://github.com/babel/babylon/tree/f09eb3200f57ea94d51c2a5b1facf2149fb406bf#babylonparseexpressioncode-options) _Since v1.5.0_
* [`graphql`](https://github.com/graphql/graphql-js/tree/master/src/language) _Since v1.5.0_
[Custom parsers](#custom-parser-api) are also supported. _Since v1.5.0_
Default | CLI Override | API Override
--------|--------------|-------------
`babylon` | `--parser <string>`<br />`--parser ./my-parser` | `parser: "<string>"`<br />`parser: require("./my-parser")`
### Filepath
Specify the input filepath. This will be used to do parser inference.
For example, the following will use `postcss` parser:
```bash
cat foo | prettier --stdin-filepath foo.css
```
Default | CLI Override | API Override
--------|--------------|-------------
None | `--stdin-filepath <string>` | `filepath: "<string>"`
### Require pragma
Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful
when gradually transitioning large, unformatted codebases to prettier.
For example, a file with the following as its first comment will be formatted when `--require-pragma` is supplied:
```js
/**
* @prettier
*/
```
or
```js
/**
* @format
*/
```
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--require-pragma` | `requirePragma: <bool>`
## Configuration File
Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support.
This means you can configure prettier via:
* A `.prettierrc` file, written in YAML or JSON, with optional extensions: `.yaml/.yml/.json/.js`.
* A `prettier.config.js` file that exports an object.
* A `"prettier"` key in your `package.json` file.
The configuration file will be resolved starting from the location of the file being formatted,
and searching up the file tree until a config file is (or isn't) found.
The options to the configuration file are the same the [API options](#options).
### Basic Configuration
JSON:
```json
// .prettierrc
{
"printWidth": 100,
"parser": "flow"
}
```
YAML:
```yaml
# .prettierrc
printWidth: 100
parser: flow
```
### Configuration Overrides
Prettier borrows eslint's [override format](http://eslint.org/docs/user-guide/configuring#example-configuration).
This allows you to apply configuration to specific files.
JSON:
```json
{
"semi": false,
"overrides": [{
"files": "*.test.js",
"options": {
"semi": true
}
}]
}
```
YAML:
```yaml
semi: false
overrides:
- files: "*.test.js"
options:
semi: true
```
`files` is required for each override, and may be a string or array of strings.
`excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.
To get prettier to format its own `.prettierrc` file, you can do:
```json
{
"overrides": [{
"files": ".prettierrc",
"options": { "parser": "json" }
}]
}
```
For more information on how to use the CLI to locate a file, see the [CLI](#cli) section.
### Configuration Schema
If you'd like a JSON schema to validate your configuration, one is available here: http://json.schemastore.org/prettierrc.
## Editor Integration
### Atom
Atom users can simply install the [prettier-atom](https://github.com/prettier/prettier-atom) package and use
`Ctrl+Alt+F` to format a file (or format on save if enabled).
### Emacs
Emacs users should see [this repository](https://github.com/prettier/prettier-emacs)
for on-demand formatting.
### Vim
Vim users can simply install either [sbdchd](https://github.com/sbdchd)/[neoformat](https://github.com/sbdchd/neoformat), [w0rp](https://github.com/w0rp)/[ale](https://github.com/w0rp/ale), or [prettier](https://github.com/prettier)/[vim-prettier](https://github.com/prettier/vim-prettier), for more details see [this directory](https://github.com/prettier/prettier/tree/master/editors/vim).
### Visual Studio Code
Can be installed using the extension sidebar. Search for `Prettier - JavaScript formatter`.
Can also be installed using `ext install prettier-vscode`.
[Check its repository for configuration and shortcuts](https://github.com/prettier/prettier-vscode)
### Visual Studio
Install the [JavaScript Prettier extension](https://github.com/madskristensen/JavaScriptPrettier).
### Sublime Text
Sublime Text support is available through Package Control and
the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in.
### JetBrains WebStorm, PHPStorm, PyCharm...
See the [WebStorm
guide](https://github.com/jlongster/prettier/tree/master/editors/webstorm/README.md).
## Language Support
Prettier attempts to support all JavaScript language features,
including non-standardized ones. By default it uses the
[Babylon](https://github.com/babel/babylon) parser with all language
features enabled, but you can also use the
[Flow](https://github.com/facebook/flow) parser with the
`parser` API or `--parser` CLI [option](#options).
All of JSX and Flow syntax is supported. In fact, the test suite in
`tests/flow` *is* the entire Flow test suite and they all pass.
Prettier also supports [TypeScript](https://www.typescriptlang.org/), CSS, [LESS](http://lesscss.org/), [SCSS](http://sass-lang.com), [JSON](http://json.org/), and [GraphQL](http://graphql.org/).
The minimum version of TypeScript supported is 2.1.3 as it introduces the ability to have leading `|` for type definitions which prettier outputs.
## Related Projects
- [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) plugs Prettier into your ESLint workflow
- [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier
- [`prettier-eslint`](https://github.com/prettier/prettier-eslint)
passes `prettier` output to `eslint --fix`
- [`prettier-stylelint`](https://github.com/hugomrdias/prettier-stylelint)
passes `prettier` output to `stylelint --fix`
- [`prettier-standard`](https://github.com/sheerun/prettier-standard)
uses `prettier` and `prettier-eslint` to format code with standard rules
- [`prettier-standard-formatter`](https://github.com/dtinth/prettier-standard-formatter)
passes `prettier` output to `standard --fix`
- [`prettier-miscellaneous`](https://github.com/arijs/prettier-miscellaneous)
`prettier` with a few minor extra options
- [`neutrino-preset-prettier`](https://github.com/SpencerCDixon/neutrino-preset-prettier) allows you to use Prettier as a Neutrino preset
- [`prettier_d`](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay. It also supports configuration via `.prettierrc`, `package.json`, and `.editorconfig`.
- [`Prettier Bookmarklet`](https://prettier.glitch.me/) provides a bookmarklet and exposes a REST API for Prettier that allows to format CodeMirror editor in your browser
- [`prettier-github`](https://github.com/jgierer12/prettier-github) formats code in GitHub comments
- [`rollup-plugin-prettier`](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup
- [`markdown-magic-prettier`](https://github.com/camacho/markdown-magic-prettier) allows you to use Prettier to format JS [codeblocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/) in Markdown files via [Markdown Magic](https://github.com/DavidWells/markdown-magic)
- [`tslint-plugin-prettier`](https://github.com/ikatyang/tslint-plugin-prettier) runs Prettier as a TSLint rule and reports differences as individual TSLint issues
- [`tslint-config-prettier`](https://github.com/alexjoverm/tslint-config-prettier) use TSLint with Prettier without any conflict
## Technical Details
This printer is a fork of
[recast](https://github.com/benjamn/recast)'s printer with its
algorithm replaced by the one described by Wadler in "[A prettier
printer](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)".
There still may be leftover code from recast that needs to be cleaned
up.
The basic idea is that the printer takes an AST and returns an
intermediate representation of the output, and the printer uses that
to generate a string. The advantage is that the printer can "measure"
the IR and see if the output is going to fit on a line, and break if
not.
This means that most of the logic of printing an AST involves
generating an abstract representation of the output involving certain
commands. For example, `concat(["(", line, arg, line ")"])` would
represent a concatenation of opening parens, an argument, and closing
parens. But if that doesn't fit on one line, the printer can break
where `line` is specified.
More (rough) details can be found in [commands.md](commands.md).
## Badge
Show the world you're using *Prettier* → [![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
```md
[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
```
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).

201
tests/markdown/TEST.md Normal file
View File

@ -0,0 +1,201 @@
[View raw (TEST.md)](https://raw.github.com/adamschwartz/github-markdown-kitchen-sink/master/README.md)
This is a paragraph.
This is a paragraph.
Header 1
========
Header 2
--------
Header 1
========
Header 2
--------
# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6
# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6
# Header 1 #
## Header 2 ##
### Header 3 ###
#### Header 4 ####
##### Header 5 #####
###### Header 6 ######
# Header 1 #
## Header 2 ##
### Header 3 ###
#### Header 4 ####
##### Header 5 #####
###### Header 6 ######
> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
> ## This is a header.
> 1. This is the first list item.
> 2. This is the second list item.
>
> Here's some example code:
>
> Markdown.generate();
> ## This is a header.
> 1. This is the first list item.
> 2. This is the second list item.
>
> Here's some example code:
>
> Markdown.generate();
- Red
- Green
- Blue
+ Red
+ Green
+ Blue
* Red
* Green
* Blue
```markdown
- Red
- Green
- Blue
+ Red
+ Green
+ Blue
* Red
* Green
* Blue
```
1. Buy flour and salt
1. Mix together with water
1. Bake
```markdown
1. Buy flour and salt
1. Mix together with water
1. Bake
```
Paragraph:
Code
<!-- -->
Paragraph:
Code
* * *
***
*****
- - -
---------------------------------------
* * *
***
*****
- - -
---------------------------------------
This is [an example](http://example.com "Example") link.
[This link](http://example.com) has no title attr.
This is [an example] [id] reference-style link.
[id]: http://example.com "Optional Title"
This is [an example](http://example.com "Example") link.
[This link](http://example.com) has no title attr.
This is [an example] [id] reference-style link.
[id]: http://example.com "Optional Title"
*single asterisks*
_single underscores_
**double asterisks**
__double underscores__
*single asterisks*
_single underscores_
**double asterisks**
__double underscores__
This paragraph has some `code` in it.
This paragraph has some `code` in it.
![Alt Text](http://placehold.it/200x50 "Image Title")
![Alt Text](http://placehold.it/200x50 "Image Title")

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1,25 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`nested.md 1`] = `
>>> 123
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> > > 123
`;
exports[`paragraph.md 1`] = `
> This is a long long long long long long long long long long long long long long long paragraph.
> This is a long long long long long long long long long long long long long long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> This is a long long long long long long long long long long long long long
> long long paragraph. This is a long long long long long long long long long
> long long long long long long paragraph.
`;
exports[`simple.md 1`] = `
> 123
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 123
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
>>> 123

View File

@ -0,0 +1,2 @@
> This is a long long long long long long long long long long long long long long long paragraph.
> This is a long long long long long long long long long long long long long long long paragraph.

View File

@ -0,0 +1 @@
> 123

View File

@ -0,0 +1,10 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
123
456
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
123\\
456
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1,2 @@
123
456

View File

@ -0,0 +1,88 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`backtick.md 1`] = `
\`\`\`\`\`\`\`\`\`\`
\`\`\`js
console.log("hello world!");
\`\`\`
\`\`\`\`\`\`\`\`\`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`\`\`\`
\`\`\`js
console.log("hello world!");
\`\`\`
\`\`\`\`
`;
exports[`format.md 1`] = `
\`\`\`js
const foo = 'bar'
console .log( 213 )
\`\`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`\`\`js
const foo = "bar";
console.log(213);
\`\`\`
`;
exports[`indent.md 1`] = `
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
- \`\`\`
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
\`\`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
- \`\`\`
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
\`\`\`
`;
exports[`lang.md 1`] = `
\`\`\`js
console.log("hello world");
\`\`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`\`\`js
console.log("hello world");
\`\`\`
`;
exports[`simple.md 1`] = `
\`\`\`
hello world
\`\`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`\`\`
hello world
\`\`\`
`;

View File

@ -0,0 +1,7 @@
``````````
```js
console.log("hello world!");
```
``````````

View File

@ -0,0 +1,7 @@
```js
const foo = 'bar'
console .log( 213 )
```

View File

@ -0,0 +1,13 @@
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
Indented Code Block
- ```
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
Fenced Code Block
```

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1,3 @@
```js
console.log("hello world");
```

View File

@ -0,0 +1,3 @@
```
hello world
```

View File

@ -0,0 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
[alpha]: http://example.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[alpha]: http://example.com
`;
exports[`space.md 1`] = `
[alpha]: <http://example.com 123> "title"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[alpha]: <http://example.com 123> "title"
`;
exports[`title.md 1`] = `
[alpha]: http://example.com "title"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[alpha]: http://example.com "title"
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[alpha]: http://example.com

View File

@ -0,0 +1 @@
[alpha]: <http://example.com 123> "title"

View File

@ -0,0 +1 @@
[alpha]: http://example.com "title"

View File

@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
~~123~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~123~~
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
~~123~~

View File

@ -0,0 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`asterisk.md 1`] = `
*123*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_123_
`;
exports[`underscore.md 1`] = `
_123_
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_123_
`;

View File

@ -0,0 +1 @@
*123*

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
_123_

View File

@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
[^alpha bravo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[^alpha bravo]
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[^alpha bravo]

View File

@ -0,0 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`long.md 1`] = `
[^hello]: this is a long long long long long long long long long long long long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[^hello]: this is a long long long long long long long long long long long long long paragraph.
`;
exports[`simple.md 1`] = `
[^hello]: world
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[^hello]: world
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[^hello]: this is a long long long long long long long long long long long long long paragraph.

View File

@ -0,0 +1 @@
[^hello]: world

View File

@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
[^hello]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[^hello]
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[^hello]

View File

@ -0,0 +1,32 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`atx.md 1`] = `
# h1
## h2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# h1
## h2
`;
exports[`long-heading.md 1`] = `
# this is a long long long long long long long long long long long long long long heading.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# this is a long long long long long long long long long long long long long long heading.
`;
exports[`setext.md 1`] = `
h1
===
h2
---
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# h1
## h2
`;

View File

@ -0,0 +1,3 @@
# h1
## h2

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
# this is a long long long long long long long long long long long long long long heading.

View File

@ -0,0 +1,5 @@
h1
===
h2
---

View File

@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
<!-- hello world -->
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<!-- hello world -->
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
<!-- hello world -->

View File

@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`indented.md 1`] = `
- 123
- 456
- 789
<!-- prettier-ignore -->
- This is a long long
long long long long
long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 123
- 456
- 789
<!-- prettier-ignore -->
- This is a long long
long long long long
long long paragraph.
`;
exports[`simple.md 1`] = `
<!-- prettier-ignore -->
This is a long long long long long long long long long long long long long long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<!-- prettier-ignore -->
This is a long long long long long long long long long long long long long long long paragraph.
`;

View File

@ -0,0 +1,7 @@
- 123
- 456
- 789
<!-- prettier-ignore -->
- This is a long long
long long long long
long long paragraph.

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1,2 @@
<!-- prettier-ignore -->
This is a long long long long long long long long long long long long long long long paragraph.

View File

@ -0,0 +1,15 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`simple.md 1`] = `
![hello](http://example.com/image.png)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
![hello](http://example.com/image.png)
`;
exports[`title.md 1`] = `
![hello](http://example.com/image.png "title")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
![hello](http://example.com/image.png "title")
`;

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
![hello](http://example.com/image.png)

View File

@ -0,0 +1 @@
![hello](http://example.com/image.png "title")

View File

@ -0,0 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`collapsed.md 1`] = `
![hello][]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
![hello][]
`;
exports[`full.md 1`] = `
![hello][world]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
![hello][world]
`;
exports[`shortcut.md 1`] = `
![hello]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
![hello]
`;

View File

@ -0,0 +1 @@
![hello][]

View File

@ -0,0 +1 @@
![hello][world]

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
![hello]

View File

@ -0,0 +1,38 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`backtick.md 1`] = `
\`\` \`123\` \`\`
\`\`12\`34\`\`
\`\` \`12\`\`
\`\`34\` \`\`
\`\` \`\`\`123\`\`\` \`\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`\` \`123\` \`\`
\`\` 12\`34 \`\`
\`\` \`12 \`\`
\`\` 34\` \`\`
\` \`\`\`123\`\`\` \`
`;
exports[`escape.md 1`] = `
\`1*2*3\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`1*2*3\`
`;
exports[`simple.md 1`] = `
\`123\`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\`123\`
`;

View File

@ -0,0 +1,9 @@
`` `123` ``
``12`34``
`` `12``
``34` ``
`` ```123``` ``

View File

@ -0,0 +1 @@
`1*2*3`

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
`123`

View File

@ -0,0 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`autolink.md 1`] = `
<https://www.example.com>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<https://www.example.com>
`;
exports[`simple.md 1`] = `
[hello](#world)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[hello](#world)
`;
exports[`title.md 1`] = `
[hello](#world "title")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[hello](#world "title")
`;

View File

@ -0,0 +1 @@
<https://www.example.com>

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[hello](#world)

View File

@ -0,0 +1 @@
[hello](#world "title")

View File

@ -0,0 +1,22 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`collapsed.md 1`] = `
[hello][]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[hello][]
`;
exports[`full.md 1`] = `
[hello][world]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[hello][world]
`;
exports[`shortcut.md 1`] = `
[hello]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[hello]
`;

View File

@ -0,0 +1 @@
[hello][]

View File

@ -0,0 +1 @@
[hello][world]

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
[hello]

View File

@ -0,0 +1,119 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`checkbox.md 1`] = `
- [ ] this is a long long long long long long long long long long long long long long paragraph.
- [x] this is a long long long long long long long long long long long long long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- [ ] this is a long long long long long long long long long long long long long
long paragraph.
- [x] this is a long long long long long long long long long long long long long
long paragraph.
`;
exports[`long-paragraph.md 1`] = `
- This is a long long long long long long long long long long long long long long paragraph.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- This is a long long long long long long long long long long long long long
long paragraph.
`;
exports[`loose.md 1`] = `
- 123
- abc
- 456
- def
- 789
- ghi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 123
- abc
- 456
- def
- 789
- ghi
`;
exports[`multiline.md 1`] = `
- 123
456
789
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 123 456 789
`;
exports[`nested.md 1`] = `
- Level 1
- Level 2
- Level 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Level 1
- Level 2
- Level 3
`;
exports[`ordered.md 1`] = `
1. 123
1. 456
1. 789
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. 123
1. 456
1. 789
`;
exports[`separate.md 1`] = `
- 123
- 123
- 123
* 123
* 123
* 123
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 123
- 123
- 123
+ 123
+ 123
+ 123
`;
exports[`simple.md 1`] = `
- 123
- 456
- 789
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- 123
- 456
- 789
`;
exports[`start.md 1`] = `
5. abc
6. def
7. ghi
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5. abc
1. def
1. ghi
`;

View File

@ -0,0 +1,2 @@
- [ ] this is a long long long long long long long long long long long long long long paragraph.
- [x] this is a long long long long long long long long long long long long long long paragraph.

View File

@ -0,0 +1 @@
run_spec(__dirname, { parser: "markdown" });

View File

@ -0,0 +1 @@
- This is a long long long long long long long long long long long long long long paragraph.

View File

@ -0,0 +1,11 @@
- 123
- abc
- 456
- def
- 789
- ghi

View File

@ -0,0 +1,3 @@
- 123
456
789

View File

@ -0,0 +1,3 @@
- Level 1
- Level 2
- Level 3

View File

@ -0,0 +1,3 @@
1. 123
1. 456
1. 789

View File

@ -0,0 +1,7 @@
- 123
- 123
- 123
* 123
* 123
* 123

View File

@ -0,0 +1,3 @@
- 123
- 456
- 789

Some files were not shown because too many files have changed in this diff Show More