summaryrefslogtreecommitdiff
path: root/internal/showcase
diff options
context:
space:
mode:
authorPaul Buetow <paul@buetow.org>2025-07-08 23:52:43 +0300
committerPaul Buetow <paul@buetow.org>2025-07-08 23:52:43 +0300
commit6a2c0dc0dc81fcf22c513c5bc54b614ce5fb02f6 (patch)
tree9032866082f10d176ebcc23e439e19c2b29c66a6 /internal/showcase
parent78c8d659e1a642e3938e763065da3a67c35f7183 (diff)
feat: remove unnecessary indentation from code snippets
- Add removeCommonIndentation function to strip common leading whitespace - Code snippets now start at column 0 when possible - Preserves relative indentation within the code - Works with both spaces and tabs 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat (limited to 'internal/showcase')
-rw-r--r--internal/showcase/code_extractor.go79
1 files changed, 79 insertions, 0 deletions
diff --git a/internal/showcase/code_extractor.go b/internal/showcase/code_extractor.go
index 518e590..d43131b 100644
--- a/internal/showcase/code_extractor.go
+++ b/internal/showcase/code_extractor.go
@@ -484,5 +484,84 @@ func stripComments(code string) string {
result = result[:len(result)-1]
}
+ // Remove unnecessary indentation
+ result = removeCommonIndentation(result)
+
return strings.Join(result, "\n")
+}
+
+// removeCommonIndentation removes common leading whitespace from all lines
+func removeCommonIndentation(lines []string) []string {
+ if len(lines) == 0 {
+ return lines
+ }
+
+ // Find the common prefix of whitespace
+ var commonPrefix string
+ firstNonEmpty := -1
+
+ // Find first non-empty line to use as reference
+ for i, line := range lines {
+ if strings.TrimSpace(line) != "" {
+ firstNonEmpty = i
+ break
+ }
+ }
+
+ if firstNonEmpty == -1 {
+ return lines
+ }
+
+ // Get the whitespace prefix of the first non-empty line
+ firstLine := lines[firstNonEmpty]
+ for i, ch := range firstLine {
+ if ch != ' ' && ch != '\t' {
+ commonPrefix = firstLine[:i]
+ break
+ }
+ }
+
+ // If the first line has no indentation, return as-is
+ if commonPrefix == "" {
+ return lines
+ }
+
+ // Find the actual common prefix among all non-empty lines
+ for _, line := range lines {
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+
+ // Reduce commonPrefix to what this line shares
+ for i := 0; i < len(commonPrefix); i++ {
+ if i >= len(line) || line[i] != commonPrefix[i] {
+ commonPrefix = commonPrefix[:i]
+ break
+ }
+ }
+
+ if commonPrefix == "" {
+ break
+ }
+ }
+
+ // If no common prefix found, return as-is
+ if commonPrefix == "" {
+ return lines
+ }
+
+ // Remove common prefix from all lines
+ result := make([]string, len(lines))
+ prefixLen := len(commonPrefix)
+ for i, line := range lines {
+ if strings.TrimSpace(line) == "" {
+ result[i] = ""
+ } else if strings.HasPrefix(line, commonPrefix) {
+ result[i] = line[prefixLen:]
+ } else {
+ result[i] = line
+ }
+ }
+
+ return result
} \ No newline at end of file