removeXMLComments removes XML comments (<!-- -->) from markdown content while preserving comments that appear within code blocks
(content string)
| 11 | // removeXMLComments removes XML comments (<!-- -->) from markdown content |
| 12 | // while preserving comments that appear within code blocks |
| 13 | func removeXMLComments(content string) string { |
| 14 | xmlCommentsLog.Printf("Removing XML comments from content: %d lines", len(strings.Split(content, "\n"))) |
| 15 | |
| 16 | // Track if we're inside a code block to avoid removing comments in code |
| 17 | lines := strings.Split(content, "\n") |
| 18 | var result []string |
| 19 | inCodeBlock := false |
| 20 | var openMarker string |
| 21 | inXMLComment := false |
| 22 | removedComments := 0 |
| 23 | |
| 24 | for _, line := range lines { |
| 25 | // If we're in a code block, preserve the line as-is (ignore XML comment processing) |
| 26 | // Code blocks that started BEFORE any XML comment take precedence |
| 27 | if inCodeBlock { |
| 28 | trimmedLine := strings.TrimSpace(line) |
| 29 | // Check if this line closes the code block |
| 30 | if isMatchingCodeBlockMarker(trimmedLine, openMarker) { |
| 31 | inCodeBlock = false |
| 32 | openMarker = "" |
| 33 | } |
| 34 | result = append(result, line) |
| 35 | continue |
| 36 | } |
| 37 | |
| 38 | // Process the line for XML comments (not in a code block) |
| 39 | processedLine, wasInComment, isInComment := removeXMLCommentsFromLine(line, inXMLComment) |
| 40 | inXMLComment = isInComment |
| 41 | |
| 42 | // If we're in an XML comment, skip this line entirely (including code block markers) |
| 43 | if wasInComment && isInComment { |
| 44 | // In the middle of a comment, skip the line completely |
| 45 | removedComments++ |
| 46 | continue |
| 47 | } |
| 48 | |
| 49 | // Check for code block markers (3 or more ` or ~) - but only if not in XML comment |
| 50 | trimmedLine := strings.TrimSpace(processedLine) |
| 51 | |
| 52 | if !inCodeBlock && isValidCodeBlockMarker(trimmedLine) { |
| 53 | // Opening a code block |
| 54 | openMarker, _ = extractCodeBlockMarker(trimmedLine) |
| 55 | inCodeBlock = true |
| 56 | xmlCommentsLog.Printf("Detected code block opening with marker: %s", openMarker) |
| 57 | result = append(result, processedLine) |
| 58 | continue |
| 59 | } |
| 60 | |
| 61 | // Handle XML comment boundaries |
| 62 | if !wasInComment && !isInComment { |
| 63 | // Line had no comment involvement, keep as-is |
| 64 | result = append(result, processedLine) |
| 65 | } else if !wasInComment && isInComment { |
| 66 | // Line started a multiline comment, keep the processed part and add empty line |
| 67 | if strings.TrimSpace(processedLine) != "" { |
| 68 | result = append(result, processedLine) |
| 69 | } |
| 70 | result = append(result, "") |