diff --git a/src/main/java/com/darkcollective/relix/cli/render/ScriptFormatter.java b/src/main/java/com/darkcollective/relix/cli/render/ScriptFormatter.java index 583559c..989cc74 100644 --- a/src/main/java/com/darkcollective/relix/cli/render/ScriptFormatter.java +++ b/src/main/java/com/darkcollective/relix/cli/render/ScriptFormatter.java @@ -80,8 +80,23 @@ 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 rows) { @@ -89,7 +104,7 @@ private static void align(List rows) { List rules = new ArrayList<>(); List widths = new ArrayList<>(); for (String row : rows) { - List split = cells(row); + List split = cells(cellsOf(row)); boolean rule = split.stream().allMatch(Tables::isRule); cells.add(split); rules.add(rule); @@ -113,6 +128,10 @@ private static void align(List 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()); } } diff --git a/src/test/java/com/darkcollective/relix/cli/command/FmtTest.java b/src/test/java/com/darkcollective/relix/cli/command/FmtTest.java index ac7f1f9..281e423 100644 --- a/src/test/java/com/darkcollective/relix/cli/command/FmtTest.java +++ b/src/test/java/com/darkcollective/relix/cli/command/FmtTest.java @@ -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)")