Skip to content

Commit

Permalink
Markdown: handle LineEndings.windows correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Jan 30, 2025
1 parent e1c9d2f commit 21d7efe
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
13 changes: 10 additions & 3 deletions scalafmt-core/shared/src/main/scala/org/scalafmt/Scalafmt.scala
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,16 @@ object Scalafmt {
file: String,
range: Set[Range],
): Try[String] =
if (FileOps.isMarkdown(file)) MarkdownParser
.transformMdoc(code)(doFormatOne(_, style, file, range))
else doFormatOne(code, style, file, range)
if (FileOps.isMarkdown(file)) {
val mdocStyle = style.withLineEndings(LineEndings.preserve)
val res = MarkdownParser
.transformMdoc(code)(doFormatOne(_, mdocStyle, file, range))
style.lineEndings match {
case Some(LineEndings.unix) => res.map(_.replaceAll("\r*\n", "\n"))
case Some(LineEndings.windows) => res.map(_.replaceAll("\r*\n", "\r\n"))
case _ => res
}
} else doFormatOne(code, style, file, range)

private[scalafmt] def toInput(code: String, file: String): Input = {
val fileInput = Input.VirtualFile(file, code).withTokenizerOptions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ private[scalafmt] object MarkdownParser {
val parts = MarkdownPart.parse(code, settings)
parts.foreach {
case p: CodeFence if p.getMdocMode.isDefined =>
fmt(p.body.value) match {
case Success(b) => hadFencedParts = true; p.newBody = Some(b.trim)
val old = p.body.value
fmt(old) match {
case Success(b) =>
hadFencedParts = true
p.newBody = Some(if (old.endsWith("\n")) b else b.trim)
case failure => return failure // RETURNING!
}
case _ =>
Expand Down

0 comments on commit 21d7efe

Please sign in to comment.