Skip to content

Commit

Permalink
unindenting code blocks and multiline strings
Browse files Browse the repository at this point in the history
  • Loading branch information
viktomas committed Sep 24, 2022
1 parent 48ab64c commit 005ede0
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
26 changes: 26 additions & 0 deletions transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,31 @@ func removeTabFromMultiLevelBulletPoints(from string) string {
}) //TODO make general (it can be merged with previous rule)
}

const multilineBlocks = `\n?(- .*\n(?: .*\n?)+)`

/*
Makes sure that code blocks and multiline blocks are without any extra characters at the start of the line
- ```ts
const hello = "world"
```
is changed to
```ts
const hello = "world"
```
*/
func unindentMultilineStrings(from string) string {
return regexp.MustCompile(multilineBlocks).ReplaceAllStringFunc(from, func(s string) string {
match := regexp.MustCompile(multilineBlocks).FindStringSubmatch(s)
onlyBlock := match[1]
replacement := regexp.MustCompile(`((?m:^[- ] ))`).ReplaceAllString(onlyBlock, "") // remove the leading spaces or dash
replacedString := strings.Replace(s, onlyBlock, replacement, 1)
return fmt.Sprintf("\n%s", replacedString) // add extra new line
})
}

func applyAll(from string, transformers ...func(string) string) string {
result := from
for _, t := range transformers {
Expand All @@ -54,6 +79,7 @@ func transformPage(p page) page {
text := applyAll(
p.text,
removeEmptyBulletPoints,
unindentMultilineStrings,
firstBulletPointsToParagraphs,
secondToFirstBulletPoints,
removeTabFromMultiLevelBulletPoints,
Expand Down
23 changes: 23 additions & 0 deletions transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,27 @@ func TestTransformPage(t *testing.T) {
result := transformText("\t\t- hello\n\t\t\t- world")
require.Equal(t, "\t- hello\n\t\t- world", result)
})
t.Run("removes tabs from all subsequent lines of a bullet point", func(t *testing.T) {
result := transformText(`
- ~~~ts
const hello = "world";
~~~
- single line
- multiple
lines
in
one`)
require.Equal(t, `
~~~ts
const hello = "world";
~~~
single line
multiple
lines
in
one`, result)
})
}

0 comments on commit 005ede0

Please sign in to comment.