htmltools

Various command line tools to transform HTML documents
git clone git://git.entf.net/htmltools
Log | Files | Refs | README | LICENSE

commit db65ee451af79646fc180dbfdfbcf6f78db94497
parent 39f445d0b67c3b736ce6d2e88c47c5dcaa077941
Author: Lukas Henkel <lh@entf.net>
Date:   Mon, 17 Aug 2020 18:48:03 +0200

Add htmlindentheadings

Diffstat:
MMakefile | 2+-
Mgo.mod | 2++
Ahtmlindentheadings/htmlindentheadings.1.scd | 21+++++++++++++++++++++
Ahtmlindentheadings/main.go | 51+++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 75 insertions(+), 1 deletion(-)

diff --git a/Makefile b/Makefile @@ -1,4 +1,4 @@ -TOOLS = htmlremove htmltotext htmlunwrap htmlselect +TOOLS = htmlremove htmltotext htmlunwrap htmlselect htmlindentheadings PREFIX = /usr/local MANS = $(shell find . -name '*.scd' | sed s/\.scd//) diff --git a/go.mod b/go.mod @@ -4,3 +4,5 @@ require ( github.com/andybalholm/cascadia v1.0.0 golang.org/x/net v0.0.0-20190320064053-1272bf9dcd53 ) + +go 1.13 diff --git a/htmlindentheadings/htmlindentheadings.1.scd b/htmlindentheadings/htmlindentheadings.1.scd @@ -0,0 +1,21 @@ +HTMLINDENTHEADINGS(1) + +# NAME + +htmlindentheadings - indents all headings by a specified amount + +# SYNOPSIS + +*htmlindentheadings* INDENT_LEVELS [_FILE_]... + +# DESCRIPTION + +Indents the heading elements (h1 to h7) of all files by the specified level. For +example, if the specified indent level is 2, all h1 elements would become h3 +elements, all h2 elements would become h4 elements and so on. htmlindentheadings +does not create invalid HTML, so it will not go beyond h7. INDENT_LEVELS can +also be a negative number, to decrease the indentation of heading elements. + +# AUTHOR + +Lukas Henkel <lh@entf.net> diff --git a/htmlindentheadings/main.go b/htmlindentheadings/main.go @@ -0,0 +1,51 @@ +package main // import "entf.net/htmltools/htmlindentheadings" + +import ( + "fmt" + "os" + "strconv" + + "golang.org/x/net/html" + + "entf.net/htmltools/shared" +) + +const usage = "usage: htmlindentheadings INDENT_LEVELS [FILES...]" + +func main() { + args := os.Args[1:] + if len(args) == 0 { + fmt.Println(usage) + os.Exit(1) + } + lvls, err := strconv.Atoi(args[0]) + if err != nil { + fmt.Println(usage) + os.Exit(1) + } + shared.Main(args[1:], func(doc *html.Node) { + visit(lvls, doc) + html.Render(os.Stdout, doc) + }) +} + +func indent(lvls int, tag string) string { + l := int(tag[1]) - 48 + l += lvls + if l > 6 { + l = 6 + } + return fmt.Sprintf("h%d", l) +} + +func visit(lvls int, n *html.Node) { + if n.Type == html.ElementNode { + switch n.Data { + case "h1", "h2", "h3", "h4", "h5", "h6": + n.Data = indent(lvls, n.Data) + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + visit(lvls, c) + } +}