@@ -14,6 +14,7 @@ import (
1414 "io"
1515 "os"
1616 "os/exec"
17+ "regexp"
1718 "strings"
1819)
1920
@@ -101,10 +102,7 @@ func FormatXml(reader io.Reader, writer io.Writer, indent string, colors int) er
101102 startTagClosed = false
102103 level ++
103104 case xml.CharData :
104- str := string (typedToken )
105- if strings .TrimSpace (str ) == "" {
106- str = ""
107- }
105+ str := normalizeSpaces (string (typedToken ), indent , level )
108106 hasContent = str != ""
109107 if hasContent && ! startTagClosed {
110108 _ , _ = fmt .Fprint (writer , tagColor (">" ))
@@ -247,10 +245,7 @@ func FormatHtml(reader io.Reader, writer io.Writer, indent string, colors int) e
247245
248246 switch token {
249247 case html .TextToken :
250- str := string (tokenizer .Text ())
251- if strings .TrimSpace (str ) == "" {
252- str = ""
253- }
248+ str := normalizeSpaces (string (tokenizer .Text ()), indent , level )
254249 hasContent = str != ""
255250 _ , _ = fmt .Fprint (writer , str )
256251 case html .StartTagToken , html .SelfClosingTagToken :
@@ -397,3 +392,23 @@ func escapeText(input string) (string, error) {
397392
398393 return result , nil
399394}
395+
396+ func normalizeSpaces (input string , indent string , level int ) string {
397+ if strings .TrimSpace (input ) == "" {
398+ input = ""
399+ }
400+
401+ regexpHead , _ := regexp .Compile ("^ *\n +" )
402+ if regexpHead .MatchString (input ) {
403+ input = strings .TrimLeft (input , " \n " )
404+ input = "\n " + strings .Repeat (indent , level ) + input
405+ }
406+
407+ regexpTail , _ := regexp .Compile ("\n +$" )
408+ if regexpTail .MatchString (input ) {
409+ input = strings .TrimRight (input , " \n " )
410+ input += "\n " + strings .Repeat (indent , level - 1 )
411+ }
412+
413+ return input
414+ }
0 commit comments