API Reference

Types

TextPrompts.MetadataModeType
MetadataMode

Enum for metadata handling modes.

  • STRICT: Requires title, description, and version fields to be present and non-empty
  • ALLOW: Parses metadata if present, but doesn't require it
  • IGNORE: Treats entire file as body text, uses filename as title
TextPrompts.PromptMetaType
PromptMeta

Metadata for a prompt file.

Fields

  • title::Union{String, Nothing}: Title of the prompt
  • version::Union{String, Nothing}: Semantic version string
  • author::Union{String, Nothing}: Author of the prompt
  • created::Union{Date, Nothing}: Creation date
  • description::Union{String, Nothing}: Description of the prompt
  • extras::Union{Dict{String, Any}, Nothing}: Additional non-standard metadata fields
TextPrompts.PromptStringType
PromptString

A string type that tracks placeholders for safe formatting.

PromptString wraps a string and extracts placeholder names from it. Call it as a function or use TextPrompts.format to substitute placeholders.

Fields

  • content::String: The string content
  • placeholders::Set{String}: Set of placeholder names extracted from content

Examples

ps = PromptString("Hello, {name}!")
ps(; name="World")  # "Hello, World!"
TextPrompts.PromptType
Prompt

A loaded prompt with metadata and content.

Prompt is callable - call it with keyword arguments to substitute placeholders and get a formatted string.

Fields

  • path::String: Path to the source file
  • meta::PromptMeta: Metadata extracted from front-matter
  • prompt::PromptString: The prompt content

Convenience Properties

  • placeholders: Set of placeholder names (delegates to prompt.placeholders)
  • content: Raw string content (delegates to prompt.content)

Examples

prompt = load_prompt("greeting.txt")

# Call as a function to format (recommended)
result = prompt(; name="World", day="Monday")

# Access properties
prompt.placeholders  # Set(["name", "day"])
prompt.content       # Raw template string
prompt.meta.title    # Metadata
TextPrompts.SectionType
Section

A parsed section of a document (markdown heading, XML tag, or preamble).

Fields

  • kind::String: Section kind – "preamble", "markdown", or "xml"
  • tag_name::String: XML tag name (empty for non-XML sections)
  • heading::String: Section heading text
  • anchor_id::String: Unique anchor identifier for the section
  • level::Int: Heading level (1-6 for markdown, nesting depth for XML, 0 for preamble)
  • start_line::Int: 1-based start line number
  • end_line::Int: 1-based end line number
  • char_count::Int: Character count of the section body
  • parent_idx::Int: 0-based index of the parent section (-1 for top-level)
  • children::Vector{Int}: 0-based indices of child sections
  • links::Vector{Link}: Links found within the section
TextPrompts.LinkType
Link

A hyperlink found within a section.

Fields

  • target::String: The URL or path target of the link
  • fragment::String: The fragment (anchor) part of the link
  • label::String: The display label of the link
  • line::Int: The 1-based line number where the link appears
TextPrompts.FrontmatterBlockType
FrontmatterBlock

A parsed front-matter block from the beginning of a document.

Fields

  • raw::String: The raw front-matter content (without delimiters)
  • format::String: The detected format – "yaml" or "toml"
  • title::String: The title extracted from the front-matter (empty if not found)
  • start_line::Int: 1-based start line number (including opening delimiter)
  • end_line::Int: 1-based end line number (including closing delimiter)
TextPrompts.ParseResultType
ParseResult

The result of parsing a document into sections via parse_sections.

Fields

  • sections::Vector{Section}: Ordered list of parsed sections
  • anchors::Dict{String, Int}: Map from anchor ID to 0-based section index
  • duplicate_anchors::Dict{String, Vector{Int}}: Anchor IDs that appear more than once
  • frontmatter::Union{FrontmatterBlock, Nothing}: Parsed front-matter block, if present
  • total_chars::Int: Total character count of the document body (excluding front-matter)

Loading and Saving

TextPrompts.load_promptFunction
load_prompt(path; meta=nothing) -> Prompt

Load a single prompt file.

Arguments

  • path: Path to the prompt file (String or AbstractString)
  • meta: Metadata mode - can be MetadataMode, Symbol (:strict, :allow, :ignore), String ("strict", "allow", "ignore"), or nothing (uses global default)

