PureXML/Sources/Emitting/Options.swift
Mihaela Mihaljevic 6b12319c89 feat(emit): XML declaration save-option parity
Add includeXMLDeclaration, xmlVersion, encodingName, and standalone to
Emitting.Options, with a single shared xmlDeclaration computation consumed
by both the tree serializer and the incremental writer. Writer gains
writeStartDocument(). Defaults stay off so fragment output is unchanged.

Closes #34
2026-06-08 02:57:27 +02:00

60 lines
2.5 KiB
Swift

public extension PureXML.Emitting {
/// Explicit emitter options. The default is pretty-printed output with
/// two-space indentation and a self-closing tag for empty elements, and no
/// XML declaration.
struct Options: Equatable, Hashable, Sendable {
/// Whether to indent nested elements onto their own lines.
public var prettyPrint: Bool
/// The indentation unit used when ``prettyPrint`` is enabled.
public var indent: String
/// Whether childless elements collapse to `<name/>`.
public var selfCloseEmptyElements: Bool
/// Whether to emit an `<?xml ...?>` declaration (libxml2 emits one by
/// default when saving a document; PureXML defaults to off for fragments).
public var includeXMLDeclaration: Bool
/// The version written in the declaration.
public var xmlVersion: String
/// The encoding name written in the declaration, or nil to omit it.
public var encodingName: String?
/// The `standalone` flag written in the declaration, or nil to omit it.
public var standalone: Bool?
public init(
prettyPrint: Bool = true,
indent: String = " ",
selfCloseEmptyElements: Bool = true,
includeXMLDeclaration: Bool = false,
xmlVersion: String = "1.0",
encodingName: String? = "UTF-8",
standalone: Bool? = nil,
) {
self.prettyPrint = prettyPrint
self.indent = indent
self.selfCloseEmptyElements = selfCloseEmptyElements
self.includeXMLDeclaration = includeXMLDeclaration
self.xmlVersion = xmlVersion
self.encodingName = encodingName
self.standalone = standalone
}
/// Pretty-printed output with two-space indentation.
public static let `default` = Options()
/// Single-line output with no inserted whitespace.
public static let compact = Options(prettyPrint: false)
/// The `<?xml ...?>` declaration string, or nil when not requested.
var xmlDeclaration: String? {
guard includeXMLDeclaration else { return nil }
var declaration = "<?xml version=\"\(xmlVersion)\""
if let encodingName {
declaration += " encoding=\"\(encodingName)\""
}
if let standalone {
declaration += " standalone=\"\(standalone ? "yes" : "no")\""
}
return declaration + "?>"
}
}
}