Skip to content

Commit

Permalink
prettier#15970 markdown: format correctly table when columns are missing
Browse files Browse the repository at this point in the history
  • Loading branch information
Yana Peycheva committed Apr 23, 2024
1 parent 1264a4c commit c6fe8ae
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
12 changes: 12 additions & 0 deletions src/language-markdown/print/table.js
Expand Up @@ -12,10 +12,15 @@ function printTable(path, options, print) {
const { node } = path;

const columnMaxWidths = [];
let columnMaxIndex = 0;

// { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } }
const contents = path.map(
() =>
path.map(({ index: columnIndex }) => {
if (columnIndex > columnMaxIndex) {
columnMaxIndex = columnIndex;
}
const text = printDocToString(print(), options).formatted;
const width = getStringWidth(text);
columnMaxWidths[columnIndex] = Math.max(
Expand All @@ -27,6 +32,13 @@ function printTable(path, options, print) {
"children",
);

// All rows in the table should have the same amount of columns
for (let i = 0; i < contents.length; i++) {
while ((contents[i].length-1) < columnMaxIndex) {
contents[i].push({text: "", width: 0})
}
}

const alignedTable = printTableContents(/* isCompact */ false);
if (options.proseWrap !== "never") {
return [breakParent, alignedTable];
Expand Down
29 changes: 27 additions & 2 deletions tests/format/markdown/table/__snapshots__/jsfmt.spec.js.snap
Expand Up @@ -72,8 +72,8 @@ Y |
=====================================output=====================================
| Foo | Bar |
| --- | --- |
| X |
| Y |
| X | |
| Y | |
================================================================================
`;
Expand Down Expand Up @@ -184,3 +184,28 @@ proseWrap: "always"
================================================================================
`;

exports[`missing-columns.md - {"proseWrap":"always"} format 1`] = `
====================================options=====================================
parsers: ["markdown"]
printWidth: 80
proseWrap: "always"
| printWidth
=====================================input======================================
a | b
:-- | :-- | :--
a | b | c
a || c
a | b
a |
=====================================output=====================================
| a | b | |
| :-- | :-- | :-- |
| a | b | c |
| a | | c |
| a | b | |
| a | | |
================================================================================
`;
6 changes: 6 additions & 0 deletions tests/format/markdown/table/missing-columns.md
@@ -0,0 +1,6 @@
a | b
:-- | :-- | :--
a | b | c
a || c
a | b
a |

0 comments on commit c6fe8ae

Please sign in to comment.