Returns

A Prompt object with parsed metadata and content. The returned Prompt is callable - use prompt(; kwargs...) to substitute placeholders.

Throws

  • FileMissingError: If file doesn't exist
  • EmptyContentError: If file has no content
  • MalformedHeaderError: If front-matter is malformed
  • InvalidMetadataError: If TOML parsing fails
  • MissingMetadataError: If required fields missing in strict mode

Examples

# Load with global default mode
prompt = load_prompt("prompts/greeting.txt")

# Load with specific mode
prompt = load_prompt("prompts/simple.txt"; meta=:ignore)

# Access prompt content
println(prompt.prompt)
println(prompt.meta.title)

# Format with placeholders - call the prompt as a function
result = prompt(; name="World")

# Use with PromptingTools
using PromptingTools
msg = prompt(; name="World") |> SystemMessage
TextPrompts.load_sectionFunction
load_section(path, anchor_id::AbstractString; meta=nothing) -> Prompt

Load a specific section from a prompt file by its anchor ID.

Arguments

  • path: Path to the prompt file
  • anchor_id::AbstractString: The anchor ID of the section to load
  • meta: Metadata mode (see load_prompt for details)

Returns

A Prompt object containing only the section's content.

Throws

  • FileMissingError: If file doesn't exist
  • TextPromptsError: If the section is not found

Examples

prompt = load_section("prompts/multi.txt", "system")
prompt = load_section("prompts/multi.txt", "examples"; meta=:ignore)
TextPrompts.save_promptFunction
save_prompt(path, content::AbstractString; format::Symbol=:toml)

Save a string as a prompt file with template metadata.

Arguments

  • path: Path where to save the prompt file
  • content::AbstractString: The prompt content to save
  • format::Symbol=:toml: Output format for front-matter (:toml or :yaml)
save_prompt(path, prompt::Prompt; format::Symbol=:toml)

Save a Prompt object to a file, preserving its metadata.

Arguments

  • path: Path where to save the prompt file
  • prompt::Prompt: The Prompt object to save
  • format::Symbol=:toml: Output format for front-matter (:toml or :yaml)

Formatting

TextPrompts.formatFunction
(s::PromptString)(; skip_validation::Bool=false, kwargs...) -> String
format(s::PromptString; skip_validation::Bool=false, kwargs...) -> String

Format the prompt string by substituting placeholders with the given values.

The recommended way is to call the PromptString as a function. The format function is also available but not exported to avoid clashes with other packages.

Arguments

  • skip_validation::Bool=false: If true, allows partial formatting with missing placeholders
  • kwargs...: Keyword arguments matching placeholder names

Returns

A formatted string with placeholders replaced.

Throws

  • PlaceholderError: If skip_validation=false and not all placeholders have values

Examples

ps = PromptString("Hello, {name}!")

# Recommended: call as a function
ps(; name="World")  # "Hello, World!"

# Alternative: use format (not exported, use TextPrompts.format)
TextPrompts.format(ps; name="World")  # "Hello, World!"

# Partial formatting
ps2 = PromptString("Hello, {name}! Today is {day}.")
ps2(; name="World", skip_validation=true)  # "Hello, World! Today is {day}."
(p::Prompt)(; skip_validation::Bool=false, kwargs...) -> String
format(p::Prompt; skip_validation::Bool=false, kwargs...) -> String

Format the prompt by substituting placeholders with the given values.

The recommended way is to call the Prompt as a function. The format function is also available but not exported to avoid clashes with other packages.

Arguments

  • skip_validation::Bool=false: If true, allows partial formatting with missing placeholders
  • kwargs...: Keyword arguments matching placeholder names

Returns

A formatted string with placeholders replaced.

Examples

prompt = load_prompt("greeting.txt")  # Contains "Hello, {name}!"

# Recommended: call as a function
prompt(; name="World")  # "Hello, World!"

# Alternative: use format (not exported)
TextPrompts.format(prompt; name="World")  # "Hello, World!"

# Use with PromptingTools
using PromptingTools
msg = prompt(; name="World") |> SystemMessage

Section Parsing

TextPrompts.parse_sectionsFunction
parse_sections(text::Union{AbstractString, Vector{UInt8}}) -> ParseResult

