diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java index 32b6a7fe8..2164f5bed 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java @@ -240,7 +240,9 @@ private Token readToken() throws LexException { private Function consumeToken() throws LexException { boolean preserveExistingFormatting = preserveExistingFormatting(); - if (input.tryConsumeRegex(NEWLINE_PATTERN)) { + if ((classicJavadoc || preserveExistingFormatting) + ? input.tryConsumeRegex(NEWLINE_PATTERN) + : input.tryConsume("\n")) { somethingSinceNewline = false; return preserveExistingFormatting ? ForcedNewline::new : Whitespace::new; } @@ -292,7 +294,7 @@ private Function consumeToken() throws LexException { if (!somethingSinceNewline && input.tryConsumeRegex(FOOTER_TAG_PATTERN)) { checkMatchingTags(); somethingSinceNewline = true; - return FooterJavadocTagStart::new; + return value -> new FooterJavadocTagStart(WHITESPACE_PATTERN.matcher(value).replaceAll(" ")); } somethingSinceNewline = true; @@ -388,9 +390,9 @@ private Function consumeToken() throws LexException { } else if (input.tryConsumeRegex(BR_PATTERN)) { return BrTag::new; } else if (input.tryConsumeRegex(MOE_BEGIN_STRIP_COMMENT_PATTERN)) { - return MoeBeginStripComment::new; + return value -> new MoeBeginStripComment(WHITESPACE_PATTERN.matcher(value).replaceAll(" ")); } else if (input.tryConsumeRegex(MOE_END_STRIP_COMMENT_PATTERN)) { - return MoeEndStripComment::new; + return value -> new MoeEndStripComment(WHITESPACE_PATTERN.matcher(value).replaceAll(" ")); } else if (input.tryConsumeRegex(HTML_COMMENT_PATTERN)) { return HtmlComment::new; } else if (input.tryConsumeRegex(literalPattern())) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java index d57391859..c5d2c83a8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java @@ -75,6 +75,7 @@ final class JavadocWriter { private final NestingStack.Int postWriteModifiedContinuingListStack = new NestingStack.Int(); private int remainingOnLine; private boolean atStartOfLine; + private boolean pendingListItemSpace; private RequestedWhitespace requestedWhitespace = NONE; private Token requestedMoeBeginStripComment; private String indentForMoeEndStripComment = ""; @@ -127,6 +128,7 @@ void writeBeginJavadoc() { } else { output.append("/// "); remainingOnLine = maxLineLength - blockIndent - 4; + atStartOfLine = true; } } @@ -148,6 +150,7 @@ void writeFooterJavadocTagStart(FooterJavadocTagStart token) { * currently know which of those tags are open. */ continuingListItemOfInnermostList = false; + pendingListItemSpace = false; indentStack.reset(); /* * There's probably no need for this, since its only effect is to disable blank lines in some @@ -224,10 +227,15 @@ void writeListClose(ListCloseTag token) { if (classicJavadoc) { requestBlankLine(); + } else if (token.value().isEmpty()) { + pendingListItemSpace = false; + requestNewline(); + atStartOfLine = false; } } void writeListItemOpen(ListItemOpenTag token) { + pendingListItemSpace = false; requestNewline(); if (continuingListItemOfInnermostList) { @@ -235,6 +243,15 @@ void writeListItemOpen(ListItemOpenTag token) { continuingListItemOfInnermostList = false; indentStack.popUntil(ListItemIndent.class); } + if (!token.value().startsWith("<")) { + // Markdown list item marker (as opposed to HTML
  • /
    /
    ). + String marker = token.value().stripTrailing(); + writeToken(new ListItemOpenTag(marker)); + continuingListItemOfInnermostList = true; + indentStack.push(new ListItemIndent(marker.length() + 1)); + pendingListItemSpace = true; + return; + } writeToken(token); continuingListItemOfInnermostList = true; int indent = token.value().length(); @@ -289,6 +306,8 @@ void writeMarkdownBlockQuoteOpen(MarkdownBlockQuoteOpen token) { void writeMarkdownBlockQuoteClose() { indentStack.popUntil(BlockQuoteIndent.class); + requestNewline(); + atStartOfLine = false; } void writePreOpen(PreOpenTag token) { @@ -336,15 +355,7 @@ void writeMoeEndStripComment(MoeEndStripComment token) { void writeHtmlComment(HtmlComment token) { requestNewline(); - - List lines = token.value().lines().toList(); - writeToken(new HtmlComment(lines.get(0))); - for (String line : lines.subList(1, lines.size())) { - writeNewline(AutoIndent.NO_AUTO_INDENT); - output.append(line); - remainingOnLine -= line.length(); - } - + writeToken(token); requestNewline(); } @@ -369,10 +380,12 @@ void writeLiteral(Literal token) { void writeMarkdownFencedCodeBlock(MarkdownFencedCodeBlock token) { if (!atStartOfLine) { - // A reminder that atStartOfLine is still true after `-␣` because it is a StartOfLineToken. + // A reminder that atStartOfLine is still true after `> ` or `-` because they are + // StartOfLineTokens. requestBlankLine(); } flushWhitespace(); + flushPendingListItemSpace(); output.append(token.start()); token .literal() @@ -393,6 +406,7 @@ void writeMarkdownTable(MarkdownTable token) { requestBlankLine(); } flushWhitespace(); + flushPendingListItemSpace(); List lines = token.value().lines().toList(); output.append(lines.get(0)); for (String line : lines.subList(1, lines.size())) { @@ -432,7 +446,7 @@ private void flushWhitespace() { requestNewline(); } - if (!wroteAnythingSignificant) { + if (!wroteAnythingSignificant || pendingListItemSpace) { requestedWhitespace = NONE; } @@ -458,8 +472,17 @@ private void flushWhitespace() { } } + private void flushPendingListItemSpace() { + if (pendingListItemSpace) { + output.append(" "); + remainingOnLine--; + pendingListItemSpace = false; + } + } + private void writeToken(Token token) { - if (token.value().isEmpty()) { + String value = token.value(); + if (value.isEmpty()) { return; } @@ -479,6 +502,8 @@ private void writeToken(Token token) { remainingOnLine--; } + flushPendingListItemSpace(); + if (requestedMoeBeginStripComment != null) { output.append(requestedMoeBeginStripComment.value()); requestedMoeBeginStripComment = null; @@ -489,7 +514,18 @@ private void writeToken(Token token) { return; } - output.append(token.value()); + int newline = value.indexOf('\n'); + if (newline == -1) { + output.append(value); + remainingOnLine -= value.length(); + } else { + output.append(value, 0, newline); + for (String line : value.substring(newline + 1).split("\n", -1)) { + writeNewline(NO_AUTO_INDENT); + output.append(line); + remainingOnLine -= line.length(); + } + } if (!(token instanceof StartOfLineToken)) { atStartOfLine = false; @@ -505,12 +541,12 @@ private void writeToken(Token token) { * Possibly the "width" question has no right answer: * http://denisbider.blogspot.com/2015/09/when-monospace-fonts-arent-unicode.html */ - remainingOnLine -= token.length(); requestedWhitespace = NONE; wroteAnythingSignificant = true; } private void writeNewlineStart() { + pendingListItemSpace = false; output.append("\n"); appendSpaces(blockIndent + (classicJavadoc ? 1 : 0)); output.append(classicJavadoc ? "*" : "///"); diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java index 241de6fcb..e2c528276 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/MarkdownPositions.java @@ -162,7 +162,7 @@ private boolean visitListItemOrBlockQuote( Pattern startPattern, Function openTokenFactory, Token closeToken) { - Matcher matcher = startPattern.matcher(input).region(start, input.length()); + Matcher matcher = startPattern.matcher(input).region(start, endPosition(node)); verify(matcher.lookingAt()); Token openToken = openTokenFactory.apply(matcher.group(1)); addSpan(node, openToken, closeToken, matcher.start(1)); @@ -346,5 +346,5 @@ private static final class CodeLink extends Link { private static final Pattern BLOCKQUOTE_START_PATTERN = Pattern.compile("(> ?)"); private static final Pattern LIST_ITEM_START_PATTERN = - Pattern.compile("(([-+*]|[0-9]+[.)])(?:\\s|$))"); + Pattern.compile("(([-+*]|[0-9]+[.)])[ \\t]?)"); } diff --git a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java index 5a7b6ae4b..679683f5b 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java @@ -3733,7 +3733,7 @@ void a() {} } @Test - public void markdownEmptyListItemBeforeFencedCodeBlock() throws Exception { + public void markdownEmptyListItemBeforeFencedCodeBlock() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3749,25 +3749,11 @@ class T { void m() {} } """; - // Baseline: currently emits an uncommented ``` line (not valid Java, so idempotency fails). - String expected = - """ - class T { - /// Items: - /// - /// - First item. - /// - - ``` - /// Foo x = new Foo(); - /// ``` - void m() {} - } - """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, input); } @Test - public void markdownEmptyListItemBeforeFencedCodeBlockNoBlankLine() throws Exception { + public void markdownEmptyListItemBeforeFencedCodeBlockNoBlankLine() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3789,17 +3775,18 @@ class T { /// /// - First item. /// - - ``` - /// Foo x = new Foo(); - /// ``` + /// + /// ``` + /// Foo x = new Foo(); + /// ``` void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test - public void markdownEmptyListItemBeforeParagraphAndFooterTag() throws Exception { + public void markdownEmptyListItemBeforeParagraphAndFooterTag() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3815,27 +3802,11 @@ int m() { } } """; - // Baseline: currently splits the comment with an uncommented blank line. - String expected = - """ - class T { - /// - First item. - /// - - - /// - /// Paragraph after. - /// - /// @return value - int m() { - return 0; - } - } - """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, input); } @Test - public void markdownEmptyListItemWithTrailingSpacesAndHtmlBlock() throws Exception { + public void markdownEmptyListItemWithTrailingSpacesAndHtmlBlock() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3846,20 +3817,20 @@ class T { void m() {} } """; - // Baseline: merges the following HTML block onto the empty list item line. String expected = """ class T { /// - First item. - /// -
    After.
    + /// - + ///
    After.
    void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test - public void markdownListItemContentOnNextLine() throws Exception { + public void markdownListItemContentOnNextLine() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3882,36 +3853,33 @@ class T { void m() {} } """; - // Baseline: emits uncommented lines when content starts on the line after `-`. + // TODO: The blank lines after the fenced code block and table come from the pre-existing + // requestBlankLine() at the end of writeMarkdownFencedCodeBlock/writeMarkdownTable, which + // turns this tight list into a loose list. String expected = """ class T { - /// - - foo - /// - - ``` + /// - foo + /// - ``` /// bar(); /// ``` /// /// - - /// - nested - /// - - > quote - /// - - | a | b | + /// - > quote + /// - | a | b | /// | - | - | /// | 1 | 2 | /// - /// -\ttabbed + /// - tabbed void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test - public void markdownFencedCodeBlockInFirstListItem() throws Exception { + public void markdownFencedCodeBlockInFirstListItem() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3922,24 +3890,26 @@ class T { void m() {} } """; - // Baseline: breaks the fenced code block onto a new line with a blank line when on line 1 - // (and re-formatting splits the comment on the empty `-` item). - String expected = + doFormatTest(input, input); + } + + @Test + public void markdownFencedCodeBlockInFirstBlockQuote() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = """ class T { - /// - - /// - /// ``` - /// foo(); - /// ``` + /// > ``` + /// > foo(); + /// > ``` void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, input); } @Test - public void markdownEmptyBlockQuoteBeforeFencedCodeBlock() throws Exception { + public void markdownEmptyBlockQuoteBeforeFencedCodeBlock() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3953,23 +3923,67 @@ class T { void m() {} } """; - // Baseline: merges the fenced code block opening fence onto the empty `>` line. String expected = """ class T { /// Summary. /// - /// > ``` + /// > + /// + /// ``` /// foo(); /// ``` void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); + } + + @Test + public void markdownBlockQuoteBeforeHtmlBlock() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// > quote + ///
    After.
    + void m() {} + } + """; + doFormatTest(input, input); + } + + @Test + public void markdownListItemLineLengthBoundaryAndPreTrailingSpaces() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbb + /// + ///
    +          /// foo  \s
    +          /// 
    + void m() {} + } + """; + String expected = + """ + class T { + /// - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + /// bbbbb + /// + ///
    +          /// foo
    +          /// 
    + void m() {} + } + """; + doFormatTest(input, expected); } @Test - public void markdownUnclosedHtmlTagAcrossNewlines() throws Exception { + public void markdownUnclosedHtmlTagAcrossNewlines() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -3983,25 +3997,24 @@ class T { void m() {} } """; - // Baseline: currently emits uncommented

    outside the comment. String expected = """ class T { ///

               /// foo();
               /// 
    + /// + ///

    /// /// After. void m() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + doFormatTest(input, expected); } @Test - public void markdownUnclosedOpenTagAcrossNewlines() throws Exception { + public void markdownUnclosedOpenTagAcrossNewlines() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -4014,23 +4027,66 @@ class T { void m() {} } """; - // Baseline: currently emits uncommented After. outside the comment. - String expected = + doFormatTest(input, input); + } + + @Test + public void multilineOpenHtmlTag() { + String classicInput = """ class T { - /// Summary. + /** + *

    +           *   foo(   a,   b);
    +           *     bar();
    +           * 
    + * + * + * + *
    a
    + */ + void classic() {} + } + """; + doFormatTest(classicInput, classicInput); + + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String markdownInput = + """ + class T { + ///
    +          ///   foo(   a,   b);
    +          ///     bar();
    +          /// 
    /// ///

    After. - void m() {} + /// class="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa">bbbbb ccccc + void markdown() {} } """; - assertThat(formatter.formatSource(input)).isEqualTo(expected); + String markdownExpected = + """ + class T { + ///

    +          ///   foo(   a,   b);
    +          ///     bar();
    +          /// 
    + /// + ///

    bbbbb + /// ccccc + void markdown() {} + } + """; + doFormatTest(markdownInput, markdownExpected); } @Test - public void markdownMultilineFooterTagAndMoeComment() throws Exception { + public void markdownMultilineFooterTagAndMoeComment() { assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); String input = """ @@ -4051,26 +4107,184 @@ void m() {} } """ .replace("moe", "MOE"); - // Baseline: emits uncommented lines for multiline MOE comments and multiline `@param\n`. String expected = """ class T { /// Summary. /// - /// + /// /// Internal. - /// + /// /// - /// @param - description + /// @param description void m() {} } """ .replace("moe", "MOE"); + doFormatTest(input, expected); + } + + @Test + public void multilineParamNamedLikeHtmlTag() { + String classicInput = + """ + class T { + /** + * Summary. + * + * @param + *

    the proto type + */ +

    void classic() {} + } + """; + String classicExpected = + """ + class T { + /** + * Summary. + * + * @param

    the proto type + */ +

    void classic() {} + } + """; + doFormatTest(classicInput, classicExpected); + + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String markdownInput = + """ + class T { + /// Summary. + /// + /// @param + ///

    the proto type +

    void markdown() {} + } + """; + String markdownExpected = + """ + class T { + /// Summary. + /// + /// @param

    the proto type +

    void markdown() {} + } + """; + doFormatTest(markdownInput, markdownExpected); + } + + @Test + public void markdownListItemStartingWithBlockElement() { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// -

    +          ///   x   y
    +          ///   
    + /// - # Heading + /// -

    para + /// - + /// + ///
    a
    + /// -

    + /// quoted + ///
    + /// - {@snippet : + /// code(); + /// } + /// - + /// - + /// - b + void m() {} + + /// - + /// @return value + int n() { + return 0; + } + + /// - + void o() {} + } + """ + .replace("moe", "MOE"); + // TODO: As in markdownListItemContentOnNextLine, the blank lines after `
    `, heading,
    +    // ``, `
    `, and `{@snippet` come from pre-existing `requestBlankLine()` + // calls on their closing tokens, which turns this tight list into a loose list. + String expected = + """ + class T { + /// -
    +          ///   x   y
    +          ///   
    + /// + /// - # Heading + /// + /// -

    para + /// -

    + /// + ///
    a
    + /// + /// -
    + /// quoted + ///
    + /// + /// - {@snippet : + /// code(); + /// } + /// + /// - + /// - + /// - b + void m() {} + + /// - + /// + /// @return value + int n() { + return 0; + } + + /// - + /// + void o() {} + } + """ + .replace("moe", "MOE"); + doFormatTest(input, expected); + } + + @Test + public void markdownListItemInsideCodeTagForcedNewline() throws Exception { + assume().that(MARKDOWN_JAVADOC_SUPPORTED).isTrue(); + String input = + """ + class T { + /// + /// + /// - + /// b + /// + void m() {} + } + """; + // Pre-existing `writeListItemOpen` adds a newline after `ForcedNewline`, so this input is not + // idempotent; verify `writeNewlineStart` clears the pending marker space so `b` stays at two + // spaces rather than three. + String expected = + """ + class T { + /// + /// + /// + /// - + /// b + /// + void m() {} + } + """; assertThat(formatter.formatSource(input)).isEqualTo(expected); } diff --git a/core/src/test/java/com/google/googlejavaformat/java/javadoc/MarkdownPositionsTest.java b/core/src/test/java/com/google/googlejavaformat/java/javadoc/MarkdownPositionsTest.java index 3b9293469..dd997ad93 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/javadoc/MarkdownPositionsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/javadoc/MarkdownPositionsTest.java @@ -331,7 +331,7 @@ public void emptyListItemBeforeBlankLine() { ImmutableListMultimap expected = ImmutableListMultimap.builder() .put(0, new ListOpenTag("")) - .put(0, new ListItemOpenTag("-\n")) + .put(0, new ListItemOpenTag("-")) .put(1, new ListItemCloseTag("")) .put(1, new ListCloseTag("")) .put(fooStart, new ParagraphOpenTag("")) @@ -353,7 +353,7 @@ public void listItemContentOnNextLine() { ImmutableListMultimap expected = ImmutableListMultimap.builder() .put(0, new ListOpenTag("")) - .put(0, new ListItemOpenTag("-\n")) + .put(0, new ListItemOpenTag("-")) .put(end, new ListItemCloseTag("")) .put(end, new ListCloseTag("")) .build();