Skip to content

Commit

Permalink
Handle code blocks in KDoc
Browse files Browse the repository at this point in the history
Summary: This only required cleaning one space to avoid double indenting.

Reviewed By: cgrushko

Differential Revision: D19841993

fbshipit-source-id: c4a4bb5cd374ccdac7c755fde9f5a4d95bf69b97
  • Loading branch information
strulovich authored and facebook-github-bot committed Feb 11, 2020
1 parent 3302a6d commit 733c7d9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
5 changes: 2 additions & 3 deletions core/src/main/java/com/facebook/ktfmt/kdoc/KDocFormatter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ import org.jetbrains.kotlin.lexer.KtTokens.WHITE_SPACE

import com.google.common.collect.ImmutableList
import com.intellij.psi.tree.IElementType
import java.util.regex.Matcher
import java.util.regex.Pattern
import org.jetbrains.kotlin.kdoc.lexer.KDocLexer
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens

Expand Down Expand Up @@ -86,7 +84,8 @@ object KDocFormatter {
} else if (tokenType === KDocTokens.TAG_NAME) {
newTokensBuilder.add(Token(LITERAL, tokenText.trim { it <= ' ' }))
} else if (tokenType === KDocTokens.CODE_BLOCK_TEXT) {
newTokensBuilder.add(Token(LITERAL, tokenText))
val trimmedFirstSpaceText = if (tokenText.first() == ' ') tokenText.substring(1) else tokenText
newTokensBuilder.add(Token(LITERAL, trimmedFirstSpaceText))
} else if (tokenType === KDocTokens.MARKDOWN_INLINE_LINK) {
newTokensBuilder.add(Token(LITERAL, tokenText))
} else if (tokenType === KDocTokens.MARKDOWN_LINK) {
Expand Down
17 changes: 17 additions & 0 deletions core/src/test/java/com/facebook/ktfmt/FormatterKtTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -1695,6 +1695,23 @@ class FormatterKtTest {
|class MyClass {}
|""".trimMargin())

@Test
fun `handle KDoc with code examples`() = assertFormatted(
"""
|/**
| * This is how you write a simple hello world in Kotlin:
| *
| * ```
| * fun main(args: Array<String>) {
| * println("Hello World!")
| * }
| * ```
| *
| * Amazing ah?
| */
|class MyClass {}
|""".trimMargin())

/** Verifies the given code passes through formatting, and stays the same at the end */
private fun assertFormatted(code: String, maxWidth: Int = DEFAULT_MAX_WIDTH) {
assertThatFormatting(code, maxWidth).isEqualTo(code)
Expand Down

0 comments on commit 733c7d9

Please sign in to comment.