ExtractTmdlBlock finds the first line whose left-trimmed text has prefix `query` and returns the "item block": that line plus following lines until the next non-empty line with indent <= the matched line's indent.
(input, query string)
| 8 | // returns the "item block": that line plus following lines until the next non-empty |
| 9 | // line with indent <= the matched line's indent. |
| 10 | func ExtractTmdlBlock(input, query string) string { |
| 11 | trimmedQuery := strings.TrimSpace(query) |
| 12 | if trimmedQuery == "" { |
| 13 | return input |
| 14 | } |
| 15 | |
| 16 | lines := strings.Split(input, "\n") |
| 17 | |
| 18 | found := false |
| 19 | baseIndent := 0 |
| 20 | |
| 21 | var out strings.Builder |
| 22 | |
| 23 | for _, line := range lines { |
| 24 | if !found { |
| 25 | if hasLeftTrimmedPrefix(line, trimmedQuery) { |
| 26 | found = true |
| 27 | baseIndent = indentWidth(line) |
| 28 | |
| 29 | out.WriteString(line) |
| 30 | out.WriteByte('\n') |
| 31 | } |
| 32 | |
| 33 | continue |
| 34 | } |
| 35 | |
| 36 | // Don't let blank lines terminate the block |
| 37 | if strings.TrimSpace(line) != "" && indentWidth(line) <= baseIndent { |
| 38 | break |
| 39 | } |
| 40 | |
| 41 | out.WriteString(line) |
| 42 | out.WriteByte('\n') |
| 43 | } |
| 44 | |
| 45 | if !found { |
| 46 | return "" |
| 47 | } |
| 48 | |
| 49 | return strings.TrimRight(out.String(), " \n\t\r") |
| 50 | } |
| 51 | |
| 52 | func hasLeftTrimmedPrefix(line, prefix string) bool { |
| 53 | trimmed := strings.TrimLeft(line, " \t") |