API Reference
Types
TextPrompts.MetadataMode — Type
MetadataModeEnum for metadata handling modes.
STRICT: Requires title, description, and version fields to be present and non-emptyALLOW: Parses metadata if present, but doesn't require itIGNORE: Treats entire file as body text, uses filename as title
TextPrompts.PromptMeta — Type
PromptMetaMetadata for a prompt file.
Fields
title::Union{String, Nothing}: Title of the promptversion::Union{String, Nothing}: Semantic version stringauthor::Union{String, Nothing}: Author of the promptcreated::Union{Date, Nothing}: Creation datedescription::Union{String, Nothing}: Description of the promptextras::Union{Dict{String, Any}, Nothing}: Additional non-standard metadata fields
TextPrompts.PromptString — Type
PromptStringA 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 contentplaceholders::Set{String}: Set of placeholder names extracted from content
Examples
ps = PromptString("Hello, {name}!")
ps(; name="World") # "Hello, World!"TextPrompts.Prompt — Type
PromptA 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 filemeta::PromptMeta: Metadata extracted from front-matterprompt::PromptString: The prompt content
Convenience Properties
placeholders: Set of placeholder names (delegates toprompt.placeholders)content: Raw string content (delegates toprompt.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 # MetadataTextPrompts.Section — Type
SectionA 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 textanchor_id::String: Unique anchor identifier for the sectionlevel::Int: Heading level (1-6 for markdown, nesting depth for XML, 0 for preamble)start_line::Int: 1-based start line numberend_line::Int: 1-based end line numberchar_count::Int: Character count of the section bodyparent_idx::Int: 0-based index of the parent section (-1 for top-level)children::Vector{Int}: 0-based indices of child sectionslinks::Vector{Link}: Links found within the section
TextPrompts.Link — Type
LinkA hyperlink found within a section.
Fields
target::String: The URL or path target of the linkfragment::String: The fragment (anchor) part of the linklabel::String: The display label of the linkline::Int: The 1-based line number where the link appears
TextPrompts.FrontmatterBlock — Type
FrontmatterBlockA 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.ParseResult — Type
ParseResultThe result of parsing a document into sections via parse_sections.
Fields
sections::Vector{Section}: Ordered list of parsed sectionsanchors::Dict{String, Int}: Map from anchor ID to 0-based section indexduplicate_anchors::Dict{String, Vector{Int}}: Anchor IDs that appear more than oncefrontmatter::Union{FrontmatterBlock, Nothing}: Parsed front-matter block, if presenttotal_chars::Int: Total character count of the document body (excluding front-matter)
Loading and Saving
TextPrompts.load_prompt — Function
load_prompt(path; meta=nothing) -> PromptLoad a single prompt file.
Arguments
path: Path to the prompt file (String or AbstractString)meta: Metadata mode - can beMetadataMode,Symbol(:strict,:allow,:ignore),String("strict", "allow", "ignore"), ornothing(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 existEmptyContentError: If file has no contentMalformedHeaderError: If front-matter is malformedInvalidMetadataError: If TOML parsing failsMissingMetadataError: 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") |> SystemMessageTextPrompts.load_section — Function
load_section(path, anchor_id::AbstractString; meta=nothing) -> PromptLoad a specific section from a prompt file by its anchor ID.
Arguments
path: Path to the prompt fileanchor_id::AbstractString: The anchor ID of the section to loadmeta: Metadata mode (seeload_promptfor details)
Returns
A Prompt object containing only the section's content.
Throws
FileMissingError: If file doesn't existTextPromptsError: 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_prompt — Function
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 filecontent::AbstractString: The prompt content to saveformat::Symbol=:toml: Output format for front-matter (:tomlor: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 fileprompt::Prompt: The Prompt object to saveformat::Symbol=:toml: Output format for front-matter (:tomlor:yaml)
Formatting
TextPrompts.format — Function
(s::PromptString)(; skip_validation::Bool=false, kwargs...) -> String
format(s::PromptString; skip_validation::Bool=false, kwargs...) -> StringFormat 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 placeholderskwargs...: Keyword arguments matching placeholder names
Returns
A formatted string with placeholders replaced.
Throws
PlaceholderError: Ifskip_validation=falseand 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...) -> StringFormat 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 placeholderskwargs...: 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") |> SystemMessageSection Parsing
TextPrompts.parse_sections — Function
parse_sections(text::Union{AbstractString, Vector{UInt8}}) -> ParseResultParse a document into sections, detecting markdown headings, XML tags, and frontmatter.
TextPrompts.generate_slug — Function
generate_slug(heading::AbstractString) -> StringGenerate a URL-friendly slug from a heading string. Strips markdown links, HTML tags, and formatting characters, then normalizes.
TextPrompts.normalize_anchor_id — Function
normalize_anchor_id(id::AbstractString) -> StringNormalize 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_anchors — Function
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_toc — Function
render_toc(result::ParseResult, path::AbstractString) -> StringRender a table of contents from a ParseResult.
TextPrompts.get_section_text — Function
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_metadata — Function
set_metadata(mode::Union{MetadataMode, Symbol, String})Set the global metadata handling mode.
Arguments
mode: Can be aMetadataModeenum value, a Symbol (:strict,:allow,:ignore), or a String ("strict", "allow", "ignore")
Examples
set_metadata(STRICT)
set_metadata(:allow)
set_metadata("ignore")TextPrompts.get_metadata — Function
get_metadata() -> MetadataModeGet the current global metadata handling mode.
Returns
The current MetadataMode.
Examples
mode = get_metadata() # Returns MetadataMode.ALLOW by defaultTextPrompts.skip_metadata — Function
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 warningsTextPrompts.warn_on_ignored_metadata — Function
warn_on_ignored_metadata() -> BoolCheck if warnings are enabled for ignored metadata.
Returns
true if warnings are enabled, false otherwise.
Placeholder Utilities
TextPrompts.extract_placeholders — Function
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_info — Function
get_placeholder_info(text::AbstractString) -> NamedTupleGet detailed information about placeholders in a format string.
Returns
A named tuple with fields:
count::Int: Number of unique placeholdersnames::Set{String}: Set of placeholder nameshas_positional::Bool: Whether there are positional placeholders (0, 1, 2, ...)has_named::Bool: Whether there are named placeholdersis_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_args — Function
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 namesprovided::Dict{String, Any}: The provided argument values
Throws
PlaceholderError: If any placeholders are missing values