Skip to content

Commit

Permalink
Make handling of comments more conservative.
Browse files Browse the repository at this point in the history
Also, handle ``` ``` preformatted blocks.
  • Loading branch information
petervdonovan committed Jun 20, 2023
1 parent fd198c1 commit daa0718
Showing 1 changed file with 33 additions and 19 deletions.
52 changes: 33 additions & 19 deletions core/src/main/java/org/lflang/ast/FormattingUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -127,27 +127,41 @@ static String lineWrapComments(List<String> comments, int width, String singleLi
}
/** Wrap lines. Do not merge lines that start with weird characters. */
private static String lineWrapComment(String comment, int width, String singleLineCommentPrefix) {
if (!MULTILINE_COMMENT.matcher(comment).matches()) return comment;
width = Math.max(width, MINIMUM_COMMENT_WIDTH_IN_COLUMNS);
List<List<String>> paragraphs =
Arrays.stream(
comment
.strip()
.replaceAll("^/?((\\*|//|#)\\s*)+", "")
.replaceAll("\\s*\\*/$", "")
.replaceAll("(?<=(\\r\\n|\\r|\\n))\\h*(\\*|//|#)\\h*", "")
.split("(\n\\s*){2,}"))
.map(s -> Arrays.stream(s.split("(\\r\\n|\\r|\\n)\\h*(?=[@#$%^&*\\-+=:;<>/])")))
.map(stream -> stream.map(s -> s.replaceAll("\\s+", " ")))
.map(Stream::toList)
.toList();
if (MULTILINE_COMMENT.matcher(comment).matches()) {
if (paragraphs.size() == 1 && paragraphs.get(0).size() == 1) {
String singleLineRepresentation = String.format("/** %s */", paragraphs.get(0).get(0));
if (singleLineRepresentation.length() <= width) return singleLineRepresentation;
}
return String.format("/**\n%s\n */", lineWrapComment(paragraphs, width, " * "));
var stripped =
comment
.strip()
.replaceAll("^/?((\\*|//|#)\\s*)+", "")
.replaceAll("\\s*\\*/$", "")
.replaceAll("(?<=(\\r\\n|\\r|\\n))\\h*(\\*|//|#)\\h?(\\h*)", "$3");
var preformatted = false;
StringBuilder result = new StringBuilder(stripped.length() * 2);
for (var part : stripped.split("```")) {
result.append(
preformatted
? part.lines()
.skip(1)
.map(it -> " * " + it)
.collect(Collectors.joining("\n", "\n * ```\n", "\n * ```\n"))
: lineWrapComment(
Arrays.stream(part.split("(\n\\s*){2,}"))
.map(
s ->
Arrays.stream(s.split("(\\r\\n|\\r|\\n)\\h*(?=[@#$%^&*\\-+=:;<>/])")))
.map(stream -> stream.map(s -> s.replaceAll("\\s+", " ")))
.map(Stream::toList)
.toList(),
width,
" * "));
preformatted = !preformatted;
}
if (result.indexOf("\n") == -1) {
String singleLineRepresentation =
String.format("/** %s */", result.substring(result.indexOf(" * ") + 3));
if (singleLineRepresentation.length() <= width) return singleLineRepresentation;
}
return lineWrapComment(paragraphs, width, singleLineCommentPrefix + " ");
return String.format("/**\n%s\n */", result);
}

/**
Expand Down

0 comments on commit daa0718

Please sign in to comment.