Parse a document into sections, detecting markdown headings, XML tags, and frontmatter.

TextPrompts.generate_slugFunction
generate_slug(heading::AbstractString) -> String

Generate a URL-friendly slug from a heading string. Strips markdown links, HTML tags, and formatting characters, then normalizes.

TextPrompts.normalize_anchor_idFunction
normalize_anchor_id(id::AbstractString) -> String

Normalize a string into a canonical anchor ID. Lowercases, keeps [a-z0-9], replaces runs of other chars with underscore, strips trailing underscores. Returns "section" if result is empty.

TextPrompts.inject_anchorsFunction
inject_anchors(text::Union{AbstractString, Vector{UInt8}}) -> Tuple{String, ParseResult}

Insert <a id="..."></a> tags before markdown headings that don't have anchors. Returns the modified text and a fresh ParseResult.

TextPrompts.render_tocFunction
render_toc(result::ParseResult, path::AbstractString) -> String

Render a table of contents from a ParseResult.

TextPrompts.get_section_textFunction
get_section_text(text::Union{AbstractString, Vector{UInt8}}, anchor_id::AbstractString) -> Union{String, Nothing}

Extract the body text of a section identified by its anchor ID. Returns nothing if the section is not found.

Configuration

TextPrompts.set_metadataFunction
set_metadata(mode::Union{MetadataMode, Symbol, String})

Set the global metadata handling mode.

Arguments

  • mode: Can be a MetadataMode enum value, a Symbol (:strict, :allow, :ignore), or a String ("strict", "allow", "ignore")

Examples

set_metadata(STRICT)
set_metadata(:allow)
set_metadata("ignore")
TextPrompts.get_metadataFunction
get_metadata() -> MetadataMode

Get the current global metadata handling mode.

Returns

The current MetadataMode.

Examples

mode = get_metadata()  # Returns MetadataMode.ALLOW by default
TextPrompts.skip_metadataFunction
skip_metadata(; skip_warning::Bool=false)

Convenience function to set metadata mode to IGNORE.

Arguments

  • skip_warning::Bool=false: If true, also disables warnings about ignored metadata

Examples

skip_metadata()  # Set mode to IGNORE
skip_metadata(skip_warning=true)  # Also disable warnings
TextPrompts.warn_on_ignored_metadataFunction
warn_on_ignored_metadata() -> Bool

Check if warnings are enabled for ignored metadata.

Returns

true if warnings are enabled, false otherwise.

Placeholder Utilities

TextPrompts.extract_placeholdersFunction
extract_placeholders(text::AbstractString) -> Set{String}

Extract placeholder names from a format string.

Handles:

  • Named placeholders: {name}
  • Positional placeholders: {0}, {1}
  • Format specifiers: {value:02d}, {price:.2f}
  • Escaped braces: {{literal}} (ignored)
  • Empty placeholders: {} (ignored)

Arguments

  • text::AbstractString: The format string to analyze

Returns

A Set{String} of unique placeholder names.

Examples

extract_placeholders("Hello, {name}!")  # Set(["name"])
extract_placeholders("{a} and {b} and {a}")  # Set(["a", "b"])
extract_placeholders("{{escaped}} and {real}")  # Set(["real"])
extract_placeholders("{0} {1} {2}")  # Set(["0", "1", "2"])
TextPrompts.get_placeholder_infoFunction
get_placeholder_info(text::AbstractString) -> NamedTuple

Get detailed information about placeholders in a format string.

Returns

A named tuple with fields:

  • count::Int: Number of unique placeholders
  • names::Set{String}: Set of placeholder names
  • has_positional::Bool: Whether there are positional placeholders (0, 1, 2, ...)
  • has_named::Bool: Whether there are named placeholders
  • is_mixed::Bool: Whether there are both positional and named placeholders

Examples

info = get_placeholder_info("Hello, {name}!")
# (count=1, names=Set(["name"]), has_positional=false, has_named=true, is_mixed=false)
TextPrompts.validate_format_argsFunction
validate_format_args(placeholders::Set{String}, provided::Dict{String, Any})

Validate that all required placeholders have values provided.

Arguments

  • placeholders::Set{String}: The set of required placeholder names
  • provided::Dict{String, Any}: The provided argument values

Throws

  • PlaceholderError: If any placeholders are missing values