github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/domclean2/09_reformat_indent.go (about)

     1  package domclean2
     2  
     3  import (
     4  	"log"
     5  	"strings"
     6  
     7  	"github.com/pbberlin/tools/net/http/dom"
     8  	"golang.org/x/net/html"
     9  )
    10  
    11  func reIndent(n *html.Node, lvl int) {
    12  
    13  	if lvl > cScaffoldLvls && n.Parent == nil {
    14  		bb := dom.PrintSubtree(n)
    15  		_ = bb
    16  		// log.Printf("%s", bb.Bytes())
    17  		hint := ""
    18  		if ml3[n] > 0 {
    19  			hint = "   from ml3"
    20  		}
    21  		log.Print("reIndent: no parent ", hint)
    22  		return
    23  	}
    24  
    25  	// Before children processing
    26  	switch n.Type {
    27  	case html.ElementNode:
    28  		if lvl > cScaffoldLvls && n.Parent.Type == html.ElementNode {
    29  			ind := strings.Repeat("\t", lvl-2)
    30  			dom.InsertBefore(n, &html.Node{Type: html.TextNode, Data: "\n" + ind})
    31  		}
    32  	case html.CommentNode:
    33  		dom.InsertBefore(n, &html.Node{Type: html.TextNode, Data: "\n"})
    34  	case html.TextNode:
    35  		n.Data = strings.TrimSpace(n.Data) + " "
    36  		if !strings.HasPrefix(n.Data, ",") && !strings.HasPrefix(n.Data, ".") {
    37  			n.Data = " " + n.Data
    38  		}
    39  		// link texts without trailing space
    40  		if n.Parent != nil && n.Parent.Data == "a" {
    41  			n.Data = strings.TrimSpace(n.Data)
    42  		}
    43  	}
    44  
    45  	// Children
    46  	for c := n.FirstChild; c != nil; c = c.NextSibling {
    47  		reIndent(c, lvl+1)
    48  	}
    49  
    50  	// After children processing
    51  	switch n.Type {
    52  	case html.ElementNode:
    53  		// I dont know why,
    54  		// but this needs to happend AFTER the children
    55  		if lvl > cScaffoldLvls && n.Parent.Type == html.ElementNode {
    56  			ind := strings.Repeat("\t", lvl-2)
    57  			ind = "\n" + ind
    58  			// link texts without new line
    59  			if n.Data == "a" {
    60  				ind = ""
    61  			}
    62  			if n.LastChild != nil {
    63  				dom.InsertAfter(n.LastChild, &html.Node{Type: html.TextNode, Data: ind})
    64  			}
    65  		}
    66  	}
    67  
    68  }