Skip to content

Commit c14edaf

Browse files
committed
Properly format indented code blocks
If a code block (surrounded by triple backticks) are indented, in other words the code block is placed inside ordered or unordered list, the closing backticks of codeblock should honor the original indentation properly. Signed-off-by: Khosrow Moossavi <khos2ow@gmail.com>
1 parent 5a4a4aa commit c14edaf

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

internal/template/sanitizer.go

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,16 @@ func sanitizeSection(s string, settings *print.Settings) string {
5555
if !strings.HasSuffix(segment, "\n") {
5656
lastbreak = "\n"
5757
}
58-
segment = fmt.Sprintf("```%s%s```", segment, lastbreak)
58+
59+
// Adjust indention and linebreak for indented codeblock
60+
// https://github.com/terraform-docs/terraform-docs/issues/521
61+
lastindent := ""
62+
lines := strings.Split(segment, "\n")
63+
if len(strings.TrimSpace(lines[len(lines)-1])) == 0 {
64+
lastbreak = ""
65+
}
66+
67+
segment = fmt.Sprintf("```%s%s%s```", segment, lastindent, lastbreak)
5968
return segment
6069
},
6170
)

internal/template/testdata/section/complex.expected

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ module "foo_bar" {
2828
}
2929
```
3030

31+
1. Entry one with code
32+
33+
```json
34+
{
35+
"key": "value"
36+
}
37+
```
38+
39+
1. This line should not be broken
40+
3141
Here is some trailing text after code block,
3242
followed by another line of text.
3343

internal/template/testdata/section/complex.golden

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,16 @@ module "foo_bar" {
2828
}
2929
```
3030

31+
1. Entry one with code
32+
33+
```json
34+
{
35+
"key": "value"
36+
}
37+
```
38+
39+
1. This line should not be broken
40+
3141
Here is some trailing text after code block,
3242
followed by another line of text.
3343

0 commit comments

Comments
 (0)