### Local Package Installation and Testing Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Installs the package locally using setup.py and runs tests using py.test. This is a preliminary step before distribution to ensure the package functions correctly. ```shell python setup.py install py.test ``` -------------------------------- ### Local Development Installation of Panflute Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/install.md Installs panflute locally from a cloned GitHub repository. The 'install' command installs the package, while 'develop' installs it via a symlink, allowing for automatic updates as you modify the source code. ```bash python setup.py install ``` ```bash python setup.py develop ``` -------------------------------- ### Installing Development Dependencies Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Installs the project in editable mode along with its development dependencies. This is useful for developers working on the project. ```shell pip install --editable ".[dev]" ``` -------------------------------- ### walk Method Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to traverse elements and their children, applying functions for modification or analysis. Includes examples of simple actions and stopping the walk at specific elements. ```APIDOC ## walk Method ### Description Walk through an element and its children, applying a function to each. ### Method `elem.walk(action, stop_if=None)` ### Parameters #### Path Parameters - **elem** (Element) - The element to start walking from. - **action** (function) - The function to apply to each element. - **stop_if** (function, optional) - A function that returns True to stop descending into a branch. ### Request Example ```python import panflute as pf def action(elem, doc): if isinstance(elem, pf.Div) and 'highlight' in elem.classes: # Walk through all children of this Div def make_bold(e, doc): if isinstance(e, pf.Str): return pf.Strong(e) elem.walk(make_bold) def finalize(doc): # Walk with stop condition def count_headers(e, doc): if isinstance(e, pf.Header): doc.header_count += 1 def stop_at_div(e): return isinstance(e, pf.Div) # Don't descend into Divs doc.header_count = 0 doc.walk(count_headers, stop_if=stop_at_div) pf.debug(f"Found {doc.header_count} headers (excluding those in Divs)") def main(doc=None): return pf.run_filter(action, finalize=finalize, doc=doc) ``` ### Response N/A (modifies document in place or performs actions) ### Response Example N/A ``` -------------------------------- ### Install Panflute from PyPI Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/install.md Installs the panflute library using pip from the Python Package Index (PyPI). This is the standard method for most users. It requires Python 3.7+ and may need administrator privileges on Windows. ```bash pip install panflute ``` -------------------------------- ### Code Example from Definition 2 Source: https://github.com/sergiocorreia/panflute/blob/master/examples/input/deflists-sample.md This snippet contains a code example found within the definition of 'Term 2'. It illustrates a specific implementation detail or usage pattern. ```text { some code, part of Definition 2 } ``` -------------------------------- ### Install Panflute from GitHub Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/install.md Installs the latest development version of panflute directly from its GitHub repository using pip. This is useful for users who want the most recent features or bug fixes. ```bash pip install git+https://github.com/sergiocorreia/panflute.git ``` -------------------------------- ### Running Pandoc Filters with Panflute (Python & Bash) Source: https://context7.com/sergiocorreia/panflute/llms.txt Provides examples of how to create and run Pandoc filters using Panflute. Includes Python code for a filter that modifies header levels and bash commands for executing filters via command line or piping JSON. Dependencies: panflute, pandoc. ```python # my_filter.py import panflute as pf def action(elem, doc): if isinstance(elem, pf.Header): elem.level = min(elem.level + 1, 6) # Increase header levels def main(doc=None): return pf.run_filter(action, doc=doc) if __name__ == '__main__': main() ``` ```bash # Run as Pandoc filter pandoc input.md --filter my_filter.py -o output.md # Or pipe through JSON pandoc input.md -t json | python my_filter.py | pandoc -f json -o output.html # Use panfl for multiple filters pandoc input.md -t json | panfl filter1.py filter2.py -t html | pandoc -f json -o output.html ``` -------------------------------- ### Instantiate block elements Source: https://context7.com/sergiocorreia/panflute/llms.txt Provides examples of creating various block-level elements like paragraphs, headers, code blocks, and block quotes using Panflute classes. ```python import panflute as pf para = pf.Para(pf.Str('Some'), pf.Space, pf.Str('text.')) header = pf.Header( pf.Str('Chapter'), pf.Space, pf.Str('One'), level=2, identifier='chapter-1', classes=['chapter-header'], attributes={'data-number': '1'} ) code = pf.CodeBlock( 'def hello():\n print("Hello!")', identifier='example-code', classes=['python', 'highlight'] ) quote = pf.BlockQuote( pf.Para(pf.Str('To be or not to be.')), pf.Para(pf.Str('— Shakespeare')) ) div = pf.Div( pf.Para(pf.Str('Content inside div')), identifier='my-div', classes=['warning'], attributes={'role': 'alert'} ) rule = pf.HorizontalRule() ``` -------------------------------- ### I/O Functions (load and dump) Source: https://context7.com/sergiocorreia/panflute/llms.txt Provides examples for loading Pandoc JSON documents from various sources (stdin, file, string) and dumping them to different destinations (stdout, file, string) using Panflute's `load` and `dump` functions. ```APIDOC ## I/O Functions ### load and dump ### Description Load and dump Pandoc JSON documents for advanced use cases. ### Method `pf.load(source=sys.stdin)` `pf.dump(doc, destination=sys.stdout)` ### Parameters #### `pf.load` - **source** (file-like object or None, optional) - The source to load from. Defaults to stdin. #### `pf.dump` - **doc** (Document) - The Pandoc document object to dump. - **destination** (file-like object or None, optional) - The destination to dump to. Defaults to stdout. ### Request Example ```python import panflute as pf import json import io # Load from stdin (default) doc = pf.load() # Load from file with open('document.json', encoding='utf-8') as f: doc = pf.load(f) # Load from string json_str = '{"pandoc-api-version":[1,23],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"Hello"}]}]}' doc = pf.load(io.StringIO(json_str)) # Modify the document doc.content.append(pf.Para(pf.Str('Added paragraph'))) # Dump to stdout (default) pf.dump(doc) # Dump to file with open('output.json', 'w', encoding='utf-8') as f: pf.dump(doc, f) # Dump to string with io.StringIO() as f: pf.dump(doc, f) json_output = f.getvalue() ``` ### Response `pf.load` returns a `Document` object. `pf.dump` writes JSON to the specified destination. ``` -------------------------------- ### C/C++ Libraries for Data Structures and Algorithms Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section highlights C and C++ libraries for implementing common data structures and algorithms. Examples include hash rings, hash tables, and template-based C++ structures. ```C struct HashTableEntry { char* key; void* value; }; void insert_entry(void* table, const char* key, void* value) { // Hash table insertion logic } ``` ```C++ #include template class MaxCPP { public: std::vector data; void add(T value) { data.push_back(value); } }; ``` -------------------------------- ### Pandoc Metadata for Panflute Filters Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/guide.md Example of Pandoc metadata configuration to specify Panflute filters and their search path. This allows for automatic execution of specified filters. ```yaml --- title: Some title panflute-filters: [remove-tables, include] panflute-path: 'panflute/docs/source' ... Lorem ipsum ``` -------------------------------- ### Run Pandoc Directly with Custom Arguments (Python) Source: https://context7.com/sergiocorreia/panflute/llms.txt Provides a low-level function to execute Pandoc with specified arguments. It can be used to get Pandoc's version, convert text between formats, or specify a custom Pandoc executable path. Input is typically text or arguments, and output is the Pandoc result as a string. ```python import panflute as pf # Get Pandoc version version = pf.run_pandoc(args=['--version']) print(version.split('\n')[0]) # 'pandoc 3.1.1' # Convert text with specific options result = pf.run_pandoc( text='# Hello\n\nWorld', args=['--from=markdown', '--to=html'] ) print(result) # '

