### Install pandocfilters using setup.py Source: https://github.com/jgm/pandocfilters/blob/master/README.rst Installs the pandocfilters module by running the setup.py script from the current directory. ```bash python setup.py install ``` -------------------------------- ### Install pandocfilters using pip Source: https://github.com/jgm/pandocfilters/blob/master/README.rst Installs the pandocfilters module from the Python Package Index (PyPI) using pip. ```bash pip install pandocfilters ``` -------------------------------- ### nwdiag: Peer Networks Example Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md Demonstrates connecting peer networks in nwdiag. This example shows an internet cloud connected to a router, which then connects to a network segment. ```nwdiag inet [shape = cloud]; inet -- router; network { router; web01; web02; } ``` -------------------------------- ### seqdiag: Simple Sequence Diagram Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md This seqdiag example creates a simple sequence diagram showing a browser interacting with a web server and a database. It illustrates request/response cycles. ```seqdiag browser -> webserver [label = "GET /index.html"]; browser <-- webserver; browser -> webserver [label = "POST /blog/comment"]; webserver -> database [label = "INSERT comment"]; webserver <-- database; browser <-- webserver; ``` -------------------------------- ### rackdiag: Multiple Racks Layout Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md This rackdiag example illustrates how to define and lay out multiple racks, specifying their height (U) and the equipment within each rack, including their dimensions. ```rackdiag // define 1st rack rack { 16U; // define rack items 1: UPS [2U]; 3: DB Server 4: Web Server 5: Web Server 6: Web Server 7: Load Balancer 8: L3 Switch } // define 2nd rack rack { 12U; // define rack items 1: UPS [2U]; 3: DB Server 4: Web Server 5: Web Server 6: Web Server 7: Load Balancer 8: L3 Switch } ``` -------------------------------- ### actdiag: Simple Flow Diagram Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md An example of an actdiag diagram illustrating a simple process flow with user and actdiag lanes. It shows the sequence of actions from writing to image conversion. ```actdiag write -> convert -> image lane user { label = "User" write [label = "Writing reST"]; image [label = "Get diagram IMAGE"]; } lane actdiag { convert [label = "Convert reST to Image"]; } ``` -------------------------------- ### Generate ABC Notation from Text Source: https://github.com/jgm/pandocfilters/blob/master/examples/abc-sample.md This snippet shows how to take raw text input and format it directly into ABC music notation. It's useful for direct conversion or generation of ABC files. ```abc X:7 T:Qui Tolis (Trio) C:André Raison M:3/4 L:1/4 Q:1/4=92 %%staves {(Pos1 Pos2) Trompette} K:F % V:Pos1 %%MIDI program 78 "Positif"x3 |x3 |c'>ba|Pga/g/f|:g2a |ba2 |g2c- |c2P=B |c>de |fga | V:Pos2 %%MIDI program 78 Mf>ed|cd/c/B|PA2d |ef/e/d |:e2f |ef2 |c>BA |GA/G/F |E>FG |ABc- | V:Trompette %%MIDI program 56 "Trompette"z3|z3 |z3 |z3 |:Mc>BA|PGA/G/F|PE>EF|PEF/E/D|C>CPB,|A,G,F,-| ``` -------------------------------- ### blockdiag: Node Shapes Example Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md This blockdiag example demonstrates various standard and flowchart-specific node shapes. It illustrates how to define and connect nodes with different visual representations. ```blockdiag // standard node shapes box [shape = box]; square [shape = square]; roundedbox [shape = roundedbox]; dots [shape = dots]; circle [shape = circle]; ellipse [shape = ellipse]; diamond [shape = diamond]; minidiamond [shape = minidiamond]; note [shape = note]; mail [shape = mail]; cloud [shape = cloud]; actor [shape = actor]; beginpoint [shape = beginpoint]; endpoint [shape = endpoint]; box -> square -> roundedbox -> dots; circle -> ellipse -> diamond -> minidiamond; note -> mail -> cloud -> actor; beginpoint -> endpoint; // node shapes for flowcharts condition [shape = flowchart.condition]; database [shape = flowchart.database]; terminator [shape = flowchart.terminator]; input [shape = flowchart.input]; loopin [shape = flowchart.loopin]; loopout [shape = flowchart.loopout]; condition -> database -> terminator -> input; loopin -> loopout; ``` -------------------------------- ### Pandoc filter for converting text to uppercase Source: https://github.com/jgm/pandocfilters/blob/master/README.rst A simple Pandoc filter example using pandocfilters to convert all regular text ('Str' elements) to uppercase. It imports necessary functions and defines a 'caps' action function that is then passed to toJSONFilter. ```python #!/usr/bin/env python """ Pandoc filter to convert all regular text to uppercase. Code, link URLs, etc. are not affected. """ from pandocfilters import toJSONFilter, Str def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) if __name__ == "__main__": toJSONFilter(caps) ``` -------------------------------- ### Embed ABC Notation in Markdown Source: https://github.com/jgm/pandocfilters/blob/master/examples/abc-sample.md This snippet demonstrates how to embed ABC music notation within a markdown-like structure, potentially for documentation or web rendering. It includes attributes for caption and width. ```markdown ```{.abc #whatever caption="this is the caption" width=50%} X:7 T:Qui Tolis (Trio) C:André Raison M:3/4 L:1/4 Q:1/4=92 %%staves {(Pos1 Pos2) Trompette} K:F % V:Pos1 %%MIDI program 78 "Positif"x3 |x3 |c'>ba|Pga/g/f|:g2a |ba2 |g2c- |c2P=B |c>de |fga | V:Pos2 %%MIDI program 78 Mf>ed|cd/c/B|PA2d |ef/e/d |:e2f |ef2 |c>BA |GA/G/F |E>FG |ABc- | V:Trompette %%MIDI program 56 "Trompette"z3|z3 |z3 |z3 |:Mc>BA|PGA/G/F|PE>EF|PEF/E/D|C>CPB,|A,G,F,-| ``` ``` -------------------------------- ### blockdiag: Diagram with Unicode Characters Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md Demonstrates blockdiag's support for Unicode characters in diagram elements. This example includes 'Ä', 'ü', and 'ö'. ```blockdiag blockdiag { Ä -> Bü -> Cö -> D; Ä -> E -> F -> G; } ``` -------------------------------- ### Generate PlantUML with Special Characters Source: https://github.com/jgm/pandocfilters/blob/master/examples/plantuml-sample.md This example shows how to generate a PlantUML diagram that includes special characters like 'Ä', 'ü', and 'ö'. It ensures that the filter can correctly process and render these characters within the diagram elements. ```plantuml Älöc -> Bob: Authentication Request Bob --> Älöc: Authentication Response Älöc -> Bob: Another authentication Request Älöc <-- Bob: another authentication Response ``` -------------------------------- ### Element Constructors - Build AST nodes Source: https://context7.com/jgm/pandocfilters/llms.txt Factory functions for creating Pandoc AST elements. Block elements include Para, CodeBlock, Header, etc. Inline elements include Str, Emph, Link, Image, etc. ```APIDOC ## Element Constructors - Build AST nodes ### Description Factory functions for creating Pandoc AST elements. Block elements include Para, CodeBlock, Header, etc. Inline elements include Str, Emph, Link, Image, etc. ### Method *Constructor functions* ### Endpoint *N/A* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import Para, Str, Space, Emph, Strong, Link, Image # Create a paragraph with emphasis para = Para([ Str("Hello"), Space(), Emph([Str("world")]) ]) # Create a link link = Link( ["", [], []], # attributes: [id, classes, key-value pairs] [Str("Click here")], # link text ["https://example.com", ""] ) # Create an image image = Image( ["fig1", [], []], # attributes [Str("Caption text")], # caption ["image.png", "fig:"] ) ``` ### Response #### Success Response (200) *Pandoc AST element object* #### Response Example *See Request Example* ``` -------------------------------- ### Generate PlantUML Diagram from Text Source: https://github.com/jgm/pandocfilters/blob/master/examples/plantuml-sample.md This snippet demonstrates converting a simple ASCII art representation of a sequence diagram into a PlantUML diagram. It takes the text-based diagram as input and outputs a PlantUML formatted string. ```plantuml Alice -> Bob: Authentication Request Bob --> Alice: Authentication Response Alice -> Bob: Another authentication Request Alice <-- Bob: another authentication Response ``` -------------------------------- ### blockdiag: Basic Diagram Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md This snippet shows the basic syntax for creating a blockdiag diagram. It defines a simple flow from A to B to C to D and A to E to F to G. ```blockdiag blockdiag { A -> B -> C -> D; A -> E -> F -> G; } ``` -------------------------------- ### Build AST nodes using Element Constructors Source: https://context7.com/jgm/pandocfilters/llms.txt Pandocfilters provides factory functions for constructing all Pandoc AST elements. These include block elements like `Para`, `CodeBlock`, and `Header`, as well as inline elements such as `Str`, `Emph`, `Link`, and `Image`. These constructors simplify the process of programmatically creating or modifying Pandoc AST structures. ```python from pandocfilters import Para, Str, Space, Emph, Strong, Link, Image # Create a paragraph with emphasis para = Para([ Str("Hello"), Space(), Emph([Str("world")]) ]) # Create a link link = Link( ["", [], []], # attributes: [id, classes, key-value pairs] [Str("Click here")], # link text ["https://example.com", ""] ) # Create an image image = Image( ["fig1", [], []], # attributes [Str("Caption text")], # caption ["image.png", "fig:"] ) ``` -------------------------------- ### Apply PlantUML Options with Filter Syntax Source: https://github.com/jgm/pandocfilters/blob/master/examples/plantuml-sample.md This snippet illustrates how to use pandoc filter syntax to apply specific options to a PlantUML diagram, such as setting a caption and controlling the width. The code block itself is formatted with PlantUML syntax and includes attributes for customization. ```plantuml Alice -> Bob: Authentication Request Bob --> Alice: Authentication Response ``` -------------------------------- ### Code Block to Image Filter (Graphviz) Source: https://context7.com/jgm/pandocfilters/llms.txt A Pandoc filter written in Python that converts Graphviz code blocks into images. It uses `get_filename4code` for caching, `get_caption` for captions, `get_value` for attributes like 'prog', and `get_extension` to determine the output format. It generates images using the `dot` command if they don't exist. ```python #!/usr/bin/env python import os import sys from subprocess import call from pandocfilters import toJSONFilter, Para, Image, get_filename4code, get_caption, get_extension, get_value def graphviz(key, value, format, meta): if key == 'CodeBlock': [[ident, classes, keyvals], code] = value if "graphviz" in classes: caption, typef, keyvals = get_caption(keyvals) prog, keyvals = get_value(keyvals, "prog", "dot") filetype = get_extension(format, "png", html="png", latex="pdf") dest = get_filename4code("graphviz", code, filetype) if not os.path.isfile(dest): # Generate image using graphviz call(["dot", f"-T{filetype}", "-o", dest], input=code.encode()) sys.stderr.write(f'Created image {dest}\n') return Para([Image([ident, [], keyvals], caption, [dest, typef])]) if __name__ == "__main__": toJSONFilter(graphviz) # Usage: pandoc --filter ./graphviz.py document.md -o output.pdf # Input markdown: # ```{.graphviz caption="My Graph"} # digraph G { A -> B -> C; } # ``` # Output: Rendered diagram image with caption ``` -------------------------------- ### Choose File Extension with get_extension Source: https://context7.com/jgm/pandocfilters/llms.txt Determines the appropriate file extension for a given output format, allowing for format-specific overrides. This is particularly useful when generating images or other media that need to have extensions suitable for the target output format (e.g., SVG for HTML, EPS for LaTeX). ```python from pandocfilters import get_extension ext_html = get_extension("html", "png", html="svg", latex="eps") # ext_html: "svg" ext_latex = get_extension("latex", "png", html="svg", latex="eps") # ext_latex: "eps" ext_other = get_extension("docx", "png", html="svg", latex="eps") # ext_other: "png" ``` -------------------------------- ### nwdiag: Simple Network Diagram Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md This nwdiag snippet defines a basic network topology with two networks, 'dmz' and 'internal', and assigns IP addresses to network elements. ```nwdiag nwdiag { network dmz { address = "210.x.x.x/24" web01 [address = "210.x.x.1"]; web02 [address = "210.x.x.2"]; } network internal { address = "172.x.x.x/24"; web01 [address = "172.x.x.1"]; web02 [address = "172.x.x.2"]; db01; db02; } } ``` -------------------------------- ### toJSONFilters - Apply multiple transformation actions Source: https://context7.com/jgm/pandocfilters/llms.txt Applies a list of action functions sequentially to transform the document AST. Each action walks the entire tree before the next action is applied. ```APIDOC ## toJSONFilters - Apply multiple transformation actions ### Description Applies a list of action functions sequentially to transform the document AST. Each action walks the entire tree before the next action is applied. ### Method *Implicitly handles stdin/stdout piping* ### Endpoint *N/A (designed for piping)* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None (reads from stdin)* ### Request Example ```python #!/usr/bin/env python from pandocfilters import toJSONFilters, Str, Emph def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) def bold_caps(key, value, format, meta): if key == 'Emph': return None # Keep emphasis as-is if __name__ == "__main__": toJSONFilters([caps, bold_caps]) ``` ### Response #### Success Response (200) *Modified Pandoc JSON to stdout* #### Response Example *N/A (output is piped)* ``` -------------------------------- ### attributes - Create attribute lists Source: https://context7.com/jgm/pandocfilters/llms.txt Constructs an attribute list `[id, classes, keyvals]` from a dictionary. Used for elements that support attributes like Div, Span, Code, etc. ```APIDOC ## attributes - Create attribute lists ### Description Constructs an attribute list `[id, classes, keyvals]` from a dictionary. Used for elements that support attributes like Div, Span, Code, etc. ### Method *Utility function* ### Endpoint *N/A* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import attributes, Span, Str attrs = attributes({ "id": "special", "classes": ["highlight", "big"], "data-value": "42" }) # attrs: ["special", ["highlight", "big"], [["data-value", "42"]]] span = Span(attrs, [Str("Important text")]) ``` ### Response #### Success Response (200) *Attribute list array* #### Response Example *See Request Example* ``` -------------------------------- ### toJSONFilter - Create a simple stdin/stdout filter Source: https://context7.com/jgm/pandocfilters/llms.txt Creates a JSON-to-JSON filter that reads Pandoc JSON from stdin, applies a transformation action, and writes modified JSON to stdout. The action function receives element type, value, output format, and document metadata. ```APIDOC ## toJSONFilter - Create a simple stdin/stdout filter ### Description Creates a JSON-to-JSON filter that reads Pandoc JSON from stdin, applies a transformation action, and writes modified JSON to stdout. The action function receives element type, value, output format, and document metadata. ### Method *Implicitly handles stdin/stdout piping* ### Endpoint *N/A (designed for piping)* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None (reads from stdin)* ### Request Example ```python #!/usr/bin/env python from pandocfilters import toJSONFilter, Str def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) if __name__ == "__main__": toJSONFilter(caps) ``` ### Response #### Success Response (200) *Modified Pandoc JSON to stdout* #### Response Example *N/A (output is piped)* ``` -------------------------------- ### Create a simple stdin/stdout filter with toJSONFilter Source: https://context7.com/jgm/pandocfilters/llms.txt The `toJSONFilter` function creates a filter that reads Pandoc JSON from stdin, applies a user-defined transformation function, and writes the modified JSON to stdout. The transformation function receives the element's key, value, output format, and document metadata. It's suitable for simple, single-action filters. ```python #!/usr/bin/env python from pandocfilters import toJSONFilter, Str def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) if __name__ == "__main__": toJSONFilter(caps) ``` -------------------------------- ### Generate TikZ Diagram Source: https://github.com/jgm/pandocfilters/blob/master/examples/tikz-sample.md This LaTeX code generates a circular diagram with numbered nodes and connecting arcs. It uses the TikZ package to define nodes and draw arcs representing connections. The number of nodes and the margin for the arcs are configurable. ```latex \begin{tikzpicture} \def \n {5} \def \radius {3cm} \def \margin {8} % margin in angles, depends on the radius \foreach \s in {1,...,\n} { \node[draw, circle] at ({360/\n * (\s - 1)}:\radius) {$\s$}; \draw[->, >=latex] ({360/\n * (\s - 1)+\margin}:\radius) arc ({360/\n * (\s - 1)+\margin}:{360/\n * (\s)-\margin}:\radius); } \end{tikzpicture} ``` -------------------------------- ### Apply multiple transformation actions with toJSONFilters Source: https://context7.com/jgm/pandocfilters/llms.txt The `toJSONFilters` function allows applying a list of transformation functions sequentially. Each function traverses the entire AST before the next one is applied. This is useful for building complex filters by composing simpler actions. It supports Python 2.7+ and Python 3.4+. ```python #!/usr/bin/env python from pandocfilters import toJSONFilters, Str, Emph def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) def bold_caps(key, value, format, meta): if key == 'Emph': return None # Keep emphasis as-is if __name__ == "__main__": toJSONFilters([caps, bold_caps]) ``` -------------------------------- ### Pandoc Filter for Theorem Formatting in Python Source: https://context7.com/jgm/pandocfilters/llms.txt This Python script acts as a Pandoc filter to transform specific Div elements marked as 'theorem' into LaTeX or HTML formatted theorem environments. It utilizes the pandocfilters library to parse and manipulate Pandoc's AST. ```python #!/usr/bin/env python from pandocfilters import toJSONFilter, RawBlock, Div theoremcount = 0 def latex(x): return RawBlock('latex', x) def html(x): return RawBlock('html', x) def theorems(key, value, format, meta): global theoremcount if key == 'Div': [[ident, classes, kvs], contents] = value if "theorem" in classes: if format == "latex": label = f'\\label{{{ident}}}' if ident else "" return [latex(f'\\begin{{theorem}}{label}')] + contents + [latex('\\end{theorem}')] elif format in ["html", "html5"]: theoremcount += 1 newcontents = [ html(f'
Theorem {theoremcount}
'), html('
') ] + contents + [html('
\n')] return Div([ident, classes, kvs], newcontents) if __name__ == "__main__": toJSONFilter(theorems) ``` -------------------------------- ### Traverse and transform AST nodes with walk Source: https://context7.com/jgm/pandocfilters/llms.txt The `walk` function recursively traverses the Pandoc AST. It applies a given action function to each node. The action function can return `None` (no change), a new node (replacement), a list (to splice), or an empty list (to delete). This function is crucial for detailed AST manipulation and works with various Pandoc AST elements. ```python from pandocfilters import walk, Str import json def uppercase_strings(key, value, format, meta): if key == 'Str': return Str(value.upper()) doc = json.loads('{"blocks":[{"t":"Para","c":[{"t":"Str","c":"hello"}]}],"pandoc-api-version":[1,17,5,4],"meta":{}}') result = walk(doc, uppercase_strings, "html", {}) # result: document with all strings uppercased ``` -------------------------------- ### stringify - Extract plain text from AST Source: https://context7.com/jgm/pandocfilters/llms.txt Walks an AST node and concatenates all text content, removing all formatting, links, and other markup. Returns a plain string. ```APIDOC ## stringify - Extract plain text from AST ### Description Walks an AST node and concatenates all text content, removing all formatting, links, and other markup. Returns a plain string. ### Method *Utility function* ### Endpoint *N/A* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import stringify, Str, Emph ast_fragment = { 't': 'Para', 'c': [ {'t': 'Str', 'c': 'Hello'}, {'t': 'Space'}, {'t': 'Emph', 'c': [{'t': 'Str', 'c': 'world'}]} ] } text = stringify(ast_fragment) # text: "Hello world" ``` ### Response #### Success Response (200) *Plain text string* #### Response Example *See Request Example* ``` -------------------------------- ### walk - Traverse and transform AST nodes Source: https://context7.com/jgm/pandocfilters/llms.txt Recursively walks the Pandoc AST tree and applies an action function to each node. Returns None to keep node unchanged, a new node to replace it, a list to splice multiple nodes, or an empty list to delete. ```APIDOC ## walk - Traverse and transform AST nodes ### Description Recursively walks the Pandoc AST tree and applies an action function to each node. Returns None to keep node unchanged, a new node to replace it, a list to splice multiple nodes, or an empty list to delete. ### Method *Internal function, typically called by filter functions* ### Endpoint *N/A* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import walk, Str import json def uppercase_strings(key, value, format, meta): if key == 'Str': return Str(value.upper()) doc = json.loads('{"blocks":[{"t":"Para","c":[{"t":"Str","c":"hello"}]}],"pandoc-api-version":[1,17,5,4],"meta":{}}') result = walk(doc, uppercase_strings, "html", {}) # result: document with all strings uppercased ``` ### Response #### Success Response (200) *Modified AST node or document* #### Response Example *See Request Example* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import walk, Str import json def uppercase_strings(key, value, format, meta): if key == 'Str': return Str(value.upper()) doc = json.loads('{"blocks":[{"t":"Para","c":[{"t":"Str","c":"hello"}]}],"pandoc-api-version":[1,17,5,4],"meta":{}}') result = walk(doc, uppercase_strings, "html", {}) # result: document with all strings uppercased ``` ### Response #### Success Response (200) *Modified AST node or document* #### Response Example *See Request Example* ``` -------------------------------- ### Transform JSON string directly with applyJSONFilters Source: https://context7.com/jgm/pandocfilters/llms.txt The `applyJSONFilters` function enables programmatic application of filters to a JSON string, bypassing stdin/stdout. This is ideal for testing filters in isolation or integrating Pandoc AST transformations within other Python applications. It takes a list of filter functions and the source JSON string. ```python from pandocfilters import applyJSONFilters, Str import json def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) source = '{"blocks":[{"t":"Para","c":[{"t":"Str","c":"hello"}]}],"pandoc-api-version":[1,17,5,4],"meta":{}}' result = applyJSONFilters([caps], source, "html") # result: '{"blocks":[{"t":"Para","c":[{"t":"Str","c":"HELLO"}]}],...}' ``` -------------------------------- ### seqdiag: Element Order Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md Demonstrates how to explicitly define the order of participants in a seqdiag diagram. By listing elements at the beginning, you control their display order. ```seqdiag seqdiag { # define order of elements # seqdiag sorts elements by order they appear browser; database; webserver; browser -> webserver [label = "GET /index.html"]; browser <-- webserver; browser -> webserver [label = "POST /blog/comment"]; webserver -> database [label = "INSERT comment"]; webserver <-- database; browser <-- webserver; } ``` -------------------------------- ### Extract plain text from AST with stringify Source: https://context7.com/jgm/pandocfilters/llms.txt The `stringify` function traverses a given Pandoc AST fragment and concatenates all text content into a single plain string. It effectively strips all formatting, markup, and links, providing only the raw text. This is useful for generating summaries or plain text versions of document content. ```python from pandocfilters import stringify, Str, Emph ast_fragment = { 't': 'Para', 'c': [ {'t': 'Str', 'c': 'Hello'}, {'t': 'Space'}, {'t': 'Emph', 'c': [{'t': 'Str', 'c': 'world'}]} ] } text = stringify(ast_fragment) # text: "Hello world" ``` -------------------------------- ### Create attribute lists with attributes function Source: https://context7.com/jgm/pandocfilters/llms.txt The `attributes` function is a utility for constructing Pandoc's attribute list format `[id, classes, keyvals]`. This list is used by various elements like `Div`, `Span`, and `CodeBlock` to define their attributes, such as IDs, CSS classes, and custom key-value pairs. It simplifies the creation of these attribute structures from Python dictionaries. ```python from pandocfilters import attributes, Span, Str attrs = attributes({ "id": "special", "classes": ["highlight", "big"], "data-value": "42" }) # attrs: ["special", ["highlight", "big"], [["data-value", "42"]]] span = Span(attrs, [Str("Important text")]) ``` -------------------------------- ### applyJSONFilters - Transform JSON string directly Source: https://context7.com/jgm/pandocfilters/llms.txt Programmatically applies filters to a JSON string without using stdin/stdout. Useful for testing filters or integrating into applications. ```APIDOC ## applyJSONFilters - Transform JSON string directly ### Description Programmatically applies filters to a JSON string without using stdin/stdout. Useful for testing filters or integrating into applications. ### Method POST (conceptually, as it processes input data) ### Endpoint *N/A (internal function)* ### Parameters #### Path Parameters *None* #### Query Parameters *None* #### Request Body *None* ### Request Example ```python from pandocfilters import applyJSONFilters, Str import json def caps(key, value, format, meta): if key == 'Str': return Str(value.upper()) source = '{"blocks":[{"t":"Para","c":[{"t":"Str","c":"hello"}]}],"pandoc-api-version":[1,17,5,4],"meta":{}}' result = applyJSONFilters([caps], source, "html") # result: '{"blocks":[{"t":"Para","c":[{"t":"Str","c":"HELLO"}]}],...}' ``` ### Response #### Success Response (200) *JSON string with applied filters* #### Response Example *See Request Example* ``` -------------------------------- ### Text Transformation Filter using Metadata Source: https://context7.com/jgm/pandocfilters/llms.txt A Python filter for Pandoc that replaces placeholders like '%{fieldname}' in the document with corresponding metadata field values. It uses regular expressions to find placeholders and retrieves values from the Pandoc metadata. This is useful for injecting dynamic content into documents. ```python #!/usr/bin/env python from pandocfilters import toJSONFilter, Str import re pattern = re.compile(r'%\{(.*)\}$') def metavars(key, value, format, meta): """Replace %{fieldname} with metadata field values""" if key == 'Str': m = pattern.match(value) if m: field = m.group(1) result = meta.get(field, {}) if result.get('t') == 'MetaString': return Str(result['c']) return None if __name__ == "__main__": toJSONFilter(metavars) # Usage: pandoc --filter ./metavars.py -M author="John Doe" document.md # Input: "Written by %{author}" # Output: "Written by John Doe" ``` -------------------------------- ### Generate Cached Filenames with get_filename4code Source: https://context7.com/jgm/pandocfilters/llms.txt Generates a cached filename for code output based on a SHA1 hash of the code content. It automatically creates a '{module}-images' directory for caching and can use temporary directories if `PANDOCFILTER_CLEANUP` is set. This is useful for managing generated image files. ```python from pandocfilters import get_filename4code import os code = "digraph G { A -> B; }" filename = get_filename4code("graphviz", code, "png") # filename: "graphviz-images/a1b2c3d4e5f6...89.png" # Directory is created if it doesn't exist # File persists across runs for caching ``` -------------------------------- ### blockdiag: Diagram with Options (No Type) Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md Illustrates the DRY principle by omitting the diagram type when it's redundant with the filter. This snippet shows a blockdiag diagram with options but without explicitly stating 'blockdiag' again. ```blockdiag A -> B -> C -> D; A -> E -> F -> G; ``` -------------------------------- ### packetdiag: TCP Header Structure Source: https://github.com/jgm/pandocfilters/blob/master/examples/blockdiag-sample.md A packetdiag diagram visualizing the structure of a TCP header. It breaks down the header into its constituent fields, specifying their bit ranges and labels. ```packetdiag colwidth = 32 node_height = 72 0-15: Source Port 16-31: Destination Port 32-63: Sequence Number 64-95: Acknowledgment Number 96-99: Data Offset 100-105: Reserved 106: URG [rotate = 270] 107: ACK [rotate = 270] 108: PSH [rotate = 270] 109: RST [rotate = 270] 110: SYN [rotate = 270] 111: FIN [rotate = 270] 112-127: Window 128-143: Checksum 144-159: Urgent Pointer 160-191: (Options and Padding) 192-223: data [colheight = 3] ``` -------------------------------- ### Extract Caption with get_caption Source: https://context7.com/jgm/pandocfilters/llms.txt Extracts a caption from a list of key-value attributes, commonly found in Pandoc's CodeBlock elements. It returns the caption as inline elements, a figure type prefix, and the remaining attributes. This function is useful for dynamically setting captions for elements like diagrams. ```python from pandocfilters import get_caption keyvals = [["caption", "My diagram"], ["width", "500"]] caption, typef, remaining = get_caption(keyvals) # caption: [{'t': 'Str', 'c': 'My diagram'}] # typef: "fig:" # remaining: [["width", "500"]] ``` -------------------------------- ### Content Filtering with State (HTML Comments) Source: https://context7.com/jgm/pandocfilters/llms.txt A Python Pandoc filter that removes HTML comment blocks from the output. It uses a global state variable `incomment` to track whether the parser is currently inside a comment block defined by '' and ''. This allows for conditional inclusion of content. ```python #!/usr/bin/env python from pandocfilters import toJSONFilter import re incomment = False def comment(key, value, format, meta): """Remove HTML comment blocks from output""" global incomment if key == 'RawBlock': fmt, s = value if fmt == "html": if re.search("", s): incomment = True return [] elif re.search("", s): incomment = False return [] if incomment: return [] # Suppress anything in comment if __name__ == "__main__": toJSONFilter(comment) # Usage: pandoc --filter ./comments.py document.md # Input: # Regular text # # This will be removed # # More text # Output: Only "Regular text" and "More text" ``` -------------------------------- ### Extract and Remove Key-Value Pair with get_value Source: https://context7.com/jgm/pandocfilters/llms.txt Extracts a specific key-value pair from a list of key-value pairs and returns the value along with the list excluding that pair. It also accepts a default value to return if the key is not found. This is helpful for processing attributes in Pandoc elements. ```python from pandocfilters import get_value keyvals = [["prog", "neato"], ["width", "500"], ["height", "300"]] prog, remaining = get_value(keyvals, "prog", "dot") # prog: "neato" # remaining: [["width", "500"], ["height", "300"]] missing, remaining = get_value(keyvals, "color", "black") # missing: "black" (default) # remaining: [["prog", "neato"], ["width", "500"], ["height", "300"]] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.