Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -80,16 +80,31 @@ static String align(String printed) {
return String.join("\n", lines);
}

/** Whether a line is a table row: cells between pipes, perhaps a {@code --} comment after. */
private static boolean isRow(String line) {
return line.length() >= 2 && line.startsWith("|") && line.endsWith("|");
String cells = cellsOf(line);
return cells.length() >= 2 && cells.startsWith("|") && cells.endsWith("|");
}

/** A row without the {@code --} comment after its last pipe, as the parser reads it. */
private static String cellsOf(String line) {
int last = line.lastIndexOf('|');
return last >= 0 && line.substring(last + 1).strip().startsWith("--")
? line.substring(0, last + 1)
: line;
}

/** The {@code --} comment after a row's last pipe, or {@code ""}. */
private static String commentOf(String line) {
return line.substring(cellsOf(line).length()).strip();
}

private static void align(List<String> rows) {
List<List<String>> cells = new ArrayList<>();
List<Boolean> rules = new ArrayList<>();
List<Integer> widths = new ArrayList<>();
for (String row : rows) {
List<String> split = cells(row);
List<String> split = cells(cellsOf(row));
boolean rule = split.stream().allMatch(Tables::isRule);
cells.add(split);
rules.add(rule);
Expand All @@ -113,6 +128,10 @@ private static void align(List<String> rows) {
line.append(' ').append(cell).append(" ".repeat(widths.get(c) - width(cell))).append(" |");
}
}
String comment = commentOf(rows.get(r));
if (!comment.isEmpty()) {
line.append(" ").append(comment);
}
rows.set(r, line.toString());
}
}
Expand Down
24 changes: 24 additions & 0 deletions src/test/java/com/darkcollective/relix/cli/command/FmtTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,30 @@ void canonical() {
""");
}

@Test
@DisplayName("keeps a comment at the end of a table's row on that row, its columns aligned")
void rowComment() {
String text = """
Goals := [
| id | minute |
|----|--------|
| 1 | 12 | -- the first
| 22 | 5 |
| 3 | 105 | -- and the third
];
""";

assertThat(fmt(text)).isEqualTo("""
Goals := [
| id | minute |
|-----|--------|
| 1 | 12 | -- the first
| 22 | 5 |
| 3 | 105 | -- and the third
];
""");
}

@Test
@Disabled("the engine's ScriptPrinter drops a blank line between a comment and the "
+ "statement or namespace after it (DarkCollective/relix-core#99 follow-up)")
Expand Down
Loading