Skip to content

Commit

Permalink
feat: adjust text block indentation
Browse files Browse the repository at this point in the history
closes #593
  • Loading branch information
jtkiesel authored and clementdessoude committed Aug 15, 2023
1 parent b1b9e7c commit 9f2687d
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 17 deletions.
17 changes: 16 additions & 1 deletion packages/prettier-plugin-java/src/printers/lexical-structure.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { printTokenWithComments } from "./comments/format-comments";
import { join } from "./prettier-builder";
import { BaseCstPrettierPrinter } from "../base-cst-printer";
import {
BooleanLiteralCtx,
Expand All @@ -7,10 +8,24 @@ import {
IToken,
LiteralCtx
} from "java-parser";
import { builders } from "prettier/doc";

const { hardline } = builders;

export class LexicalStructurePrettierVisitor extends BaseCstPrettierPrinter {
literal(ctx: LiteralCtx) {
if (ctx.CharLiteral || ctx.TextBlock || ctx.StringLiteral || ctx.Null) {
if (ctx.TextBlock) {
const lines = ctx.TextBlock[0].image.split("\n");
const open = lines.shift()!;
const baseIndent = Math.min(
...lines.map(line => line.search(/\S/)).filter(indent => indent >= 0)
);
return join(hardline, [
open,
...lines.map(line => line.slice(baseIndent))
]);
}
if (ctx.CharLiteral || ctx.StringLiteral || ctx.Null) {
return printTokenWithComments(this.getSingle(ctx) as IToken);
}
return this.visitSingle(ctx);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ public void print(%s object) {
</body>\r
</html>\r
""";

System.out.println(
// leading comment
"""
abaoeu
euaoeu
aoeu
oaeu
abc""" // trailing comment
);

System.out.println(
"""
abaoeu
euaoeu
aoeu
oaeu
abc"""
);
}

}
Original file line number Diff line number Diff line change
@@ -1,30 +1,50 @@
public class TextBlock {

void method() {
String myTextBlock = """
my text
String myTextBlock =
"""
my text
sentence\"""
sentence\"""

""";
""";

String source =
"""
public void print(%s object) {
System.out.println(Objects.toString(object));
}
""".formatted(
type
);
public void print(%s object) {
System.out.println(Objects.toString(object));
}
""".formatted(type);

String html =
"""
<html>\r
<body>\r
<p>Hello, world</p>\r
</body>\r
</html>\r
""";
<html>\r
<body>\r
<p>Hello, world</p>\r
</body>\r
</html>\r
""";

System.out.println(
// leading comment
"""
abaoeu
euaoeu
aoeu
oaeu
abc""" // trailing comment
);

System.out.println(
"""
abaoeu
euaoeu
aoeu
oaeu
abc"""
);
}
}

0 comments on commit 9f2687d

Please sign in to comment.