Hello

\n

World

' # Use custom Pandoc path result = pf.run_pandoc( text='*emphasis*', args=['--from=markdown', '--to=latex'], pandoc_path='/usr/local/bin/pandoc' ) ``` -------------------------------- ### Navigate Document Tree Elements (Python) Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to navigate the Pandoc document tree using element relationships. It covers accessing parent, next/previous siblings, ancestors by offset, and the root document. It also shows how to get an element's index within its container and the container itself. Dependencies include panflute. ```python import panflute as pf def action(elem, doc): # Access parent element if elem.parent: pf.debug(f"{elem.tag} is child of {elem.parent.tag}") # Access siblings if elem.next: pf.debug(f"Next sibling: {elem.next.tag}") if elem.prev: pf.debug(f"Previous sibling: {elem.prev.tag}") # Access by offset sibling_2_ahead = elem.offset(2) sibling_1_behind = elem.offset(-1) # Access ancestors grandparent = elem.ancestor(2) # elem.parent.parent great_grandparent = elem.ancestor(3) # Get the root document root = elem.doc # Get element's position in its container if elem.index is not None: pf.debug(f"Element is at index {elem.index}") # Get the container holding this element container = elem.container if container: pf.debug(f"Container has {len(container)} elements") def main(doc=None): return pf.run_filter(action, doc=doc) ``` -------------------------------- ### Embedded HTML Block Source: https://github.com/sergiocorreia/panflute/blob/master/tests/sample_files/abstract/example.md Demonstrates how to embed standard HTML elements within a Markdown document. This example shows a simple div structure. ```html
foo
``` -------------------------------- ### Automatic Filter Execution Configuration (YAML & Bash) Source: https://context7.com/sergiocorreia/panflute/llms.txt Explains how to configure Panflute filters to run automatically by specifying them in the document's YAML metadata. Includes a YAML example and a bash command for running Pandoc with automatic filter detection. Dependencies: panflute, pandoc. ```yaml --- title: My Document panflute-filters: - remove-tables - include-files - custom-styles panflute-path: - ./filters - ~/my-filters panflute-verbose: true --- # Document content here ``` ```bash # Run with automatic filter detection pandoc input.md --filter panflute -o output.pdf ``` -------------------------------- ### Run pycodestyle for PEP 8 Check Source: https://github.com/sergiocorreia/panflute/blob/master/CONTRIBUTING.md This command executes pycodestyle (formerly pep8) to check the Panflute code against the PEP 8 style guide. The output is redirected to a file named 'pycodestyle-report.txt'. ```bash pycodestyle ./panflute > pycodestyle-report.txt ``` -------------------------------- ### C/C++ Game Development and Utilities Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet includes C/C++ projects focused on game development, system utilities, and libraries. Examples include Android NDK game development, SA-MP gamemodes, and general C/C++ libraries for various purposes. ```C++ #include int main() { std::cout << "Hello, NDK!" << std::endl; return 0; } ``` ```C #include int main() { printf("Hello, C Game Dev!\n"); return 0; } ``` -------------------------------- ### Markdown Code Blocks Source: https://github.com/sergiocorreia/panflute/blob/master/tests/sample_files/example1/example.md Shows how to create code blocks in Markdown using indentation. Code blocks are typically indented by four spaces or one tab. The example also demonstrates that special characters like $, \, >, and { within code blocks are not escaped. ```markdown ---- (should be four hyphens) sub status { print "working"; } this code block is indented by one tab And: this code block is indented by two tabs These should not be escaped: $ \ > [ { ``` -------------------------------- ### Define Perl Status Subroutine Source: https://github.com/sergiocorreia/panflute/blob/master/tests/sample_files/abstract/example.md A simple Perl subroutine example used to demonstrate code block formatting within Markdown. It prints 'working' to the console. ```perl sub status { print "working"; } ``` -------------------------------- ### yaml_filter with Multiple Tags Source: https://context7.com/sergiocorreia/panflute/llms.txt Handles multiple code block types with different handlers using `yaml_filter`. This example defines handlers for 'note' and 'alert' code blocks. ```APIDOC ## yaml_filter with Multiple Tags ### Description Handles multiple code block types with different handlers using `yaml_filter`. This example defines handlers for 'note' and 'alert' code blocks, demonstrating flexibility in processing tagged code blocks. ### Method N/A (Python function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import panflute as pf def note_handler(options, data, element, doc): """Create a note box.""" note_type = options.get('type', 'info') return pf.Div( pf.Para(pf.Strong(pf.Str(note_type.upper() + ':'))), *pf.convert_text(data), classes=['note', f'note-{note_type}'] ) def alert_handler(options, data, element, doc): """Create an alert box.""" level = options.get('level', 'warning') return pf.Div( pf.Para(pf.Emph(pf.Str(data.strip()))), classes=['alert', f'alert-{level}'] ) def main(doc=None): return pf.run_filter( pf.yaml_filter, tags={ 'note': note_handler, 'alert': alert_handler }, doc=doc ) # Example input: # ~~~ note # type: warning # --- # Remember to save your work frequently! # ~~~ # # ~~~ alert # level: danger # --- # System will restart in 5 minutes # ~~~ ``` ### Response #### Success Response (200) Returns Pandoc elements (e.g., Divs) representing the processed code blocks based on their tags and handlers. #### Response Example ``` # Pandoc Div objects for notes and alerts ``` ``` -------------------------------- ### Get Option with Panflute Source: https://context7.com/sergiocorreia/panflute/llms.txt Fetches option values with a defined priority: local element attributes first, then document metadata, and finally a default value. This is useful for configuring element behavior based on context. ```python import panflute as pf def action(elem, doc): if isinstance(elem, pf.Div) and 'custom-style' in elem.classes: # Priority: element attribute > document metadata > default style_name = pf.get_option( options=elem.attributes, local_tag='name', doc=doc, doc_tag='style-div.name', default='DefaultStyle' ) elem.attributes['custom-style'] = style_name def main(doc=None): return pf.run_filter(action, doc=doc) # Example markdown: # --- # style-div: # name: MyGlobalStyle # --- # # ::: custom-style # Uses MyGlobalStyle from metadata # ::: # # ::: {.custom-style name=LocalStyle} # Uses LocalStyle from attribute (overrides metadata) # ::: ``` -------------------------------- ### Implement filter with prepare and finalize callbacks Source: https://context7.com/sergiocorreia/panflute/llms.txt Shows how to use prepare and finalize hooks to perform document-wide initialization and post-processing, such as generating a table of contents. ```python import panflute as pf def prepare(doc): """Initialize document-level variables.""" doc.headers = [] doc.word_count = 0 def action(elem, doc): """Collect headers and count words.""" if isinstance(elem, pf.Header): doc.headers.append(pf.stringify(elem)) elif isinstance(elem, pf.Str): doc.word_count += len(elem.text.split()) def finalize(doc): """Add table of contents at the beginning.""" toc_items = [pf.ListItem(pf.Plain(pf.Str(h))) for h in doc.headers] toc = pf.BulletList(*toc_items) doc.content.insert(0, pf.Header(pf.Str('Table of Contents'), level=1)) doc.content.insert(1, toc) pf.debug(f"Document has {doc.word_count} words") def main(doc=None): return pf.run_filter(action, prepare=prepare, finalize=finalize, doc=doc) if __name__ == '__main__': main() ``` -------------------------------- ### Generating and Deploying Documentation Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Generates HTML documentation for the project using Sphinx (via make.bat) and builds the website using Jekyll. It then pushes the website to S3. ```shell cd docs && make.bat html && cd .. && cd ../website && jekyll build && s3_website push && cd ../panflute ``` -------------------------------- ### JavaScript Comment Execution Source: https://github.com/sergiocorreia/panflute/blob/master/tests/sample_files/abstract/example.md An example of a script tag containing JavaScript that should not be interpreted as Markdown by the parser. ```javascript document.write('This *should not* be interpreted as markdown'); ``` -------------------------------- ### C Libraries for System Management and Package Handling Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section contains C libraries for system management and package handling. It includes a library providing simplified C and Python API to libsolv, and a multithreaded downloader library. ```C #include void solve_dependencies() { printf("libsolv dependency resolution example\n"); } ``` ```C #include #include void download_file_threaded(const char* url) { printf("Starting threaded download for: %s\n", url); // Threaded download logic } ``` -------------------------------- ### C Libraries for Virtualization and Containerization Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet includes C libraries related to virtualization and containerization. It features a library for lightweight containers using Linux user namespaces and a tool for AmigaOS cross-compilation. ```C #include void create_container(const char* name) { printf("Creating Linux user namespace container: %s\n", name); } ``` ```C // AmigaOS cross-compiler setup void setup_cross_compiler() { printf("AmigaOS cross-compiler setup complete.\n"); } ``` -------------------------------- ### yaml_filter Source: https://context7.com/sergiocorreia/panflute/llms.txt Parses fenced code blocks containing YAML options and data, simplifying the creation of custom block handlers. This example shows a handler for CSV data. ```APIDOC ## yaml_filter (CSV Example) ### Description Parses fenced code blocks containing YAML options and data, simplifying the creation of custom block handlers. This specific example demonstrates a handler for CSV data, converting it into a Pandoc table. ### Method N/A (Python function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import panflute as pf import csv import io def csv_handler(options, data, element, doc): """Convert CSV data in code blocks to tables.""" title = options.get('title', '') has_header = options.get('has-header', True) # Parse CSV data reader = csv.reader(io.StringIO(data)) rows = list(reader) if not rows: return pf.Para(pf.Str('Empty table')) # Create table cells def make_row(items): cells = [pf.TableCell(pf.Plain(pf.Str(item.strip()))) for item in items] return pf.TableRow(*cells) # Separate header and body if has_header and len(rows) > 1: head = pf.TableHead(make_row(rows[0])) body_rows = [make_row(row) for row in rows[1:]] else: head = None body_rows = [make_row(row) for row in rows] body = pf.TableBody(*body_rows) caption = pf.Caption(pf.Para(pf.Str(title))) if title else None return pf.Table(body, head=head, caption=caption) def main(doc=None): return pf.run_filter( pf.yaml_filter, tag='csv', function=csv_handler, doc=doc ) if __name__ == '__main__': main() # Example markdown input: # ~~~ csv # title: Sales Data # has-header: true # --- # Product,Price,Quantity # Widget,10.00,100 # Gadget,25.50,50 # ~~~ ``` ### Response #### Success Response (200) Returns a Pandoc Table element generated from the CSV data. #### Response Example ``` # Pandoc Table object representing the CSV data ``` ``` -------------------------------- ### Initialize Panflute Elements Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/code.md Demonstrates how to instantiate a paragraph element containing inline elements like strings and spaces. This shows the internal structure of content management in Panflute. ```python from panflute import Para, Str, Space e = Para(Str('Hello'), Space, Str('World!')) ``` -------------------------------- ### Building and Uploading to PyPI Test Repository Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Builds a source distribution (sdist) of the package and uploads it to the PyPI test repository. This allows for testing the distribution process without affecting the live PyPI. ```shell pandoc README.md --output=README.rst && python setup.py sdist upload -r pypitest ``` -------------------------------- ### Construct Lists and Line Blocks Source: https://context7.com/sergiocorreia/panflute/llms.txt Shows how to create bulleted, ordered, and definition lists, as well as line blocks. These structures allow for organized content representation within a document. ```python import panflute as pf bullet_list = pf.BulletList(pf.ListItem(pf.Para(pf.Str('First item'))), pf.ListItem(pf.Para(pf.Str('Second item')))) ordered_list = pf.OrderedList(pf.ListItem(pf.Para(pf.Str('Step one'))), start=1, style='Decimal') def_list = pf.DefinitionList(pf.DefinitionItem(term=[pf.Str('Email')], definitions=[pf.Definition(pf.Para(pf.Str('Electronic mail')))])) line_block = pf.LineBlock(pf.LineItem(pf.Str('Line one')), pf.LineItem(pf.Str('Line two'))) ``` -------------------------------- ### Markdown Definition Lists Source: https://github.com/sergiocorreia/panflute/blob/master/tests/sample_files/example1/example.md Demonstrates the syntax for creating definition lists in Markdown. It covers tight and loose spacing, multiple definitions for a single term, and the use of alternative markers and sublists within definitions. ```markdown apple : red fruit orange : orange fruit banana : yellow fruit apple : red fruit orange : orange fruit banana : yellow fruit *apple* : red fruit contains seeds, crisp, pleasant to taste *orange* : orange fruit { orange code block } > orange block quote apple : red fruit : computer orange : orange fruit : bank apple : red fruit : computer orange : orange fruit : bank apple : red fruit : computer orange : orange fruit 1. sublist 2. sublist ``` -------------------------------- ### Get Metadata with Panflute Source: https://context7.com/sergiocorreia/panflute/llms.txt Retrieves metadata from a Panflute document, supporting nested keys using dot notation and providing default values if keys are not found. It can return metadata as Python built-ins or raw MetaValue objects. ```python import panflute as pf def action(elem, doc): # Get metadata with dot notation for nested keys author = doc.get_metadata('author', default='Unknown') # Nested metadata access # Given YAML: format: {show-frame: true, width: 100} show_frame = doc.get_metadata('format.show-frame', default=False) width = doc.get_metadata('format.width', default=80) # Get entire metadata as Python dict all_meta = doc.get_metadata() # Get raw MetaValue objects instead of Python builtins raw_meta = doc.get_metadata('title', builtin=False) if isinstance(elem, pf.Header): pf.debug(f"Processing document by {author}") def main(doc=None): return pf.run_filter(action, doc=doc) # Example document with metadata: # --- # title: My Document # author: John Doe # format: # show-frame: true # width: 100 # tags: # - python # - pandoc # --- ``` -------------------------------- ### Pushing to PyPI using Twine Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Prepares the distribution files (sdist) and checks them for common issues using Twine. It then uploads the distribution to the test PyPI repository and finally to the official PyPI. ```shell cls && python setup.py sdist && twine check dist/* ``` ```shell twine upload --repository-url https://test.pypi.org/legacy/ dist/* --verbose ``` ```shell twine upload dist/* ``` -------------------------------- ### Command Line Usage Source: https://context7.com/sergiocorreia/panflute/llms.txt Details on how to run Panflute filters from the command line, either directly using Python or by configuring filters within the document's metadata for automatic execution. ```APIDOC ## Command Line Usage ### Running as Pandoc Filter ### Description Execute filters from the command line using panflute's built-in filter runner. ### Request Example ```python # my_filter.py import panflute as pf def action(elem, doc): if isinstance(elem, pf.Header): elem.level = min(elem.level + 1, 6) # Increase header levels def main(doc=None): return pf.run_filter(action, doc=doc) if __name__ == '__main__': main() ``` ```bash # Run as Pandoc filter pandoc input.md --filter my_filter.py -o output.md # Or pipe through JSON pandoc input.md -t json | python my_filter.py | pandoc -f json -o output.html # Use panfl for multiple filters pandoc input.md -t json | panfl filter1.py filter2.py -t html | pandoc -f json -o output.html ``` ### Automatic Filter Execution ### Description Configure filters in document metadata for automatic execution. ### Request Example ```yaml --- title: My Document panflute-filters: - remove-tables - include-files - custom-styles panflute-path: - ./filters - ~/my-filters panflute-verbose: true --- # Document content here ``` ```bash # Run with automatic filter detection pandoc input.md --filter panflute -o output.pdf ``` ``` -------------------------------- ### Create Text and Inline Elements with Panflute Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to instantiate various inline elements such as formatted text, code blocks, math, links, images, and raw content. These elements form the building blocks for more complex document structures. ```python import panflute as pf text = pf.Str('Hello') emph = pf.Emph(pf.Str('italic')) strong = pf.Strong(pf.Str('bold')) code = pf.Code('print("hello")', classes=['python']) inline_math = pf.Math('x^2 + y^2 = z^2', format='InlineMath') link = pf.Link(pf.Str('Click'), pf.Space, pf.Str('here'), url='https://example.com') para = pf.Para(text, pf.Space(), emph, pf.Str(','), pf.Space(), strong, pf.Str('!')) ``` -------------------------------- ### C/C++ Tools and Utilities Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section contains C/C++ projects that serve as tools or utilities for various purposes. This includes configuration tools, API clients, and libraries for specific tasks like speech recognition or image processing. ```C++ #include int main() { std::cout << "SteelSeries Sensei Raw Config Tool Placeholder\n"; return 0; } ``` ```C #include int main() { printf("OKCoin REST API Client Example\n"); return 0; } ``` -------------------------------- ### Walk Method for Element Traversal (Python) Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to traverse a Panflute element and its children using the walk method. It shows applying functions to elements and using stop conditions to control the traversal. Dependencies include the panflute library. ```python import panflute as pf def action(elem, doc): if isinstance(elem, pf.Div) and 'highlight' in elem.classes: # Walk through all children of this Div def make_bold(e, doc): if isinstance(e, pf.Str): return pf.Strong(e) elem.walk(make_bold) def finalize(doc): # Walk with stop condition def count_headers(e, doc): if isinstance(e, pf.Header): doc.header_count += 1 def stop_at_div(e): return isinstance(e, pf.Div) # Don't descend into Divs doc.header_count = 0 doc.walk(count_headers, stop_if=stop_at_div) pf.debug(f"Found {doc.header_count} headers (excluding those in Divs)") def main(doc=None): return pf.run_filter(action, finalize=finalize, doc=doc) ``` -------------------------------- ### Building PDF Documentation Source: https://github.com/sergiocorreia/panflute/blob/master/DISTRIBUTION.md Builds the PDF version of the documentation. This process requires a LaTeX distribution like MiKTeX and involves generating LaTeX files from reStructuredText and then compiling them into a PDF. ```shell cd docs && make.bat latex && cd build && cd latex && Makefile && cd ``` ```shell (On Windows, replace `Makefile` with a few runs of `pdflatex Panflute.tex`) ``` -------------------------------- ### Python Filter: Include External Files Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/guide.md This Panflute filter enables include directives within Pandoc documents, allowing content from external files to be inserted. It parses lines starting with '$include', reads the specified file (defaulting to '.md' extension), converts its content, and replaces the directive with the file's content. ```python """ Panflute filter to allow file includes Each include statement has its own line and has the syntax: $include ../somefolder/somefile Each include statement must be in its own paragraph. That is, in its own line and separated by blank lines. If no extension was given, ".md" is assumed. """ import os import panflute as pf def is_include_line(elem): if len(elem.content) < 3: return False elif not all (isinstance(x, (pf.Str, pf.Space)) for x in elem.content): return False elif elem.content[0].text != '$include': return False elif type(elem.content[1]) != pf.Space: return False else: return True def get_filename(elem): fn = pf.stringify(elem, newlines=False).split(maxsplit=1)[1] if not os.path.splitext(fn)[1]: fn += '.md' return fn def action(elem, doc): if isinstance(elem, pf.Para) and is_include_line(elem): fn = get_filename(elem) if not os.path.isfile(fn): return with open(fn) as f: raw = f.read() new_elems = pf.convert_text(raw) # Alternative A: return new_elems # Alternative B: # div = pf.Div(*new_elems, attributes={'source': fn}) # return div def main(doc=None): return pf.run_filter(action, doc=doc) if __name__ == '__main__': main() ``` -------------------------------- ### C Libraries for System Utilities and Performance Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section includes C libraries for system utilities and performance analysis. It features a trivial C11 threads.h implementation over POSIX threads and a library for reading virtual slide images. ```C #include #include void create_c11_thread(void* (*start_routine)(void*), void* arg) { pthread_t tid; pthread_create(&tid, NULL, start_routine, arg); printf("C11 thread created.\n"); } ``` ```C #include void open_slide_file(const char* filename) { printf("Opening virtual slide image: %s\n", filename); // openslide library usage } ``` -------------------------------- ### C Libraries for Voice Recognition and System Utilities Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet includes C libraries for voice recognition and general system utilities. It features a voice print recognition library and a tool for managing cron jobs. ```C #include void analyze_voice_print(const char* audio_file) { printf("Analyzing voice print from: %s\n", audio_file); } ``` ```Java import com.google.cloud.tools.jib.api.JibContainerBuilder; public class CronUtilsExample { public static void main(String[] args) { System.out.println("Cron utilities example running."); // Example usage of cron utilities } } ``` -------------------------------- ### Access Element Attributes Source: https://github.com/sergiocorreia/panflute/blob/master/docs/source/code.md Shows how to instantiate a standard Pandoc element and verify its attributes, including the inherited parent attribute. ```python from panflute import Str h = Str(text='something') print(h.text) print(hasattr(h, 'parent')) ``` -------------------------------- ### Loading a Pandoc Document with Panflute Source: https://github.com/sergiocorreia/panflute/blob/master/CONTRIBUTING.md Demonstrates how Panflute loads JSON input from stdin to create a Doc object, which represents the entire Pandoc document structure. ```python import panflute as pf doc = pf.load() ``` -------------------------------- ### Create and modify a Doc object Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to programmatically construct a document using the Doc class and modify its contents or metadata. ```python import panflute as pf para1 = pf.Para(pf.Str('Hello'), pf.Space, pf.Emph(pf.Str('world!'))) para2 = pf.Para(pf.Strong(pf.Str('Bold text'))) header = pf.Header(pf.Str('My Title'), level=1, identifier='title') doc = pf.Doc( header, para1, para2, metadata={'author': 'John Doe', 'title': 'Sample Document'}, format='html', api_version=(1, 23) ) print(doc.format) print(doc.api_version) print(len(doc.content)) doc.content.append(pf.Para(pf.Str('New paragraph'))) ``` -------------------------------- ### Walking a Pandoc Document Tree with Panflute Source: https://github.com/sergiocorreia/panflute/blob/master/CONTRIBUTING.md Shows how to traverse the Pandoc document tree using the `walk` method. The provided action function is applied to each element during the traversal. ```python import panflute as pf def action(elem, doc): # Process element pass doc = pf.load() doc.walk(action, doc) ``` -------------------------------- ### I/O Functions for Pandoc JSON (Python) Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates the use of Panflute's load and dump functions for reading and writing Pandoc JSON documents. Covers loading from stdin, files, and strings, as well as dumping to stdout, files, and strings. Requires panflute and json libraries. ```python import panflute as pf import json import io # Load from stdin (default) doc = pf.load() # Load from file with open('document.json', encoding='utf-8') as f: doc = pf.load(f) # Load from string json_str = '{"pandoc-api-version":[1,23],"meta":{},"blocks":[{"t":"Para","c":[{"t":"Str","c":"Hello"}]}]}' doc = pf.load(io.StringIO(json_str)) # Modify the document doc.content.append(pf.Para(pf.Str('Added paragraph'))) # Dump to stdout (default) pf.dump(doc) # Dump to file with open('output.json', 'w', encoding='utf-8') as f: pf.dump(doc, f) # Dump to string with io.StringIO() as f: pf.dump(doc, f) json_output = f.getvalue() ``` -------------------------------- ### Lua Networking and Asynchronous Framework Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet focuses on Lua projects, specifically a framework for embeddable asynchronous networking, threading, and notification. It utilizes continuation queues for efficient operation on Unix-like systems. ```Lua local cqueues = require "cqueues" cqueues.loop(function() print("Lua cqueues example running.") end) ``` -------------------------------- ### Run pylint for Code Analysis Source: https://github.com/sergiocorreia/panflute/blob/master/CONTRIBUTING.md This command runs pylint, a static code analysis tool, on the Panflute project from the root directory. The analysis report is saved to 'pylint-report.txt'. ```bash pylint panflute > pylint-report.txt ``` -------------------------------- ### Element Navigation Source: https://context7.com/sergiocorreia/panflute/llms.txt Demonstrates how to navigate the document tree using element relationships like parent, siblings, and ancestors. ```APIDOC ## Element Navigation ### Description Navigate the document tree using element relationships such as parent, siblings, and ancestors. This section provides examples of accessing related elements and the document root. ### Method N/A (Python function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python import panflute as pf def action(elem, doc): # Access parent element if elem.parent: pf.debug(f"{elem.tag} is child of {elem.parent.tag}") # Access siblings if elem.next: pf.debug(f"Next sibling: {elem.next.tag}") if elem.prev: pf.debug(f"Previous sibling: {elem.prev.tag}") # Access by offset sibling_2_ahead = elem.offset(2) sibling_1_behind = elem.offset(-1) # Access ancestors grandparent = elem.ancestor(2) # elem.parent.parent great_grandparent = elem.ancestor(3) # Get the root document root = elem.doc # Get element's position in its container if elem.index is not None: pf.debug(f"Element is at index {elem.index}") # Get the container holding this element container = elem.container if container: pf.debug(f"Container has {len(container)} elements") def main(doc=None): return pf.run_filter(action, doc=doc) ``` ### Response #### Success Response (200) N/A (Navigation methods operate on the document tree structure) #### Response Example N/A ``` -------------------------------- ### C/C++ Libraries for Performance Benchmarking and Optimization Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet contains C/C++ projects focused on performance benchmarking and optimization. It includes a tool for generating benchmark data for integer maps and a library for compiler exploitation of undefined behavior. ```C #include int main() { printf("Integer map benchmark data generation\n"); return 0; } ``` ```C // Example of code that might trigger compiler warnings or undefined behavior int undefined_behavior_example(int* ptr) { if (ptr == NULL) { return *ptr; // Dereferencing NULL pointer } return 0; } ``` -------------------------------- ### C Libraries for System Programming and Utilities Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet contains C libraries for system-level programming and utilities. It includes implementations for C11 threads, a fast file reader, and a garbage collector for C. ```C #include int my_thread_func(void* arg) { printf("C11 thread started.\n"); return 0; } ``` ```C #include void fast_read_file(const char* filename) { FILE* file = fopen(filename, "r"); if (file) { printf("Reading file: %s\n", filename); fclose(file); } } ``` -------------------------------- ### C/C++ Libraries for Web and API Interaction Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section includes C and C++ libraries for web-related functionalities, such as HTTP servers and clients, and interacting with APIs. It also covers a library for running batch processing jobs. ```C #include int main() { printf("libebb HTTP server library example\n"); return 0; } ``` ```C #include void send_http_request(const char* url) { printf("Sending HTTP request to: %s\n", url); } ``` -------------------------------- ### C Libraries for Networking and HTTP Servers Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet contains C libraries for networking and high-performance HTTP servers. It includes a lightweight HTTP server library and a simple HTTP client. ```C #include void start_http_server(int port) { printf("Starting lightweight HTTP server on port %d\n", port); // libebb server implementation } ``` ```C #include void http_client_get(const char* url) { printf("Performing HTTP GET request to: %s\n", url); // Simple HTTP client logic } ``` -------------------------------- ### C++ Libraries for Game Development and Graphics Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section features C++ libraries for game development and graphics. It includes a C++ port of the Wave Function Collapse tiling algorithm and a library for writing SA-MP gamemodes. ```C++ #include void generate_wfc_pattern() { std::cout << "Wave Function Collapse pattern generation\n"; } ``` ```C++ // SA-MP gamemode function example void OnPlayerConnect(int playerid) { printf("Player %d connected.\n", playerid); } ``` -------------------------------- ### shell Source: https://context7.com/sergiocorreia/panflute/llms.txt Executes shell commands and returns the output. ```APIDOC ## shell ### Description Executes shell commands and returns the output. ### Method `panflute.shell()` ### Parameters - **cmd** (str or list) - The shell command to execute. If a list, it's passed directly to `subprocess.Popen`. - **msg** (bytes, optional) - Input message to be sent to the command's stdin. ### Request Example ```python import panflute as pf def action(elem, doc): if isinstance(elem, pf.CodeBlock) and 'run' in elem.classes: # Execute the code and capture output try: output = pf.shell(['python', '-c', elem.text]) result = output.decode('utf-8') return pf.CodeBlock(f"# Output:\n{result}", classes=['output']) except IOError: return pf.Para(pf.Str('Error executing code')) def main(doc=None): return pf.run_filter(action, doc=doc) # Example usage with string argument output = pf.shell('echo "Hello World"') print(output.decode('utf-8')) # Pass input via msg parameter result = pf.shell(['cat'], msg=b'Input text') print(result.decode('utf-8')) ``` ### Response Example ``` Hello World Input text ``` ``` -------------------------------- ### Panflute Filter Execution Flow Source: https://github.com/sergiocorreia/panflute/blob/master/CONTRIBUTING.md Illustrates the typical program flow when using Panflute filters. It shows how filters are initiated, how the document is loaded, traversed, and then dumped back to JSON. ```python import panflute as pf def action(elem, doc): # Your filter logic here pass if __name__ == "__main__": pf.run_filter(action) ``` -------------------------------- ### C Libraries for Monitoring and Analytics Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet features C libraries for monitoring and analytics. It includes a C port of Etsy's statsd for collecting and sending metrics, and an iOS client for the Keen IO API. ```C #include void send_metric(const char* key, int value) { printf("Sending metric: %s = %d\n", key, value); } ``` ```Objective-C #import void send_analytics_event(NSString* eventName) { // Keen IO analytics event sending logic NSLog(@"Sending analytics event: %@\n", eventName); } ``` -------------------------------- ### C Libraries for Networking and Data Structures Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This section features C libraries designed for networking, data structures, and system-level programming. It includes implementations for continuation queues, hash rings, hash tables, and serial port access. ```C #include int main() { printf("C Networking Library Example\n"); return 0; } ``` ```C struct HashRingNode { // Node structure }; void add_node(void* ring, struct HashRingNode* node) { // Add node implementation } ``` -------------------------------- ### C Libraries for Graphics and Game Development Source: https://github.com/sergiocorreia/panflute/blob/master/tests/input/awesome-c/index.md This snippet contains C libraries for graphics and game development. It includes an OpenGL-based implementation of the Marching Cubes algorithm for surface extraction and a general C graphics library. ```C #include void compute_marching_cubes(float* volume_data) { printf("GPU Marching Cubes algorithm execution\n"); // GPU computation logic } ``` ```C #include void draw_triangle(float x1, float y1, float x2, float y2, float x3, float y3) { printf("Drawing triangle at (%.1f, %.1f), (%.1f, %.1f), (%.1f, %.1f)\n", x1, y1, x2, y2, x3, y3); } ``` -------------------------------- ### Metadata Manipulation (Python) Source: https://context7.com/sergiocorreia/panflute/llms.txt Illustrates how to create, access, and modify document metadata using Panflute. It covers simple key-value pairs, complex nested structures, and specific metadata element types like MetaString, MetaBool, MetaList, MetaMap, MetaInlines, and MetaBlocks. Requires the panflute library. ```python import panflute as pf def prepare(doc): # Access existing metadata title = doc.get_metadata('title', 'Untitled') # Modify metadata directly doc.metadata['version'] = '1.0.0' doc.metadata['generated'] = True # Create complex metadata structures doc.metadata['authors'] = ['Alice', 'Bob', 'Charlie'] doc.metadata['config'] = { 'theme': 'dark', 'language': 'en', 'features': ['toc', 'numbering'] } # Create metadata elements explicitly meta_string = pf.MetaString('Hello') meta_bool = pf.MetaBool(True) meta_list = pf.MetaList('item1', 'item2', 'item3') meta_map = pf.MetaMap( ('key1', 'value1'), ('key2', 'value2'), nested=pf.MetaMap(('inner', 'value')) ) # MetaInlines and MetaBlocks for formatted content meta_inlines = pf.MetaInlines(pf.Str('Formatted'), pf.Space, pf.Emph(pf.Str('text'))) meta_blocks = pf.MetaBlocks( pf.Para(pf.Str('First paragraph')), pf.Para(pf.Str('Second paragraph')) ) ```