1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"\\[\\]\\{#(?<anchor>[^\\}]+?)\\}" as $empty_anchor_regex |
"\\[(?<text>[^\\]]+?)\\]\\{#(?<anchor>[^\\}]+?)\\}" as $anchor_regex |


def transform_anchors_html:
    . | gsub($empty_anchor_regex; "<a name=\"" + .anchor + "\"></a>")
      | gsub($anchor_regex; "<a href=\"#" + .anchor + "\" id=\"" + .anchor + "\">" + .text + "</a>");


def transform_anchors_strip:
    . | gsub($empty_anchor_regex; "")
      | gsub($anchor_regex; .text);


def map_contents_recursively(transformer):
    . + {
        Chapter: (.Chapter + {
            content: .Chapter.content | transformer,
            sub_items: .Chapter.sub_items | map(map_contents_recursively(transformer)),
        }),
    };


def process_command:
    .[0] as $context |
    .[1] as $body |
	# XXX FUTURE: drop sections once mdBook is at 0.5.0 or above in nixpkgs
	$body | (.items? // .sections) |= map(map_contents_recursively(if $context.renderer == "html" then transform_anchors_html else transform_anchors_strip end))
	;

process_command