gofastcore

package module
v0.1.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: MIT Imports: 17 Imported by: 9 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-fast-core

The shared document model and extractor interface for the go-fast-* extraction libraries. Standard library only.

Every extractor (go-fast-pdf, go-fast-ooxml, go-fast-odf, go-fast-html, go-fast-rtf, go-fast-email, go-fast-msbin, go-fast-xml) returns the same *gofastcore.Document, so chunkers, indexers and knowledge-graph builders are written once and work for every format.

import "github.com/AOShei/go-fast-core" // package gofastcore

Status: module v0.1.11, schema version 0.2. The module version is the Go module's tag; the schema version is the schema_version in every document and changes only as Schema evolution says. Schema 0.1 was agreed with the PDF extractor over two review rounds on 2026-11-18. Schema 0.2 (2026-11-20) replaced the hidden-text verdicts with what a file declares about display; see What the file declares. Changes are in CHANGELOG.md.

Series conventions

  • Naming. Every package carries the brand prefix: gofastcore, gofastpdf, gofasthtml. No package in the series shares a name with a standard library package, so callers never need an import alias.
  • Layout. A library's public API is in its module root. Implementation goes under internal/, the CLI under cmd/. No pkg/ directory.
  • Format-specific settings. Options holds only what every format understands. Settings for one format (for PDF: memory mapping, a cache budget) are fields on that library's extractor value: (&gofastpdf.Extractor{...}).Extract(...).
  • Dependencies. go-fast-core imports only the standard library. A library's package imports only the standard library and go-fast-core, never another extractor; its command may import other go-fast extractors to hand on embedded documents (see Embedded documents). Any other dependency must be challenged.
  • Pinned versions. A library requires go-fast-core, and a command other go-fast modules, at a tag or at the pseudo-version of a pushed commit. No replace directive or go.work file is committed.
  • Bounded input. Every input is read within Options.Limits: what a file decides (its size, how much it decompresses to, how much text it becomes, how many parts and how deep its embedded documents go) is bounded. Reaching a bound truncates the document with a limit.exceeded warning, or is ErrLimitExceeded when there is no document yet. The same holds for the fixed bounds a library keeps of its own (the longest field instruction it reads, the most columns of a table): what they cut or leave out is reported with limit.exceeded, never dropped silently. This covers anything that would appear in the output: text, table cells, notes, metadata values, names (authors, sheet, slide and attachment names, the name an embedded document is given), labels and addresses. A bound on data used only inside the library (a lookup key, an internal part name, a style name used only to match) loses nothing and needs no warning. A bound small enough that ordinary files reach it (a subject of 90 Chinese characters is 270 bytes) is raised, not warned about. The code is limit.exceeded, at severity error, for every such cut; a library does not report the same event under a code of its own. Warnings are bounded too: see Warnings.
  • Nothing fetched or run. The libraries never run what a file contains (macros, scripts, actions) and never fetch or send anything a file refers to. They report that it is there (input.active_content, input.external_reference).
  • Layering. The shared model is the common denominator across formats. An extractor may offer a richer native API beside it (for PDF: word and line boxes, font names and sizes, glyph positions). Those details stay out of core.
  • Preserve content. Anything that is real content, whether it carries meaning or provides context, is preserved where possible. Normalizing a representation is fine (a ligature to its letters, \r\n to \n); dropping or flattening something the author put there is not. This is why tabs are kept in text, running headers and footers are tagged instead of removed, and an attachment that cannot be extracted is still listed.
  • Report what the file declares; never judge. Content the file says is not shown, or draws with no ink, is extracted like any other and carries that declaration. The libraries do not judge whether text is visible, suspicious or safe. See What the file declares.
  • No OCR. The go-fast libraries extract what the file contains. They report what they found and leave the next step to the caller.

The model

Document
├── Source      format, name, MIME, size
├── Metadata    title, authors, dates, language, extra
├── Outline[]   the source's own table of contents (PDF bookmarks, epub nav)
├── Parts[]     the format's natural unit: page, slide, sheet, chapter, message, body;
│   │           and, last, what the file stores and shows nowhere (stored)
│   ├── Blocks[]    content in reading order
│   └── Warnings[]  what went wrong in this part
├── Children[]  embedded documents (attachments, archive members), each a full Document
└── Warnings[]  what went wrong for the document as a whole

A block has a Kind, usually Text, and kind-specific fields:

Kind Text Level Other fields
heading heading text 1–6 Marker for a numbered heading; Attrs["level"] if the source level is deeper than 6
paragraph paragraph text
list_item item text without the marker nesting depth, from 1 Ordered, Marker
table empty Table (rows of cell strings, header row count, merges, details of cells); Attrs: name, role (chart, pivot), for a chart chart, x_axis, y_axis
image alt text or description Image (id, MIME, pixel size, optional bytes)
code verbatim code Attrs["language"]
quote quoted text nesting depth, from 1
caption caption text
footnote note text Marker
formula LaTeX, UnicodeMath or plain text Attrs["notation"]: latex, unicodemath, plain
note speaker note, comment, text removed by a tracked change, field instruction, or the values of a drop-down list Attrs: type, author, date, field
header, footer running page header/footer
thematic_break empty

A thematic_break is a break between topics or scenes that the source declares: an HTML <hr>, a Markdown ---, Word's horizontal line, an empty paragraph in LibreOffice's Horizontal Line paragraph style (Horizontal_20_Line, which is how LibreOffice writes an <hr>). A named style counts as a declaration, as a heading style does. It is always native: a bordered or ruled paragraph, a drawn line or a row of asterisks is formatting, not a declared break, and no break is inferred from it (Validate rejects an inferred one). It is a boundary a chunker can split on. It has no text, is never Continued, and Markdown() writes it as ---; Text() writes nothing for it, since blocks are already separated by a blank line. Page, column and section breaks are layout, not content, and are not emitted as blocks: a paged format already has its pages as parts.

Every block may also carry:

  • Origin: native when the source declares the block's kind, level and boundaries (a docx style, an HTML tag, a tagged-PDF element, a PDF outline entry), inferred when the extractor deduced them from geometry or fonts. Absent in JSON means native. It does not cover the block's position in the reading order: a PDF image is native even though where it falls among the text is inferred.
  • Display: the reasons the file declares that content in this block is not shown (hidden) or drawn with no ink (no_ink). Absent in JSON means the file declares neither, which says nothing about whether a reader can see the text. See What the file declares.
  • Continued: this block continues the nearest block of the same kind before it: the last one of the previous part, such as a paragraph split by a page break, or the one before it in the same part, such as a table too long for one block and split by rows. A continued table has the columns of the table it continues. The renderers run a continued block on to the one it continues when that is the block written just before it, or when only footnotes stand between them (the notes at the foot of the page where a paragraph is cut): the continued block is then written first and the footnotes after it. Any other block written between the two, such as a footer included by Furniture, keeps them apart, and a part rendered by itself has no block before it.
  • Loc: where it came from. BBox for paged formats, Range (A1 notation) for sheets, Offset/Length for plain-text formats, Anchor for formats where the source itself names its blocks (a Word paragraph id, an HTML id, an e-book fragment). This is what lets a retrieval hit be cited. A table may also say where each row came from, in Table.RowLocs (JSON row_locs): empty, or one location per row.
  • Spans: inline bold/italic/link ranges over Text (optional), and the ranges that carry a Display reason (always present when the reason applies to only part of a block).
  • Attrs: format-specific key/values with no dedicated field.
Labels, notes and deep headings
  • Marker is the label a reader sees in front of a block: the label of a list item (3., (a), 4.2.1), the number of a numbered heading (2.3), the mark of a footnote. It is content (a contract refers to "clause 4.2"), it is kept out of Text, and Markdown() and Text() put it back in front: ## 2.3 Scope.

  • note blocks say what they are in Attrs, under keys every format spells the same way (constants AttrNoteType, AttrAuthor, AttrDate):

    type Meaning
    comment A reviewer's comment or annotation attached to the content
    deletion Text removed by a tracked change. The document's text is given as if the change were accepted; the removed text is kept here
    speaker The speaker's notes of a slide
    field The instruction of a field whose result is in the text (HYPERLINK ..., MERGEFIELD Name). It is never shown, but that is what a field is, not a declaration: no Display reason. It is stored data: always marked stored=field_code, so the renderers leave it out unless asked
    attribute Text a markup element keeps in an attribute rather than in its content (aria-label, title, placeholder, an image map area's alt), at the element's place, with the attribute's name in attribute. No Display reason
    headers The headers of a message that a mail program does not show, one Name: value per line. No Display reason
    mime_preamble, mime_epilogue The text of a multipart message body before its first part and after its last, which no mail program shows. No Display reason
    choices The values a control offers to choose from (a spreadsheet cell's drop-down, a drop-down form field or content control, a PDF choice field), one per line in the source's order. A list taken from cells elsewhere is given as the reference to them (=Lists!$A$1:$A$12), since those values are already in the text. It follows the control's block, or on a sheet stands at the cells it is for (Loc.Range), with the control's name in field where the source names one. No Display reason

    author and date are as the source gives them.

  • The values of type (on a note), role and stored are closed sets, the Note*, Role* and Stored* constants: every format means the same by each, so a consumer can filter on them across formats. A library writes no other value, and Validate rejects one. A value a library needs is added to core; a fact only one format has goes under a key of that library's own. role says what a block stands for when its kind alone does not: chart and pivot on a table, headers on the block of a message's headers a mail program shows, signature on a block of a message's signature.

  • A table's cells can say more than their text (Table.Cells, an entry only for a cell that has something): where the cell links to (href, with Spans), the formula whose result it shows (formula, never evaluated), and the type of the value it stores with the value where the text does not show it in full (type: number, date, bool, error, text; value), both with Options.Cells. The renderers write the links, never formulas or values: a formula can hold text nobody sees on the sheet.

  • Data the file stores and never shows is read as data, never run, evaluated or followed, with Attrs["stored"] saying what it is: pivot_cache (the records of a pivot table whose source is gone), defined_name, document_variable, custom_xml, field_code (the instruction of a field: every field note carries it, and Validate checks that), macro, markup_comment (an HTML or XML <!-- --> comment, which no reader displays; it stays where it stands; a reviewer's comment is a comment note and is not stored), form_field (a field of a form shown on no page), after_end (data after the logical end of the file: after an RTF document's closing brace, after a PDF's last %%EOF, appended to a zip; the part also carries an input.trailing_data warning), manifest_item (a resource a publication lists and no chapter shows, such as an EPUB's unused image), stylesheet (the text of a style sheet, an HTML <style>), generator (the program that wrote the file, where the file records it as data), custom_property (a property the author or a program defined, with its name in name), shape_data (the data a shape of a drawing carries and does not draw, such as Visio's shape data: a table after the shape's own text in its page), linked_data (a copy the file keeps of data from an outside source it links to, such as a Visio data recordset: a table in the stored part). StoredKindNames() lists them. Being stored records where the text came from; it sets no Display reason. What belongs to the file and to no page, sheet or slide goes in a part of kind stored: at most one, the last, with no part-level reason. Stored data that belongs to a page, sheet or slide (the scripts of a PDF page) stays in that part, marked with Attrs["stored"], so that its place is kept. The renderers leave out the stored part, and every block marked stored wherever it is, unless RenderOptions.Stored is set; RenderOptions.StoredKinds includes only the kinds it names (for example only markup_comment), in the stored part and elsewhere. To collect all stored data, check Attrs["stored"] on every block, not only the stored part. Options.Parts selects it only with the whole document, and a reader that gives parts one at a time gives it last.

  • The value of a form field or control that its own appearance does not show (a PDF form field, a Word form field or content control) is a block at its place, with the field's name in Attrs["field"] (AttrField).

  • Heading levels are 1 to 6. A source with deeper levels (Word has nine) has them clamped to 6, with the real level in Attrs["level"], and the part carries the structure.heading_level_clamped warning at severity info. Levels above six are not allowed because Markdown has none.

Design decisions
  • Flat blocks, no section tree. Hierarchy is implied by heading levels. Extractors emit in one pass and page workers stay independent.
  • Parts are self-contained. A part owns its blocks and its warnings. A page worker fills one Part with no shared state and no locking, and a part handed on by itself is complete.
  • Structure first, Markdown derived. Markdown() and Text() render the blocks. Extractors never emit Markdown strings. Markdown() writes links, of text and of table cells, as [text](<address>); other inline formatting is not rendered, and Text() has no links.
  • Provenance, not confidence. Origin says whether structure was declared or guessed. There is no numeric score: heuristics do not produce calibrated probabilities. A consumer that needs certainty treats inferred blocks as plain text and chunks by size.
  • Tables are [][]string. Merged cells put their text top-left and are listed in Merges. Numbers appear as the source displays them: thousands separators, decimals, percent and currency signs as formatted.
  • Dates and times stored as values are written in ISO 8601, whatever the display format: 2026-03-04, 2026-03-04T14:30:00, 14:30:00. This is the one exception to "as displayed", and it applies where the source holds a date as a value with a display format beside it (a spreadsheet cell), not to dates written as text. The reason is that 03/04/2026 means two different days depending on where the file was made, and the file does not always say. The exception standardises and loses nothing: every component the value holds is kept, so a cell with a time of day keeps it, and a fraction of a second is kept where there is one.
  • Furniture is kept but tagged. Running headers and footers are header/footer blocks; the renderers drop them by default.
  • Partial results beat errors. A document that is 95% readable returns with warnings. An error means nothing usable came out.

Extractor contract

  1. All strings are valid UTF-8 and follow the text conventions below.
  2. A block is at least a paragraph-sized unit, never a fragment of a line or word.
  3. Blocks are in reading order. Where the format does not declare order (PDF), order is the extractor's best inference.
  4. A top-level document has at least one part.
  5. Part.Number is the part's 1-based ordinal in the source. Numbers strictly increase but need not be contiguous: extracting pages 40–60 yields parts numbered 40 to 60.
  6. A block that runs across a part boundary is either assigned to the part where it starts or split, with Continued set on the later piece. A table too large for one block is split by rows within its part, with Continued set on the later pieces.
  7. Table is set exactly on table blocks, Image exactly on image blocks.
  8. Extract is safe to call from many goroutines and honors context cancellation.
  9. Content the file declares not shown or not inked is extracted like any other and carries the reason in Display, never dropped. Nothing else about visibility is judged. Every extractor calls part.Finish() on each finished part.
  10. Document.Parts, Part.Blocks and Table.Rows are never nil, so JSON has [] and never null. A table has at least one row and one column.
  11. Output is deterministic: the same input and options give the same document whatever Options.Workers is, including where a limit truncates it.

doc.Validate() checks everything mechanical in rules 1, 4, 5, 7 and 10, and in rule 9 that part.Finish() was called, plus spans, tables, merges, warnings, enum values and the closed sets of stored, type and role. Run it on every test fixture and fuzz output:

doc, err := gofastpdf.Extract(ctx, f, size, nil)
if err != nil { t.Fatal(err) }
if err := doc.Validate(); err != nil { t.Fatal(err) }
Text conventions
  • Text is in logical order, the order in which it is read and typed, also for right-to-left scripts. An extractor that cannot guarantee this for some input says so with a warning.
  • Soft line breaks inside a paragraph are joined with a single space. A \n in Text means a hard break.
  • End-of-line hyphenation is resolved only when the extractor is certain. Otherwise the hyphen stays and the lines are joined with no space: inter- + national gives inter-national, so a real compound such as well- + known comes out right.
  • Ligature characters are written as their letters, everywhere. The seven presentation-form ligatures U+FB00 to U+FB06 come out as ff, fi, fl, ffi, ffl, st, st in every piece of text a library extracts: block text, table cells, markers, part names, outline titles, alt text, and the title, subject, authors and keywords in the metadata. The output is for retrieval, and a search for "office" must find a document that spells it with U+FB01. Nothing wider is done: this is not compatibility normalization, and no other character is rewritten. Strings that identify or address something are left as the source has them: a link target, an image ID, an anchor, the source's file name. Use Ligature, ExpandLigatures or AppendLigatures from this package; no library keeps its own table.
  • No string contains a control character (NUL, form feed, carriage return, ...) other than \n and \t.
  • Block text is not empty and has no leading or trailing whitespace.
  • Code blocks that the source declares as code are verbatim: the ligature and whitespace rules do not apply to them, because there the character is what the author typed. Code that an extractor infers from layout (PDF) has no such claim, and its ligatures are expanded like any other text.
  • Unicode normalization form is not guaranteed (normalization is not in the standard library).

Validate enforces the rules it can check mechanically: no control characters in any string, no unexpanded ligatures in any of the text listed above (code blocks excepted), and trimmed non-empty block text.

JSON

parts, blocks and rows are always arrays, [] when empty and never null, so a consumer can iterate them without a nil check on a failed page or an unextracted child.

The model has no custom JSON marshalers, which keeps encoding at the full speed of encoding/json. The guarantee comes from the lists never being nil: New creates an empty parts list, part.Finish() makes an empty blocks list, and a table has at least one row and one column. Validate rejects a nil list.

Coordinates

Part.Width/Height and Loc.BBox describe the part as displayed: origin top-left, y increasing downward. For PDF that is the CropBox after /Rotate and UserUnit are applied, in points. A box drawn at BBox on a rendered image of the page encloses the block.

Span offsets are bytes

Span.Start and Span.End are byte offsets into the UTF-8 text, not character offsets. They always fall on character boundaries. Languages that index strings by code point must convert. In Python:

text.encode("utf-8")[span["start"]:span["end"]].decode("utf-8")
Images

Every image is a block unless the caller asks for none (ImagesNone): where a picture stands is context, its alternative text is text its author wrote, and a caller may want to look at the picture itself (ImagesData). Image.ID identifies the image resource, not the block. Equal IDs mean equal bytes, and several blocks may share one ID (a logo on every page). With ImagesData, the bytes are guaranteed only on the first block with a given ID in document order; repeats may omit them.

Warnings

A warning is a fact about what happened. It never recommends an action.

{"code": "part.image_only", "severity": "warning", "message": "1 image, no text operators"}

Warnings local to a part are in Part.Warnings; those about the whole file are in Document.Warnings. doc.AllWarnings() iterates both, and part.Has(code) tests one part.

A warning that can be raised many times in one part (once per code page, per charset label, per chapter) is raised once, with a count. As a bound for the rest, Part.Warn and Document.Warn keep at most MaxWarnings (1000) warnings on a part or a document; past it they count the rest in one last warnings.omitted warning, whose severity is the highest of those it counts.

Severity Meaning
info Something notable happened; the output is complete
warning The output is present but incomplete or degraded, or it is one of more than one way the input can be read
error Content is missing or untrustworthy

Shared codes (constants Warn*):

Code What happened
part.failed The part could not be parsed; its blocks are missing or incomplete
part.no_text The part was parsed and contains no text and no images
part.image_only The part was parsed and contains no text, but does contain image content. Reported whatever Options.Images is set to
text.tracked_changes The part has tracked changes. Its text is given as if all were accepted; each deletion is kept as a note block of type deletion
structure.heading_level_clamped The part has headings deeper than six levels; each has level 6 and its real level in Attrs["level"]
text.unmapped_glyphs Some text has no Unicode mapping in the source and appears as U+FFFD or is absent
text.control_characters_removed Control characters (Unicode Cc) with no meaning as text were removed, as the text conventions require: NUL, ESC, the C1 controls and the like, not tabs, line ends or what the format reads as white space or a break. The message says how many. Info
text.encoding_detected The input declares no character encoding and is not UTF-8; it was read in the encoding its bytes were recognised as, which the message names. An extractor uses one only where it is certain, and otherwise refuses the input. Warning
image.unsupported_encoding Image data was requested and an image uses an encoding the extractor cannot deliver; its block has no data
input.repaired The input was structurally damaged and was read by a recovery path
input.unread_content The input holds content of a kind the extractor does not read (an equation, a sound clip, a plug-in); the message names it. Warning
input.stream_damaged A stream or member of the file other than its main content (styles, properties, a manifest, a VBA project) could not be read to its end; what was read is used, and the message names it. Warning
input.decrypted The input was encrypted and was decrypted (Metadata.Encrypted is set); the message names the scheme and which password or certificate opened it. Info
input.trailing_data Data follows the logical end of the file; its text is in the stored part with Attrs["stored"] after_end. The message says how many bytes follow the end
input.active_content The input contains something meant to be run, or an instruction to run something: macros, scripts, an action that starts a program or opens a file. It is not read and never run
input.external_reference The input refers to a file or address outside itself other than by an ordinary hyperlink: a remote template, a linked picture, an action that sends or loads data. Nothing is fetched or sent
input.ambiguous The input can be read as two different documents depending on the program, such as an archive that names a member twice in two ways
table.region_split A sparse area of a sheet was written as tables of one row each instead of one mostly empty table; the message gives the count. Info
table.formula_no_value Cells hold formulas with no stored result, so they are empty; formulas are not evaluated. Info
limit.exceeded A limit was reached during extraction, one of Options.Limits or a fixed bound of the extractor; the output is cut or left out there, and the message says what
warnings.omitted More than MaxWarnings warnings were raised on the part or document; the rest are counted here, and the message begins with their number. Added by Warn at the end of the list; warnings an extractor appends to the list directly can follow it
child.not_extracted An embedded document is listed but was not extracted
child.unsupported No extractor handles the embedded document's format, or it uses an unimplemented feature
child.encrypted The embedded document is encrypted and was not opened (no password, the wrong one, or no key for the certificate it is encrypted for)
child.failed Extraction of an embedded document failed for any other reason

An extractor may add codes of its own under a format prefix, such as pdf.font_missing, for events only its format has. An event a shared code describes is always raised with that code, at the severity given here, and never with a code of the extractor's own: a caller handles "control characters were removed" with one code, whatever the format. Where a library removes control characters, decrypts, or recognises an encoding, it says so with the shared code, not silently.

This is how a caller handles scanned pages without go-fast knowing anything about OCR:

for i := range doc.Parts {
    p := &doc.Parts[i]
    if p.Has(gofastcore.WarnPartImageOnly) {
        sendToMyOCR(path, p.Number) // the caller's decision, not ours
    }
}

What the file declares

The libraries report what a file declares about its content; they do not judge whether text is visible or harmful, and the absence of a reason says nothing about either. Threat detection is outside these libraries.

Everything a file contains is extracted, including content the file says is not to be shown. Where the file declares that, the block, span, table region or part carries the reason in Display:

Reason The file declares
hidden The content is switched off: hidden formatting or the hidden attribute; a hidden sheet, row, column, slide, shape, layer or annotation; display:none
no_ink The text is drawn with no paint: no fill, full transparency, PDF text render mode 3 or 7

What counts as declared. A reason is set only where the file states it, in one switch or one value of the content or of something containing it. Following the file's own inheritance (a style, an ancestor element) to find that switch counts. If deciding needs two values compared or a threshold, it is not a declaration and is not reported: colour against background (white on white included), a size against a minimum, a box against the page or against another box, the coverage of an image, an evaluated condition. Each library's README lists, one line each, the declarations it reports for its format.

Characters are kept. Zero-width characters, Unicode tag characters, bidirectional controls and variation selectors stay in the text as the file has them, subject only to the text conventions. No reason or warning is set for them.

Scanned PDFs. The searchable text layer of a scanned page is drawn with no ink, so it carries no_ink. Excluding no_ink leaves that text out.

Where the reason is
  • Block.Display lists every reason declared anywhere in the block, so b.Display != 0 is the only test needed.
  • Part of a block. When a reason applies to only a passage, a Span with Display set marks the range; for a table, a DisplayCells region marks the cells. A reason that appears on a span or region applies only there; one that appears on none applies to the whole block. b.DisplayWhole() and b.DisplayedText(exclude) do this arithmetic.
  • Part.Display marks a whole hidden sheet or slide; its blocks carry the same reasons.
  • There is no warning for content that carries a reason. Warnings are for facts about the extraction: damage, limits, unsupported features, encryption, trailing data.
{"kind": "paragraph", "display": "hidden",
 "text": "Shown one. Hidden sentence. Shown two.",
 "spans": [{"start": 11, "end": 27, "display": "hidden"}]}

A reason added by a newer extractor decodes as unknown and is kept.

Using it

Markdown() and Text() include everything by default. To leave declared content out of rendered output:

// Everything with a declared reason:
doc.WriteText(w, &gofastcore.RenderOptions{ExcludeDisplay: gofastcore.DisplayAny})

// Hidden content only, keeping the no-ink text layer of scanned pages:
doc.WriteText(w, &gofastcore.RenderOptions{ExcludeDisplay: gofastcore.DisplayHidden})

Exclusion cuts exactly the ranges that carry the reason.

For extractor authors
  1. Set a reason only where your format declares it (the rule above), on the block, span, table region or part. List those declarations in your README, and say plainly that colour, size, position and overlap are not judged.
  2. Never merge declared content into another block without marking the range.
  3. Call part.Finish() once per finished part, including a failed or blank one. It copies Part.Display to the blocks and makes an empty blocks list non-nil. Validate fails if it was skipped.
  4. Don't remove or flag invisible characters, and never describe output as safe, suspicious or malicious.

Extractor interface

type Extractor interface {
    Formats() []string
    Extract(ctx context.Context, r io.ReaderAt, size int64, opts *Options) (*Document, error)
}

Options (zero value: text, structure and a block for every image, whole input, all CPUs):

Field Purpose
Workers Goroutines inside one document; 0 means all CPUs
Images ImagesMeta, the default: a block for every image, with its place, size and alternative text. ImagesData: the bytes too. ImagesNone: no image blocks, and so no alternative text
Spans Ask for inline formatting and links
Password Tried on encrypted input, and passed down to embedded documents. An extractor that decrypts the input sets Metadata.Encrypted (see below)
Keys Private keys (crypto.Decrypter) tried on input encrypted for a certificate: the one whose public half matches a recipient the file names. Passed down like Password
Cells Ask for the formulas, types and stored values of table cells in Table.Cells
Parts PartRange{First, Last}, inclusive part numbers; zero value means all; a range that selects nothing is ErrNoPartsSelected
Limits MaxInputBytes, MaxDecodedBytes, MaxTextBytes, MaxParts, MaxDepth. Zero means the default; negative means no limit
Child Function that extracts embedded documents; see below
Name Recorded as Source.Name
Encrypted input

An extractor that decrypts its input sets Metadata.Encrypted. The field states what the input was, not who supplied the password: it is set also when the file opens with a password its format defines for files meant to open without one (a PDF with an empty user password, an Excel workbook encrypted with VelvetSweatshop). The document also carries input.decrypted (info), whose message names the scheme and the password or certificate used; the field is what a caller tests. Input that is not decrypted is an error (ErrPasswordRequired, ErrWrongPassword, ErrKeyRequired), or child.encrypted for an embedded document.

Errors

Extractors wrap these, so test with errors.Is: ErrPasswordRequired, ErrWrongPassword, ErrKeyRequired, ErrUnsupported, ErrMalformed, ErrLimitExceeded, ErrNoPartsSelected.

ErrLimitExceeded means a limit stopped the extraction before there was anything to return. That is always so for MaxInputBytes, and it is so for any other limit reached before the input could even be identified (a decompression bomb in the part that says what the file is). A limit reached once there is a document truncates it and adds a limit.exceeded warning with severity error; an error is never returned together with a document. MaxParts returns the first MaxParts parts of the requested range, also where the part count is known up front.

How much text a file may become

A file can be small and say a great deal: one long string that every cell of a sheet refers to, a form drawn on every page of a PDF. What is repeated is stored once, so MaxDecodedBytes does not see it, and the document that results writes the text out as often as it occurs. A workbook of 110 KB can become 2 GiB of text this way.

Limits.MaxTextBytes bounds it: the text of blocks and the cells of tables, counted as often as they occur, in a document and the documents embedded in it together. The default is 256 MiB (DefaultMaxTextBytes). A part that reaches it is cut off there with limit.exceeded.

Every block takes BlockCost (128) bytes from the budget beyond its text, and every cell of a table CellCost (16) beyond its text, empty cells included: a file decides how many blocks and cells there are as freely as it decides how long a string is. A PDF page that draws one image 100,000 times needs six bytes of content for each; the 300,000 image blocks of 1.8 MB of content held 189 MB. BlockCost is about what a block takes written down with no text; CellCost is what a cell takes in memory. At the default limit a document has at most two million blocks.

Text outside blocks counts in the same way wherever the file decides both how long it is and how often it occurs: the titles of the outline, a part name that is put together for every part (a PDF page label with its prefix), list markers, link targets, the details of table cells. An extractor may instead hold such a string to the length of a name and leave it uncounted: the number of blocks and parts, which the other limits bound, then bounds it. Metadata occurs once and is not counted.

The outline is counted before the first part, and a part's name with the part, so that where a document is cut does not depend on the number of workers. When the budget is spent in the outline, the entries read so far are kept and the document carries limit.exceeded.

An extractor counts with a TextBudget:

ctx, budget := gofastcore.WithTextBudget(ctx, opts.Limits)
defer budget.Close()
...
if !budget.Take(gofastcore.BlockCost + len(text)) {
    // keep what there is, warn limit.exceeded on the part, stop reading
}
...
opts.ExtractChild(ctx, name, mime, reader, size) // this ctx: the child shares the budget

The context carries the budget to the extractor of an embedded document, of whatever library: its WithTextBudget gives it no more than its parent has left, and its Close takes what it used from its parent. Embedded documents are extracted one after another, so the result does not depend on timing. An extractor that reads a document again from the start, to cut it at the same place whatever the number of workers, calls Reset first. One that has stopped at the limit by a count of its own (an outline already cut there) calls Exhaust, so that nothing is left for what follows.

The limit on decompressed bytes is shared in the same way, for the same reason turned around: each document's own count stops a bomb, and a document that embeds thousands of bombs, each just inside the limit, would cost thousands of limits. WithDecodeBudget(ctx, opts.Limits, default) gives the budget for one reading; before an embedded document is handed to ExtractChild the extractor sees to it that the budget says what the document has left (Take as it goes, or Settle(left) from a count of its own), and the child, reading within what it is given, takes what it used from its parent on Close.

Embedded documents

An email attachment may be a PDF; a PDF may embed a spreadsheet. Extractors do not import each other. The caller injects a dispatcher as Options.Child, and an extractor hands every embedded file to opts.ExtractChild(...), appending the result to Children:

doc.Children = append(doc.Children, opts.ExtractChild(ctx, name, mime, reader, size))

ExtractChild always returns a document, so every embedded file is at least listed with its name and size. When the child was not extracted, the result has no parts and one warning whose code says why: child.not_extracted (no Child supplied, or depth limit reached), child.unsupported, child.encrypted or child.failed. The last three are chosen from the error the child extractor returned, so a dispatcher should return ErrUnsupported for formats it has no extractor for.

The renderers leave children out unless RenderOptions.Children is set. Then each child follows the document's own parts, depth first, after a line that names it (<!-- child 2: report.pdf --> in Markdown, [child 2: report.pdf] in text; a nested child is child 2.1), and the same options apply to it. JSON always has the children.

A library never imports another extractor. A command (cmd/gofast<lib>) may, to build its Child dispatcher: go-fast-email's command hands HTML and RTF bodies to go-fast-html and go-fast-rtf. The library's package still imports only core and the standard library; the module's go.mod lists the other extractors because its command needs them.

Commands

Every command offers the same flags for RenderOptions, with the same names, values and meaning: -furniture, -stored[=kinds], -part-markers, -exclude-display[=reasons] and -children (on by default). A command defines them with AddRenderFlags and sets its options with Apply, so that the list of kinds and reasons, and the parsing, are core's:

render := gofastcore.AddRenderFlags(flags)
flags.Parse(args)
ro := &gofastcore.RenderOptions{}
render.Apply(ro)
Decompression

Package inflate (github.com/AOShei/go-fast-core/inflate) decompresses deflate streams held in memory, about twice as fast as the standard library: on the deflated members of 3,783 ODT, ODS and ODP files, 3,770 MB/s against compress/flate's 1,740. It came from go-fast-pdf, where it was written and measured. It uses the standard library only.

For Output
Raw(dst, src, limit) a zip member (RFC 1951) appended to dst in one pass
Zlib(dst, src, limit) a PDF stream (RFC 1950), Adler-32 checked appended to dst in one pass
Gzip(dst, src, limit) a .gz file (RFC 1952), one member after another, CRC-32 and size checked appended to dst in one pass
NewRawReader(src, limit) a member too large to hold whole an io.Reader, holding 96 KiB; Reset reuses it; InputOffset is where the stream ended
NewGzipReader(src, limit) a .gz file too large to hold decompressed (a .tar.gz) an io.Reader, as NewRawReader
Decompressor the deflated members of a zip.Reader: zr.RegisterDecompressor(zip.Deflate, inflate.Decompressor) through a pooled NewRawReader; archive/zip checks the CRC-32

Each gives the bytes the standard library gives, also for a damaged stream: what was decompressed before the damage, with an error that says which kind it is (ErrHeader, ErrCorrupt, ErrShort, ErrChecksum). limit bounds the output; past it the output is cut and the error is ErrLimit. The tests and fuzz targets compare each with compress/flate, compress/zlib and compress/gzip. Through Decompressor, a damaged member can keep up to 32 KiB more of its output before the error than with compress/flate (or at most 4 KiB less): archive/zip drops the read that ends a member short of its size or passes it, and the reads are cut differently.

Zip archives cut short

Package ziprecover (github.com/AOShei/go-fast-core/ziprecover) opens a zip archive the same way for every library, including one cut short in transit (a stopped download, a crawl's size cap), which has lost the directory at its end. Open(r, size, limits) returns a *zip.Reader with inflate.Decompressor registered, or for a file that is not a zip, archive/zip's error (matching ErrNotZip). For a cut file it also returns a *Recovery saying what was found, and Recovery.Message gives the text of the input.repaired warning, worded the same in every library.

  • How members are found. Recovery runs only when the directory cannot be read and the file begins with a member's header. It reads the headers in order from the first byte and stops at the first offset that holds none. It never searches for things that look like headers, so a header inside a member's data (a zip stored in the archive) is never taken for a member.
  • A member whose sizes follow its data is decompressed to find where it ends, which also gives its size and CRC-32. Its directory entry is then written, and archive/zip checks every whole member's CRC-32 as usual.
  • A stored member whose sizes follow its data ends at the first descriptor after it that gives the length it would have there, is followed by a header, and holds the CRC-32 of the bytes before it. That cannot match by chance; go-fast-ooxml's code stopped at such a member, which Go's own zip writer makes (an EPUB's mimetype). If none is found, the member is taken as the one the file ends inside.
  • The member the file ends inside is kept. Reading it ends in an error after the text that is there. For a stored member cut inside its descriptor, that text includes what is there of the descriptor, at most 15 bytes.
  • A zip stored inside a cut archive. archive/zip alone would read that zip's directory as the file's own, so Open checks that the directory lists the member at the file's first byte, and recovers the file if it does not.
  • Names are the caller's to clean: an archive whose names archive/zip calls insecure (with GODEBUG=zipinsecurepath=0) is read whole, not recovered.
  • Bounds: Limits.MaxMembers, the members recovery finds (ErrTooManyMembers; a sound archive's members are the caller's to count), and Limits.MaxDecodedBytes, the decompression done to find member ends (ErrBudget). Files of 4 GiB or more are not recovered, as a directory of the plain kind cannot describe them.
  • Speed and memory. A file of up to 32 MiB is read into memory once to find member ends with inflate; a larger one is read from the file with compress/flate.

It was go-fast-ooxml's recovery, which go-fast-odf had copied.

  • Compared with that code on 12,103 ODF, OOXML and EPUB files, each cut at 13 places (156,442 cuts), it finds the same members, sizes, CRC-32s and contents, with three exceptions:
    • the 937 cuts that end just after a stored zip, which that code read as the stored zip;
    • 6 cuts of a LibreOffice test file of stored members with descriptors (dd-stored.docx), where it reads 14 to 18 members, not 12;
    • the size recorded for a member damaged inside its data, which is now the rest of the file. It reads to the same text and the same error.
  • Speed: opening those cuts takes 31% less CPU.
Number formats

Package numfmt (github.com/AOShei/go-fast-core/numfmt) shows a spreadsheet cell's value the way the cell shows it: through its number format ("#,##0.00" writes 1234.5 as 1,234.50, "0.0%" writes 0.125 as 12.5%), with up to four sections for positive numbers, negative numbers, zero and text. go-fast-ooxml (xlsx, xlsb, SpreadsheetML 2003, chart data) and go-fast-msbin (xls, chart data) use it, so that the same cell shows the same text from every format. OpenDocument files store what a cell shows, so go-fast-odf needs none. It uses the standard library only.

Parse(code) a format code, parsed; it does not fail: a code that cannot be understood gives General
General(), Builtin(id) the General format; the code of a built-in format by its number
Format.Number(dst, v, date1904) appends v as the format shows it, and a Result: Shown, Blank (the format shows nothing, so the value is written in full and the caller can say the cell hides it) or Date
Format.Text(dst, s) appends a cell's text as the format shows it
AppendGeneral(dst, v) appends v in General: its digits, up to the fifteen a spreadsheet keeps
Format.PlainText(), Format.IsDate() what the format is
NewCache(entries), Cache.Number(f, dst, v, date1904), Cache.Reset() remembers what Format.Number made of recent values; see below

Two things are not as displayed, on purpose. Dates and times are written in ISO 8601 whatever the format, since 03/04/2026 names two days depending on where the file was made. Padding (space the width of a digit, a character repeated to fill the cell) is written as one space, and space at the ends is removed. Numbers are rounded on their fifteen significant digits, half away from zero, as a spreadsheet does, so 0.1+0.2 shows as 0.3.

The behaviour is held to what LibreOffice shows: testdata/libreoffice.tsv has 7,392 pairs of format and value with LibreOffice's text, and the tests check every one. go-fast-ooxml's TestNumberFormatTable -update writes the table, from a workbook LibreOffice shows. It was go-fast-ooxml's engine, which go-fast-msbin had copied, moved here unchanged.

A cache, for a sheet's repeated values. A column often holds the same amount, date or code many times. Cache.Number(f, dst, v, date1904) gives what f.Number(dst, v, date1904) gives, always, and copies the text when the same format, value and date system came recently. The key is the *Format, so the formats must be parsed once per workbook, not once per cell.

  • Size. NewCache(entries) takes the most entries the table may grow to, rounded down to a power of two, at most 2^20. Under one gives the nil *Cache, which remembers nothing and is Format.Number; so does a Cache not made by NewCache. The table starts at 64 entries and doubles, keeping its entries, each time it has missed as many values as it has entries. An entry is 24 bytes, plus its text in a buffer bounded at 64 bytes an entry. A full table of 4,096 entries holds about 368 KB.
  • One per sheet reader. A Cache is not safe for concurrent use. Reset empties it when a sheet begins and keeps its memory; a reader that makes a new sheet reader for each sheet can keep its caches in a sync.Pool between sheets.
  • The size is the library's choice, a trade of memory for speed measured in each library. A cache too small for a sheet's distinct values can cost more than it saves. go-fast-msbin measured its 1,111-workbook batch 7.9% faster with 4,096 entries (all workers), go-fast-ooxml its Common Crawl batch 1.6% faster with 256 (one worker), with the output unchanged.
Shared readers

Code that more than one library needs lives here once, so that a fix is made once and every library reads the same bytes the same way. Each package came from the libraries that had a copy of it; where the copies differed, the one here keeps every fix.

Package What it reads Came from
charset text in a character encoding: UTF-8, UTF-16, the Windows code pages, Mac Roman, the WHATWG Encoding Standard's single-byte encodings, Shift_JIS, GBK, GB18030, EUC-KR, Big5 (with HKSCS), EUC-JP and ISO-2022-JP; by label (Lookup), by Windows code page (CodePage) or by a font's character set (ForCharset); whole (Decode, with a map back to source offsets), in pieces (Decoder, NewReader), a byte at a time (Decoder.Byte, PageDecoder for code pages that change from byte to byte) or as a string (DecodeCodePage); and what decides an encoding (SniffText, and SniffHTML with the HTML standard's <meta> prescan) go-fast-html (shared with go-fast-xml), go-fast-email, go-fast-rtf (shared with go-fast-msbin), go-fast-ooxml
xmlscan XML, as a stream of tokens, in bounded memory, without allocating per token; namespaces by number (Options.Spaces) and by URI go-fast-ooxml, go-fast-odf, go-fast-xml
opc the container of the Open Packaging Conventions (Word, Excel, PowerPoint, Visio, XPS): the zip archive, the content-types table, relationships, part names, interleaved parts, the decompression budget go-fast-ooxml
cfb compound files (the container of the binary Office formats, Outlook messages, encrypted Office files), and writes them (Write, Export); cfbtest builds them for tests go-fast-msbin, go-fast-email, go-fast-ooxml
clean strings to the text conventions: valid UTF-8, no control characters, line ends as line feeds, ligatures as letters, labels bounded (MaxLabel, 4 KiB) go-fast-ooxml and go-fast-msbin, go-fast-odf
symbol the characters of the Symbol, Wingdings and Webdings fonts, as Unicode go-fast-ooxml, go-fast-msbin
label list labels: bullets, Roman numerals, letters as Office repeats them (Letters: AA, BB) and in base 26 (Alpha: AA, AB) go-fast-ooxml, go-fast-msbin
hidden what the file declares about the display of a paragraph's spans, placed on blocks and spans go-fast-ooxml, go-fast-msbin
vba the source of a VBA project, in any storage of a compound file (Read) or a vbaProject.bin (ReadBytes); vbatest builds projects for tests go-fast-msbin, go-fast-ooxml

Decoding where the copies disagreed. The answer here is the WHATWG Encoding Standard's: a byte a single-byte Windows code page leaves undefined in 0x80 to 0x9F is the C1 control of the same value (0x81 in windows-1252 is U+0081), not U+FFFD; the label ISO-8859-1 means windows-1252; GBK byte 0x80 is the euro sign; Mac Roman is Apple's table (0xDB the euro sign); a lead byte followed by an ASCII byte that makes no character with it is U+FFFD and the ASCII byte is read again; the user-defined areas of code pages 932 and 936 are Private Use Area characters, and Shift_JIS byte 0x80 is U+0080.

The XML scanner's options. By default it reads as go-fast-ooxml's and go-fast-odf's scanners did: well-formed XML, any error ends the scan (ErrSyntax), comments and processing instructions are passed over, a document type declaration is accepted only if it declares nothing (no internal subset, before the root element, the only one), and an attribute's value is decoded when it is read. The encoding is the one a byte order mark or the XML declaration names, decoded by charset. What XML from anywhere needs is in options, so that a reader of Office XML does not pay for it:

Option
Recover read on through damaged markup, counting each repair in Stats.Repairs: mismatched end tags, elements left open, a stray < or &, attributes without quotes or values, markup cut off at the end; elements deeper than MaxDepth read as part of their ancestor
Markup comments, processing instructions and the document type declaration as tokens
Spans each token's offsets in the input (Span)
Resolve, ExpansionLimit, MaxEntityDepth general entities expanded, within bounds
Decoded the input is UTF-8 already, whatever its declaration says
Bindings namespace declarations in scope before the first element (a part of a Flat OPC document)
MaxAttrs, MaxValueBytes, MaxTokenBytes, MaxDepth bounds; names of open elements keep MaxNameKept bytes

Attributes are read by namespace number (Attr, AttrAt) or by URI (AttrURI, AttrURIAt). Windows are pooled: Release hands one back, Reset and ResetBytes reuse a scanner. The tests of all three scanners it came from pass, and so does the comparison with encoding/xml over the XML parts of the development corpus's zip packages (TestAgainstEncodingXML, where encoding/xml reads a part). Measured in instructions, against go-fast-ooxml's scanner on the reads of its own benchmarks: 2 to 4.5 percent more on its large generated documents, 1 to 2 percent more on a batch of corpus files (a third of the Office and OpenDocument files); against go-fast-xml's on its corpus, with Recover, Markup and Spans, 13 percent fewer.

Schema evolution

schema_version changes when a field is removed or its meaning changes. Additions do not change it, including new block kinds: a decoder that meets a kind, part kind, origin or severity it does not know maps it to that enum's Unknown value, and unknown style names are ignored. An unknown block renders as a paragraph. Re-encoding such a document writes "unknown", so the original name is lost. Validate rejects Unknown, since extractors must never emit it.

How each format maps

Format (library) Part kind Notes
pdf (go-fast-pdf) page BBox on blocks; structure is inferred unless the PDF is tagged or the outline confirms a heading; Loc.Anchor from named destinations and the /ID of structure elements
docx and wordml (go-fast-ooxml), doc (go-fast-msbin), odt and fodt (go-fast-odf), rtf (go-fast-rtf) one body Heading styles and outline levels give levels; numbered headings and list items carry Marker; comments, tracked deletions, field instructions and the values of drop-down controls become note; Loc.Anchor is the paragraph id (docx, odt) or the bookmark that starts the paragraph (rtf, doc)
pptx (go-fast-ooxml), ppt (go-fast-msbin), odp and fodp (go-fast-odf) slide Name is the slide title; speaker notes become note
vsdx (go-fast-ooxml), odg and fodg (go-fast-odf) page Name is the page name; the shapes' text. vsdx: Width and Height, shapes in reading order, with Loc.BBox where the file gives their position, a used background page as header/footer blocks on the pages in front of it, shape data as shape_data tables after each shape's text, data recordsets as linked_data tables in the stored part
xlsx and spreadsheetml (go-fast-ooxml), xls (go-fast-msbin), ods and fods (go-fast-odf) sheet Name is the sheet name; each used region is a table with Loc.Range; drop-down lists become note blocks of type choices; defined names and macro sheets go to the stored part
html, md, txt (go-fast-html) one body Loc.Offset/Length into the source; Loc.Anchor from id attributes
csv, tsv (go-fast-html) one sheet Name is the file name; the rows are a table, split by rows past 1,000 rows, each piece with Loc.Range
ipynb (go-fast-html) one body Markdown cells read as Markdown; code cells are code blocks with the notebook's language; each output follows its cell with Attrs["output"]; Loc.Anchor is the cell id
json, yaml (go-fast-html) one body The text as written, in code blocks whose language is the format, split at line ends past a size; a block per YAML document; nothing parsed
xml (go-fast-xml) one body; a profile may start more parts, body or chapter A schema with a profile (26 built in, or one the caller loads) is read as headings, lists, tables, notes and metadata, native; any other XML is read generically, a paragraph per element that holds text, inferred, with the element path in Attrs["element"]. Loc.Offset/Length are bytes of the file on every block, Table.RowLocs gives them per row, and Loc.Anchor is the id the profile names. The feed profile hands an item's HTML, newsml-g2 an item's XHTML body, boamp a notice's HTML page, and the invoice and XLIFF profiles their base64 attachments, to Options.ExtractChild: HTML as text/html or application/xhtml+xml, an attachment under its own media type
epub (go-fast-html) chapter One per spine item; nav becomes Outline
eml, msg, mbox, tnef (go-fast-email) message One part per message. For a single message every header is in Metadata.Extra; in a mailbox the headers a mail program does not show are a note of type headers. Attachments in Children

go-fast-ooxml reads the macro and template variants of docx, xlsx and pptx, binary workbooks (.xlsb), and any of these saved as one XML file (Flat OPC, with Metadata.Extra["packaging"] flat_opc), under those three format names; and Office 2003's XML formats under the names wordml (Word's XML Document) and spreadsheetml (Excel's XML Spreadsheet). It reads Visio 2013 and later under the format name vsdx: drawings, templates and stencils, with and without macros, which Source.MIME tells apart; a stencil's masters are parts after its pages. go-fast-msbin reads the templates and shows of the three binary formats, the workbooks of Excel 5 and 95 and the documents of Word 6 and 95, under the names doc, xls and ppt. go-fast-xml chooses a profile by the document's root element and names it in Metadata.Extra["xml.profile"]; its README lists the built-in profiles (Akoma Ntoso, BOAMP, Canadian federal laws, HL7 CDA, Cross Industry Invoice, CLML, DILA case law, DITA, DocBook, EU eForms, web feeds: RSS and Atom, Formex, JATS, Légifrance, NewsML-G2, NITF, patents, PubMed, S1000D, Service-Public, TED, TEI, TMX, UBL invoices, XLIFF 1.x and 2.x). Each library's README gives the details. go-fast-pdf's MIGRATION.md maps its API before the shared model to this one.

Example output

{
  "schema_version": "0.2",
  "source": {"format": "pdf", "name": "report.pdf"},
  "metadata": {"title": "Q3 Report", "authors": ["A. Writer"]},
  "outline": [{"title": "Q3 Report", "level": 1, "part": 1, "y": 72}],
  "parts": [
    {
      "kind": "page", "number": 1, "width": 612, "height": 792,
      "blocks": [
        {"kind": "heading", "level": 1, "text": "Q3 Report",
         "loc": {"bbox": {"x0": 72, "y0": 72, "x1": 300, "y1": 96}}},
        {"kind": "paragraph", "origin": "inferred", "text": "Revenue grew in every region."},
        {"kind": "table", "origin": "inferred", "table": {"header_rows": 1,
         "rows": [["Region", "Rev"], ["EMEA", "1.2M"]]}}
      ]
    },
    {
      "kind": "page", "number": 2, "width": 612, "height": 792,
      "blocks": [
        {"kind": "image", "loc": {"bbox": {"x0": 0, "y0": 0, "x1": 612, "y1": 792}},
         "image": {"id": "obj-14", "mime": "image/jpeg", "width": 2550, "height": 3300}}
      ],
      "warnings": [{"code": "part.image_only", "severity": "warning", "message": "1 image, no text operators"}]
    }
  ],
  "warnings": [{"code": "input.repaired", "severity": "info", "message": "xref rebuilt"}]
}

Deferred

  • Streaming. No shared Sink in module v0.1.0 or schema 0.2, but nothing prevents one: parts are self-contained, carry their own warnings, and need not be numbered contiguously. One conflict must be settled before a sink is designed. Some inferred structure needs the whole document (PDF heading levels need the document-wide body font size; header/footer tagging compares pages), so a streaming extractor either offers only page-local inference or runs a statistics pass first. That decides whether a sink receives final parts or provisional ones. When it is added, it should come with a serialized form (one header line, one line per part, one trailer line) for the CLI and non-Go consumers.
  • Numeric confidence. Only if measurements from the PDF layout work show that a score would be meaningful.

Documentation

Overview

Package gofastcore defines the document model and extractor interface shared by every go-fast-* extraction library.

Every extractor, whatever its input format, produces a *Document:

Document
├── Source      where the bytes came from and what format they were
├── Metadata    title, authors, dates, ...
├── Outline[]   the source's own table of contents, if it has one
├── Parts[]     the format's natural top-level unit: page, slide, sheet, ...
│   ├── Blocks[]    content in reading order: heading, paragraph, table, ...
│   └── Warnings[]  what went wrong in this part
├── Children[]  embedded documents: email attachments, archive members
└── Warnings[]  what went wrong for the document as a whole

The model is deliberately flat inside a part. Section hierarchy is not stored; it is implied by heading levels, which lets extractors emit blocks in a single pass and lets page workers run independently.

The shared model is the common denominator across formats. An extractor may offer a richer native API beside it (word boxes, fonts, glyph positions for PDF); those details do not belong here.

Contract for extractors

  • All strings are valid UTF-8 and follow the text conventions below.
  • A block is at least a paragraph-sized unit, never a fragment of a line or word.
  • Blocks appear in reading order. Where the format does not declare order (PDF), order is the extractor's best inference. Block.Origin does not cover order; it describes kind, level and boundaries only.
  • A top-level document has at least one part. Formats with no natural unit (docx, html, txt) use a single PartBody.
  • Part numbers are the 1-based ordinal of the part in the source and strictly increase. They need not be contiguous: extracting pages 40-60 yields parts numbered 40 to 60.
  • A block that runs across a part boundary is either assigned to the part where it starts or split, with Continued set on the later piece. A table too large for one block is split by rows within its part, with Continued set on the later pieces.
  • Partial extraction returns a Document with warnings, not an error. Errors are for input that yields nothing usable.
  • Content the file declares not shown or not inked is extracted like any other and carries the reason (Display), never dropped. Nothing else about visibility is judged. Every extractor calls Part.Finish on each finished part.
  • Lists that consumers iterate are never nil: Document.Parts, Part.Blocks and Table.Rows. JSON then has [] where a list is empty, never null, at no encoding cost. New and Part.Finish take care of the first two; a table has at least one row and one column.
  • Output is deterministic: the same input and options give the same Document whatever Options.Workers is, including where a limit truncates it.

Text conventions

  • Text is in logical order, the order in which it is read and typed, also for right-to-left scripts. An extractor that cannot guarantee this for some input says so with a warning.
  • Soft line breaks inside a paragraph are joined with a single space. A "\n" in Text means a hard break.
  • End-of-line hyphenation is resolved only when the extractor is certain. Otherwise the hyphen stays and the lines are joined with no space: "inter-" + "national" gives "inter-national", so that a real compound such as "well-" + "known" comes out right.
  • Presentation-form ligatures (U+FB00 to U+FB06) are written as their letters in every piece of text: block text, table cells, markers, part names, outline titles, alt text and the metadata's title, subject, authors and keywords. The output is for retrieval. Nothing wider is rewritten, and strings that identify or address something (a link target, an image ID, an anchor, a file name) are left as the source has them. See Ligature and ExpandLigatures.
  • No string contains a control character (Unicode category Cc: NUL, form feed, carriage return, ...) other than "\n" and "\t".
  • Block text is not empty and has no leading or trailing whitespace.
  • Code blocks that the source declares as code are verbatim: the ligature and whitespace rules do not apply to them. Code that an extractor infers from layout has its ligatures expanded.
  • Unicode normalization form is not guaranteed.

Document.Validate checks the mechanical parts of this contract and is intended to run in every extractor's test suite.

Index

Constants

View Source
const (
	// AttrNoteType says what a KindNote block is: one of the Note*
	// values.
	AttrNoteType = "type"
	// AttrAuthor is who wrote a note or made a tracked change, as the
	// source names them.
	AttrAuthor = "author"
	// AttrDate is when a note was written or a change made, as the
	// source writes it, normally ISO 8601.
	AttrDate = "date"
	// AttrLevel is the real level of a heading deeper than six, in
	// decimal ("8").
	AttrLevel = "level"
	// AttrLanguage is the programming language of a KindCode block.
	AttrLanguage = "language"
	// AttrName is the name the source gives a table, a pivot table or a
	// chart ("SalesTable").
	AttrName = "name"
	// AttrRole says what a block stands for when its kind alone does not
	// say: a table that is not a grid of cells the source shows as such,
	// the headers of a message, a block of a signature. One of the Role*
	// values.
	AttrRole = "role"
	// AttrChart is the type of a chart, lowercase as the source names it
	// ("bar", "line", "pie", "scatter").
	AttrChart = "chart"
	// AttrAxisX and AttrAxisY are the titles of a chart's axes.
	AttrAxisX = "x_axis"
	AttrAxisY = "y_axis"
	// AttrStored says what kind of stored, never-shown data a block is:
	// one of the Stored* values. It records where the text came from; it
	// sets no Display reason. Such a block is usually in the stored part,
	// but stored data that belongs to a page, sheet or slide (a PDF page's
	// scripts) stays in that part. The renderers leave out every block
	// marked stored, wherever it is, unless RenderOptions.Stored is set.
	AttrStored = "stored"
	// AttrNotation is the notation of a KindFormula block: one of the
	// Notation* values.
	AttrNotation = "notation"
	// AttrField is the name the source gives the form field or control
	// whose value the block is (a PDF form field, a Word form field or
	// content control).
	AttrField = "field"
)

Keys of Block.Attrs that mean the same in every format.

View Source
const (
	// RoleChart: the table is the data of a chart, as the chart's source
	// stores it. A chart's title is a KindCaption block before it.
	RoleChart = "chart"
	// RolePivot: the table is a pivot table.
	RolePivot = "pivot"
	// RoleHeaders: the block is the headers of a message that a mail
	// program shows (From, To, Date, Subject).
	RoleHeaders = "headers"
	// RoleSignature: the block is part of a message's signature, the text
	// after a line "-- ".
	RoleSignature = "signature"
)

Values of Attrs[AttrRole].

View Source
const (
	// StoredPivotCache: the records a pivot table was built from, kept in
	// the file where the source data is gone.
	StoredPivotCache = "pivot_cache"
	// StoredDefinedName: a name a workbook defines for a value, a formula
	// or a range of cells.
	StoredDefinedName = "defined_name"
	// StoredDocumentVariable: a variable a document stores for fields and
	// macros to use (Word's document variables).
	StoredDocumentVariable = "document_variable"
	// StoredCustomXML: data a program stored in the file as XML of its
	// own.
	StoredCustomXML = "custom_xml"
	// StoredFieldCode: the instruction of a field (a NoteField note, an
	// RTF index or table-of-contents entry). Every field note carries it.
	StoredFieldCode = "field_code"
	// StoredMacro: the source code of a macro or script, read as text and
	// never run.
	StoredMacro = "macro"
	// StoredMarkupComment: a comment in the file's markup (an HTML or XML
	// <!-- --> comment), which no reader displays. It stays where it
	// stands. A reviewer's comment, which is displayed, is a NoteComment
	// note and is not stored.
	StoredMarkupComment = "markup_comment"
	// StoredFormField: a field of a form that is shown on no page, such as
	// a PDF form field with no widget.
	StoredFormField = "form_field"
	// StoredAfterEnd: data that follows the logical end of the file (after
	// an RTF document's closing brace, after a PDF's last %%EOF, appended
	// to a zip archive). The part also carries WarnInputTrailingData.
	StoredAfterEnd = "after_end"
	// StoredManifestItem: a resource a publication lists in its manifest
	// and no chapter shows, such as an EPUB's image that no page uses.
	StoredManifestItem = "manifest_item"
	// StoredStylesheet: the text of a style sheet (an HTML <style>
	// element).
	StoredStylesheet = "stylesheet"
	// StoredGenerator: the name of the program that wrote the file, where
	// the file records it as data (RTF \generator).
	StoredGenerator = "generator"
	// StoredCustomProperty: a property of the document that its author or
	// a program defined, with its name in Attrs[AttrName] (RTF
	// \userprops).
	StoredCustomProperty = "custom_property"
	// StoredShapeData: the data a shape of a drawing carries and does not
	// draw (Visio's shape data, a row per label), a table after the
	// shape's own text in its page.
	StoredShapeData = "shape_data"
	// StoredLinkedData: a copy the file keeps of data from an outside
	// source it links to (a Visio data recordset), a table in the stored
	// part.
	StoredLinkedData = "linked_data"
)

Values of Attrs[AttrStored].

View Source
const (
	NotationLaTeX       = "latex"
	NotationUnicodeMath = "unicodemath" // the linear form Word uses
	NotationPlain       = "plain"
)

Values of Attrs[AttrNotation].

View Source
const (
	// NoteComment is a reviewer's comment or annotation attached to the
	// content.
	NoteComment = "comment"
	// NoteDeletion is text removed by a tracked change. The document's
	// text is given as if the change were accepted; the removed text is
	// kept here.
	NoteDeletion = "deletion"
	// NoteSpeaker is the speaker's notes of a slide.
	NoteSpeaker = "speaker"
	// NoteField is the instruction of a field whose result is in the text
	// ("HYPERLINK ...", "MERGEFIELD Name"). It follows its paragraph. The
	// instruction is never shown, but that is what a field is, not a
	// declaration: the note sets no Display reason. It is stored data:
	// every field note is marked Attrs[AttrStored] = StoredFieldCode, so
	// the renderers leave it out unless RenderOptions.Stored or
	// StoredKinds asks for it.
	NoteField = "field"
	// NoteChoices is the list of values a control offers to choose from:
	// the drop-down of a spreadsheet cell (a data validation list), a
	// drop-down form field or content control, the options of a PDF choice
	// field. Its Text is the values, one per line, in the source's order.
	// A list the source takes from cells elsewhere is given as the
	// reference to them ("=Lists!$A$1:$A$12"), since the values are
	// already in the text where those cells are. It follows the block of
	// the control, or for a sheet stands at the place of the cells it is
	// for (Loc.Range), with the control's name in Attrs[AttrField] where
	// the source names it. The values are shown to a reader who opens the
	// list; the note sets no Display reason.
	NoteChoices = "choices"
	// NoteAttribute is text a markup element keeps in an attribute rather
	// than in its content, and which a reader meets only through assistive
	// technology or by pointing at it: aria-label, title, placeholder, an
	// image map area's alt. It stands at the element's place, with the
	// attribute's name in Attrs["attribute"]. No Display reason.
	NoteAttribute = "attribute"
	// NoteHeaders: the headers of a message that a mail program does not
	// show, one "Name: value" per line. No Display reason: the format
	// declares none.
	NoteHeaders = "headers"
	// NoteMIMEPreamble and NoteMIMEEpilogue: the text of a multipart
	// message body before its first part and after its last, which no mail
	// program shows. No Display reason: the format declares none.
	NoteMIMEPreamble = "mime_preamble"
	NoteMIMEEpilogue = "mime_epilogue"
)

Values of Attrs[AttrNoteType].

View Source
const (
	BlockCost = 128
	CellCost  = 16
)

BlockCost and CellCost are what a block, and a cell of a table, take from the text budget (Limits.MaxTextBytes) beyond their text. A file decides how many blocks and cells there are as freely as it decides how long a string is: a PDF page that draws one image a hundred thousand times needs six bytes of content for each, and a sheet can have a grid of empty cells. BlockCost is about what a block takes written down with no text (in the PDF corpus, a document's JSON is 157 bytes a block beyond its text); CellCost is what a cell takes in memory, more than it takes in JSON. At the default limit a document has at most two million blocks.

View Source
const (
	// WarnPartFailed: the part could not be parsed. Its blocks are missing
	// or incomplete. Severity error.
	WarnPartFailed = "part.failed"

	// WarnPartNoText: the part was parsed and contains no text and no
	// images, e.g. a blank page or a page of vector drawing only.
	WarnPartNoText = "part.no_text"

	// WarnPartImageOnly: the part was parsed and contains no text, but
	// does contain image content. This is what a scanned page looks like.
	// It is reported whatever Options.Images is set to.
	WarnPartImageOnly = "part.image_only"

	// WarnTextUnmappedGlyphs: some text has no Unicode mapping in the
	// source and appears as U+FFFD or is absent.
	WarnTextUnmappedGlyphs = "text.unmapped_glyphs"

	// WarnTextControlCharactersRemoved: control characters (Unicode Cc)
	// with no meaning as text were removed from extracted text, as the
	// text conventions require: NUL, ESC, the C1 controls and the like.
	// Not counted are those the format reads as something: tab, line
	// ends (a carriage return), and white space or a break (a form feed
	// in HTML, or between pages). The message says how many. Severity
	// info. Every extractor that removes any raises it, once per part or
	// document with the count.
	WarnTextControlCharactersRemoved = "text.control_characters_removed"
	// WarnTextEncodingDetected: the input declares no character encoding
	// and is not valid UTF-8; it was read in the encoding its bytes were
	// recognised as, which the message names, with how to give one
	// instead. Severity warning: the encoding is not declared, though an
	// extractor uses one only where it is certain and refuses the input
	// otherwise.
	WarnTextEncodingDetected = "text.encoding_detected"
	// WarnTextTrackedChanges: the part has tracked changes. Its text is
	// given as if all were accepted; each deletion is kept as a note block
	// of type NoteDeletion.
	WarnTextTrackedChanges = "text.tracked_changes"

	// WarnHeadingLevelClamped: the part has headings deeper than six
	// levels. Each has Level 6 and its real level in Attrs[AttrLevel].
	// Severity info: nothing is lost.
	WarnHeadingLevelClamped = "structure.heading_level_clamped"

	// WarnImageUnsupportedEncoding: image data was requested
	// (ImagesData) and an image uses an encoding the extractor cannot
	// deliver; its block is present without data.
	WarnImageUnsupportedEncoding = "image.unsupported_encoding"

	// WarnInputRepaired: the input was structurally damaged and was read
	// by a recovery path. Severity info if nothing is known to be lost.
	WarnInputRepaired = "input.repaired"

	// WarnInputUnreadContent: the input holds content of a kind the
	// extractor does not read (an equation, a sound or video clip, a
	// plug-in, a dialog sheet); the message names the kind and how many.
	// It is not in the output. Severity warning.
	WarnInputUnreadContent = "input.unread_content"
	// WarnInputStreamDamaged: a stream or member of the file other than
	// its main content (styles, numbering, notes, document properties, a
	// manifest, a VBA project, an embedded object) could not be read to
	// its end; what was read before the damage is used. The message names
	// it. "Stream" is a piece of the file, not a Part of the document.
	// Severity warning.
	WarnInputStreamDamaged = "input.stream_damaged"
	// WarnInputDecrypted: the input was encrypted and was decrypted, and
	// Metadata.Encrypted is set. The message names the scheme, and which
	// password (the caller's, or one the format defines for files meant to
	// open without one) or certificate opened it. Severity info.
	WarnInputDecrypted = "input.decrypted"
	// WarnInputActiveContent: the input contains something meant to be
	// run, or an instruction to run something: macros, scripts, an action
	// that starts a program or opens a file (a PDF Launch action). It is
	// not read and never run. An instruction that names a file or address
	// outside the input is also WarnInputExternalReference; the two are
	// separate facts.
	WarnInputActiveContent = "input.active_content"

	// WarnInputExternalReference: the input refers to a file or address
	// outside itself other than by an ordinary hyperlink: a remote
	// template, a linked picture, a linked object, an action that sends
	// form data to or loads data from an address. Nothing is fetched or
	// sent.
	WarnInputExternalReference = "input.external_reference"

	// WarnInputAmbiguous: the input can be read as two different
	// documents, depending on the program: an archive that names a member
	// twice in two ways, or has two members with one name. Which reading
	// this extractor takes is in its documentation.
	WarnInputAmbiguous = "input.ambiguous"

	// WarnInputTrailingData: data follows the logical end of the file
	// (after an RTF document's closing brace, after a PDF's last %%EOF,
	// appended to a zip archive). Its text is in the stored part with
	// Attrs[AttrStored] = StoredAfterEnd. The message says how many bytes
	// follow the end.
	WarnInputTrailingData = "input.trailing_data"

	// WarnTableRegionSplit: an area of a sheet whose cells are spread so
	// thinly that the rectangle around them is mostly empty was not
	// written as one table: each run of cells side by side in a row is a
	// table of one row. The message gives the sheet and the count.
	// Severity info: no cell is lost.
	WarnTableRegionSplit = "table.region_split"
	// WarnTableFormulaNoValue: cells hold formulas with no stored result
	// (a program wrote the file without calculating it), so they are
	// empty; formulas are not evaluated, and are in Table.Cells when
	// Options.Cells is set. One warning per part with the count.
	// Severity info.
	WarnTableFormulaNoValue = "table.formula_no_value"
	// WarnLimitExceeded: a limit was reached during extraction and the
	// output is cut or left out at that point. The limit is one of
	// Options.Limits or a fixed bound of the extractor (the longest field
	// instruction it keeps, the most columns of a table it reads); the
	// message says which, and what was left out. It covers anything that
	// would appear in the output: text, cells, notes, metadata values,
	// names, labels and addresses; a bound on data used only inside the
	// extractor needs no warning. Severity error, for every such cut.
	WarnLimitExceeded = "limit.exceeded"

	// WarnWarningsOmitted: more warnings were raised on the part or the
	// document than MaxWarnings, and the rest are counted here instead of
	// listed. Part.Warn and Document.Warn add it at the end of the list
	// (warnings appended to the list directly can follow it); extractors
	// do not emit it themselves. Its message begins with the
	// number of warnings it counts, and its severity is the highest of
	// theirs.
	WarnWarningsOmitted = "warnings.omitted"

	// WarnChildNotExtracted: an embedded document is listed in Children
	// with its name and size but was not extracted, because no child
	// extractor was supplied, the depth limit was reached, or the
	// extractor had nothing to hand over (a limit stopped it first).
	WarnChildNotExtracted = "child.not_extracted"

	// WarnChildUnsupported: no extractor handles the embedded document's
	// format, or it uses a feature that is not implemented. It is listed
	// in Children without content.
	WarnChildUnsupported = "child.unsupported"

	// WarnChildEncrypted: the embedded document is encrypted and was not
	// opened: no password was supplied, the one supplied does not open
	// it, or no key in Options.Keys matches a recipient it names.
	// Severity error.
	WarnChildEncrypted = "child.encrypted"

	// WarnChildFailed: extraction of an embedded document was attempted
	// and failed for any other reason. Severity error.
	WarnChildFailed = "child.failed"
)

Warning codes shared by all extractors. Each describes an observed fact about the input or the output.

View Source
const DefaultMaxDepth = 4

DefaultMaxDepth is how deeply embedded documents are followed when Limits.MaxDepth is zero: an attachment inside an archive inside an email is depth 2.

View Source
const DefaultMaxTextBytes = 256 << 20

DefaultMaxTextBytes is the text a document and the documents embedded in it may hold when Limits.MaxTextBytes is zero. It is some ten times the text of a workbook of two million cells or of a book of a million and a half words.

View Source
const MaxWarnings = 1000

MaxWarnings is the number of warnings Part.Warn and Document.Warn keep on one part or one document. Past it, each further warning is counted in a single warning with the code warnings.omitted, added at the end of the list, whose severity is the highest of those it counts and whose message begins with their number. The count is read back from that warning, so it survives a copy of the part and a round trip through JSON. It stays last unless an extractor appends to Warnings directly after it; such appends are not bounded by MaxWarnings, and an extractor that makes many of them past the bound may get a second summary. The count stops at 999,999,999. Past the bound Warn adds no entry and updates the summary in place: Has does not see a warning that was only counted, code that remembers the index of a warning it raises must check it, and two copies of a part that share one Warnings array share the summary, or overwrite each other's. A summary copied in from another part's list counts on for this one. An extractor should still merge warnings that repeat, with a count, rather than rely on this bound.

View Source
const SchemaVersion = "0.2"

SchemaVersion identifies the shape of the serialized model. It changes when a field is removed or its meaning changes. Additions, including new block kinds, do not change it: decoders map names they do not know to the Unknown value of the enum.

0.2 (2026-11-20): Hidden became Display, with only the reasons a file declares ("hidden", "no_ink"); hidden_checked and the text.hidden warning were removed. Later in 0.2, two rules narrowed what an extractor may write without changing the shape: a thematic break is always native (Validate rejects an inferred one), and the values of Attrs["stored"], Attrs["type"] on a note and Attrs["role"] are closed sets.

The schema version is not the module version: module v0.1.0 writes schema 0.2.

Variables

View Source
var (
	// ErrPasswordRequired: the input is encrypted and no password was given.
	ErrPasswordRequired = errors.New("gofastcore: password required")
	// ErrWrongPassword: the input is encrypted and the password given does
	// not open it.
	ErrWrongPassword = errors.New("gofastcore: wrong password")
	// ErrKeyRequired: the input is encrypted for a certificate and no key
	// in Options.Keys matches a recipient it names.
	ErrKeyRequired = errors.New("gofastcore: private key required")
	// ErrUnsupported: the input is valid but uses a feature or variant the
	// extractor does not implement.
	ErrUnsupported = errors.New("gofastcore: unsupported input")
	// ErrMalformed: the input is not a readable file of the expected format.
	ErrMalformed = errors.New("gofastcore: malformed input")
	// ErrLimitExceeded: a limit stopped the extraction before there was
	// anything to return. That is always the case when the input exceeds
	// Limits.MaxInputBytes, and it is the case for any other limit that is
	// reached before the input could even be identified, such as a
	// decompression bomb in the part that says what the file is. A limit
	// reached once there is a document truncates it and adds
	// WarnLimitExceeded instead of failing.
	ErrLimitExceeded = errors.New("gofastcore: limit exceeded")
	// ErrNoPartsSelected: Options.Parts selects no part of the input,
	// because it lies beyond the last part or First is greater than Last.
	ErrNoPartsSelected = errors.New("gofastcore: part range selects no parts")
)

Errors common to all extractors. Extractors wrap them, so test with errors.Is.

Functions

func AppendLigatures

func AppendLigatures(dst, src []byte) []byte

AppendLigatures appends src to dst with every presentation-form ligature written as its letters, and returns the extended slice. It is ExpandLigatures for an extractor that assembles text in a buffer.

func ExpandLigatures

func ExpandLigatures(s string) string

ExpandLigatures returns s with every presentation-form ligature (U+FB00 to U+FB06) written as its letters. A string that has none is returned as it is, without allocating.

func Ligature

func Ligature(r rune) string

Ligature returns the letters a presentation-form ligature (U+FB00 to U+FB06) stands for, and "" for any other character.

Every go-fast library writes these seven characters as their letters in all text it extracts, because the output is searched and compared: a reader looking for "office" must find a document that spells it with U+FB01. Nothing wider is done; this is not compatibility normalization. An extractor that builds text a character at a time calls Ligature, and one that has whole strings calls ExpandLigatures or AppendLigatures, so that no library keeps its own table.

func ResolveLimit

func ResolveLimit(v, def int64) int64

ResolveLimit applies the Limits convention to one value: it returns def when v is zero, the largest int64 when v is negative, and v otherwise.

func StoredKindNames

func StoredKindNames() []string

StoredKindNames returns every value of Attrs[AttrStored], for a command that takes kinds by name (RenderOptions.StoredKinds). The slice is the caller's.

Types

type Block

type Block struct {
	// Kind is what the block is; it decides which other fields mean
	// something (the table above).
	Kind Kind `json:"kind"`
	// Level is a heading's level, or the nesting depth of a list item or
	// quote; other kinds do not use it.
	Level uint8 `json:"level,omitempty"`
	// Text is the block's text, following the package's text conventions.
	// It is empty only for a table or a thematic break, and for an image
	// with no alternative text.
	Text string `json:"text,omitempty"`

	// Origin says whether the block's kind, level and boundaries are
	// declared by the source or were inferred by the extractor. It does
	// not cover the block's position in the reading order: a PDF image is
	// native (the file declares it and its box) even though where it falls
	// among the text is inferred. The zero value is OriginNative, so an
	// extractor that infers structure must set OriginInferred explicitly
	// on every such block.
	Origin Origin `json:"origin,omitempty"`

	// Display lists every reason the file declares why content in this
	// block is not shown or not inked; zero means it declares none, which
	// says nothing about whether a reader can see the text. A reason that
	// also appears on a span, or on a DisplayCells region of a table,
	// applies only there; any other reason applies to the whole block. See
	// DisplayWhole and DisplayedText. Such content is never dropped.
	Display Display `json:"display,omitempty"`

	// Continued marks a block that continues the nearest block of the
	// same kind before it: the last one of the preceding part, as with
	// the second half of a paragraph split by a page break, or the one
	// before it in the same part, as with a table too long for one block
	// and split by rows. A continued table has the columns of the table
	// it continues; its HeaderRows count only header rows it repeats.
	// Optional: an extractor that cannot tell leaves it false.
	Continued bool `json:"continued,omitempty"`

	// Ordered applies to list items.
	//
	// Marker is the label a reader sees in front of the block, as it
	// appeared, when the source provides or defines one: the label of a
	// list item ("3.", "(a)", "4.2.1"), the number of a numbered heading
	// ("2.3"), the mark of a footnote ("1", "*"). It is content: a
	// contract refers to "clause 4.2". It is kept out of Text, and the
	// renderers put it back in front.
	Ordered bool   `json:"ordered,omitempty"`
	Marker  string `json:"marker,omitempty"`

	// Spans carries inline formatting and links over Text, and marks the
	// ranges the file declares not shown or not inked. Formatting and links
	// are optional and only produced when Options.Spans is set; spans with
	// Display set are always produced.
	Spans []Span `json:"spans,omitempty"`

	// Table is set exactly on a table block, Image exactly on an image
	// block.
	Table *Table `json:"table,omitempty"`
	Image *Image `json:"image,omitempty"`

	// Loc says where in the source the block came from.
	Loc Location `json:"loc,omitzero"`

	// Attrs is the escape hatch for format-specific facts. Keys are
	// lowercase. Prefer a real field once two formats need the same key.
	// The keys every format spells the same way are the Attr* constants.
	Attrs map[string]string `json:"attrs,omitempty"`
}

Block is one unit of content in reading order.

Which fields are meaningful depends on Kind:

Kind             Text                 Level           Other
KindHeading      heading text         1-6             Marker
KindParagraph    paragraph text       -               -
KindListItem     item text, no marker nesting, from 1 Ordered, Marker
KindTable        empty                -               Table
KindImage        alt text / caption   -               Image
KindCode         code, verbatim       -               Attrs["language"]
KindQuote        quoted text          nesting, from 1 -
KindCaption      caption text         -               -
KindFootnote     note text            -               Marker
KindFormula      the formula          -               Attrs["notation"]
KindNote         the note's text      -               Attrs: type, author, date, field
KindHeader       running header       -               -
KindFooter       running footer       -               -
KindThematicBreak empty               -               -

A heading's Level is 1 to 6. A source with deeper levels (Word has nine) has them clamped to 6, with the real level, in decimal, in Attrs[AttrLevel]; the part then carries WarnHeadingLevelClamped.

KindHeader and KindFooter are page furniture (repeated titles, page numbers). They are kept so nothing is silently lost, and tagged so consumers can drop them.

KindThematicBreak marks a break between topics or scenes that the source declares (an HTML <hr>, a Markdown thematic break, Word's horizontal line, LibreOffice's Horizontal Line paragraph style). It is a boundary a chunker can split on. It has no text and is never Continued.

func (*Block) DisplayWhole

func (b *Block) DisplayWhole() Display

DisplayWhole returns the reasons that apply to the whole block.

Block.Display lists every reason declared anywhere in the block. A reason that also appears on a span (or, for a table, on a DisplayCells region) applies only to those ranges; a reason that appears on none applies to the whole block.

func (*Block) DisplayedText

func (b *Block) DisplayedText(exclude Display) string

DisplayedText returns the block's text without the content declared with one of the reasons in exclude: the empty string if such a reason applies to the whole block, otherwise Text with those ranges cut out.

type CellDetail

type CellDetail struct {
	Row int `json:"row"`
	Col int `json:"col"`
	// Href is where the cell links to: an address, or "#place" inside the
	// document.
	Href string `json:"href,omitempty"`
	// Formula is the formula whose result the cell displays, as the
	// source writes it, without a leading "=". It is never evaluated.
	Formula string `json:"formula,omitempty"`
	// Type is the kind of value the cell stores. Value is that value
	// where the displayed text does not show it in full: a number its
	// format rounds, a date's serial number. Value is set only with Type.
	Type  CellType `json:"type,omitempty"`
	Value string   `json:"value,omitempty"`
}

CellDetail is what one cell of a table holds besides its displayed text.

type CellType

type CellType uint8

CellType is the kind of value a table cell stores (CellDetail.Type).

const (
	// CellUnset: the type is not given.
	CellUnset CellType = iota
	// CellUnknown is a cell type this version of the package does not
	// know.
	CellUnknown
	CellNumber
	CellDate
	CellBool
	CellError
	CellText
)

func (CellType) MarshalText

func (t CellType) MarshalText() ([]byte, error)

func (CellType) String

func (t CellType) String() string

func (*CellType) UnmarshalText

func (t *CellType) UnmarshalText(b []byte) error

func (CellType) Valid

func (t CellType) Valid() bool

Valid reports whether t is a cell type an extractor may emit.

type ChildFunc

type ChildFunc func(ctx context.Context, name, mime string, r io.ReaderAt, size int64, opts *Options) (*Document, error)

ChildFunc extracts one embedded document. name is the attachment or member name and mime its declared media type; either may be empty. The function is expected to work out the format and route to the right extractor, passing opts through.

type DecodeBudget

type DecodeBudget struct {
	// contains filtered or unexported fields
}

DecodeBudget counts the bytes a document and the documents embedded in it may still decompress, against Limits.MaxDecodedBytes.

The limit on decompressed bytes is what stops a decompression bomb. An extractor counts against it as it reads, and each document has its own count. But a document can embed thousands of documents, each of them a bomb that stays just inside the limit: without more, the limit would hold for each and the whole would cost thousands of times as much. DecodeBudget makes the limit the document's and its embedded documents' together, as TextBudget does for text, and in the same way.

An extractor gets the budget of the document it is reading from WithDecodeBudget, and before it hands an embedded document to Options.ExtractChild sees to it that the budget says what the document has left (Take). It passes the context WithDecodeBudget returned. The child's extractor, of whatever library, gets from WithDecodeBudget a budget no larger than what its parent has left, reads within it, and on Close takes what it used from its parent; the parent then goes on with what is left. Embedded documents are extracted one after another.

How an extractor counts while it reads is its own affair: it may take from the budget as it goes, or keep a count of its own and settle with the budget (Settle) before each embedded document and at the end.

A nil *DecodeBudget has no limit. A DecodeBudget is safe for concurrent use.

func DecodeBudgetFrom

func DecodeBudgetFrom(ctx context.Context) *DecodeBudget

DecodeBudgetFrom returns the budget ctx carries, or nil.

func WithDecodeBudget

func WithDecodeBudget(ctx context.Context, limits Limits, def int64) (context.Context, *DecodeBudget)

WithDecodeBudget returns the budget for one reading of a document, and ctx carrying it. The budget is limits.MaxDecodedBytes (def if zero, none if negative; the default is the extractor's own), or what the document this one is embedded in has left, if ctx carries that and it is less.

func (*DecodeBudget) Close

func (d *DecodeBudget) Close()

Close ends the reading: what the document took is taken from the budget of the document it is embedded in, if there is one. Later calls do nothing.

func (*DecodeBudget) Left

func (d *DecodeBudget) Left() int64

Left returns the bytes not yet taken; a negative number once more was asked for than there was.

func (*DecodeBudget) Settle

func (d *DecodeBudget) Settle(left int64) bool

Settle takes from the budget what is needed for Left to be at most left, and reports whether Left is then not negative. It is for an extractor that keeps a count of its own while it reads (left is what that count says the document has left) and settles with the budget before it hands an embedded document to Options.ExtractChild, and at the end. It never gives back: if the budget already has less than left, it is unchanged.

func (*DecodeBudget) Take

func (d *DecodeBudget) Take(n int64) bool

Take takes n decompressed bytes from the budget and reports whether they were there to take.

type Display

type Display uint16

Display is a set of reasons, each declared by the file, why content is not shown or not inked. The zero value means the file declares neither. In JSON it is a "+"-joined list of names, e.g. "hidden+no_ink".

A reason is declared when the file states it in one switch or one value of the content or of something containing it, including through the file's own inheritance (a style, an ancestor element). Anything that needs two values compared, or a threshold, is not a declaration and is not reported: colour against background, a size against a minimum, a box against the page or another box, the coverage of an image, an evaluated condition.

const (
	// DisplayHidden: the file switches the content off. Hidden formatting
	// or the hidden attribute; a hidden sheet, row, column, slide, shape,
	// layer or annotation; display:none.
	DisplayHidden Display = 1 << iota
	// DisplayNoInk: the file declares the text drawn with no paint: no
	// fill, full transparency, PDF text render mode 3 or 7. The searchable
	// text layer of a scanned PDF page is drawn this way, so excluding
	// DisplayNoInk leaves out the text of scanned pages.
	DisplayNoInk

	// DisplayUnknown stands for reasons this version of the package does
	// not know. Unlike an unknown style, an unknown reason is kept on
	// decode, so that an older consumer never loses a declaration.
	DisplayUnknown Display = 1 << 15

	// DisplayAny is every reason. It is meant for
	// RenderOptions.ExcludeDisplay.
	DisplayAny Display = 0xFFFF
)

func (Display) MarshalText

func (d Display) MarshalText() ([]byte, error)

func (Display) String

func (d Display) String() string

func (*Display) UnmarshalText

func (d *Display) UnmarshalText(b []byte) error

func (Display) Valid

func (d Display) Valid() bool

Valid reports whether d holds only reasons an extractor may emit.

type DisplayCells

type DisplayCells struct {
	Row     int     `json:"row"`
	Col     int     `json:"col"`
	RowSpan int     `json:"row_span"`
	ColSpan int     `json:"col_span"`
	Display Display `json:"display"`
}

DisplayCells marks a rectangular region of a Table whose cells the file declares not shown or not inked. Row and Col are 0-based; RowSpan and ColSpan are at least 1. A hidden column is one region the height of the table.

type Document

type Document struct {
	// SchemaVersion is the SchemaVersion of the package that wrote it.
	SchemaVersion string `json:"schema_version"`
	// Source says what the document was extracted from.
	Source Source `json:"source"`
	// Metadata holds the properties the source declares for the whole
	// document.
	Metadata Metadata `json:"metadata,omitzero"`
	// Outline is the source's own table of contents, in its order.
	Outline []OutlineItem `json:"outline,omitempty"`
	// Parts are the format's natural units in source order: pages,
	// slides, sheets, chapters, messages or one body, then the stored
	// part if there is one. Never nil.
	Parts []Part `json:"parts"`
	// Children are the embedded documents, in the order the extractor met
	// them; see Options.ExtractChild.
	Children []*Document `json:"children,omitempty"`
	// Warnings holds problems that concern the document as a whole.
	// Problems local to a part are in Part.Warnings.
	Warnings []Warning `json:"warnings,omitempty"`
}

Document is the output of every go-fast-* extractor.

func New

func New(format string) *Document

New returns an empty Document for the given format with the schema version set. Its Parts list is empty but not nil, so that it is written to JSON as [] and never as null.

func (*Document) AllBlocks

func (d *Document) AllBlocks() iter.Seq2[*Part, *Block]

AllBlocks iterates over every block of the document in reading order, together with the part that holds it. Children are not visited.

func (*Document) AllWarnings

func (d *Document) AllWarnings() iter.Seq2[*Part, Warning]

AllWarnings iterates over the document-level warnings, for which the part is nil, and then over each part's warnings. Children are not visited.

func (*Document) Markdown

func (d *Document) Markdown() string

Markdown renders the document (not its children) as Markdown with default options.

func (*Document) Text

func (d *Document) Text() string

Text renders the document (not its children) as plain text with default options, for consumers such as embedding pipelines that do not want Markdown syntax. Blocks are separated by blank lines, tables are tab-separated, and images contribute their alt text.

func (*Document) Validate

func (d *Document) Validate() error

Validate checks that the document obeys the model's structural contract and the mechanical text conventions (valid UTF-8, no control characters, no unexpanded ligatures in text, trimmed non-empty block text) and returns every violation found, joined with errors.Join. It also checks that Part.Finish was called on every part, that the lists consumers iterate are not nil, and that every Attrs["stored"], note Attrs["type"] and Attrs["role"] is one of the package's values.

It is a check on producers. It walks the whole document, so call it from tests rather than on the hot path, and it rejects the Unknown enum values that only arise when decoding output from a newer extractor.

func (*Document) Walk

func (d *Document) Walk(fn func(doc *Document, depth int) bool)

Walk calls fn for d and then for every descendant in Children, depth first. It stops early if fn returns false.

func (*Document) Warn

func (d *Document) Warn(severity Severity, code, message string)

Warn appends a document-level warning. It keeps at most MaxWarnings of them, as Part.Warn does. It is not safe for concurrent use; workers should warn on their own Part instead.

func (*Document) WriteMarkdown

func (d *Document) WriteMarkdown(w io.Writer, opts *RenderOptions) error

WriteMarkdown renders the document's parts to w as Markdown.

Text that would be read as Markdown structure at the start of a line ("# ", "> ", "- ", "1. ") is escaped, so a paragraph stays a paragraph. Inline characters are not escaped. Of Spans, links are rendered, as [text](<address>), and so are the links of table cells; formatting is not.

func (*Document) WriteText

func (d *Document) WriteText(w io.Writer, opts *RenderOptions) error

WriteText renders the document's parts to w as plain text.

type Extractor

type Extractor interface {
	// Formats lists the format names this extractor handles, as they
	// appear in Source.Format: "pdf", or "docx", "pptx", "xlsx".
	Formats() []string

	// Extract reads size bytes from r and returns the document. io.ReaderAt
	// is used because the container formats (PDF, zip, OLE) need random
	// access; an *os.File, a bytes.Reader and a memory map all satisfy it.
	//
	// opts may be nil. A partially readable input yields a Document with
	// warnings. An error means nothing usable was extracted, and wraps one
	// of the Err* values where one applies. Extract must return promptly
	// with ctx.Err() once ctx is cancelled.
	Extract(ctx context.Context, r io.ReaderAt, size int64, opts *Options) (*Document, error)
}

Extractor turns one or more input formats into the shared document model. Every go-fast-* library provides one, so that a dispatcher can treat all formats alike.

Implementations must be safe for concurrent use: a pipeline calls Extract from many goroutines, one document each.

type Image

type Image struct {
	// ID identifies the image resource within the document. Equal IDs
	// mean equal bytes, and several blocks may share one ID (a logo on
	// every page). It is not a per-block identifier.
	ID   string `json:"id,omitempty"`
	MIME string `json:"mime,omitempty"`
	// Width and Height are in pixels, 0 if unknown.
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
	// Data holds the encoded image bytes when the extractor was asked for
	// them. Serialized as base64. When several blocks share an ID, Data is
	// guaranteed only on the first of them in document order; later ones
	// may leave it nil.
	Data []byte `json:"data,omitempty"`
}

Image describes an image referenced by a KindImage block.

type ImageMode

type ImageMode uint8

ImageMode selects how much image information an extractor produces.

const (
	// ImagesMeta, the default, emits a block for every image, with what
	// the source says of it: its place, its dimensions, its alternative
	// text, and an ID by which the same image is known wherever it
	// occurs. An image is content: where it stands gives context, and
	// its alternative text is text its author wrote.
	ImagesMeta ImageMode = iota
	// ImagesData additionally fills Image.Data with the encoded bytes,
	// for a caller that looks at the pictures.
	ImagesData
	// ImagesNone emits no image blocks: the alternative text of images
	// is then not in the document. WarnPartImageOnly is still reported.
	// For callers that want text only and know what they leave out.
	ImagesNone
)

type Kind

type Kind uint8

Kind is the type of a Block.

const (
	// KindInvalid is the zero value: a block whose kind was never set.
	KindInvalid Kind = iota
	// KindUnknown is a kind this version of the package does not know.
	// Consumers should treat it as a paragraph.
	KindUnknown
	// The kinds of content. What each uses of Block's fields is in the
	// table in Block's documentation.
	KindParagraph
	KindHeading
	KindListItem
	KindTable
	KindImage
	KindCode
	KindQuote
	KindCaption
	KindFootnote
	KindFormula
	KindNote
	KindHeader
	KindFooter
	// KindThematicBreak is a break between topics or scenes that the
	// source marks as such: an HTML <hr>, a Markdown thematic break,
	// Word's horizontal line, an empty paragraph in LibreOffice's
	// Horizontal Line paragraph style. It has no text and is always OriginNative:
	// a bordered or ruled paragraph, a drawn line or a row of asterisks is
	// formatting, not a declared break, and no break is inferred from it.
	// Page, column and section breaks are layout and are not emitted as
	// blocks.
	KindThematicBreak
)

func (Kind) Furniture

func (k Kind) Furniture() bool

Furniture reports whether k is page furniture rather than content.

func (Kind) MarshalText

func (k Kind) MarshalText() ([]byte, error)

func (Kind) String

func (k Kind) String() string

func (*Kind) UnmarshalText

func (k *Kind) UnmarshalText(b []byte) error

func (Kind) Valid

func (k Kind) Valid() bool

Valid reports whether k is a kind an extractor may emit.

type Limits

type Limits struct {
	// MaxInputBytes bounds the input size. Exceeding it is
	// ErrLimitExceeded before any work is done.
	MaxInputBytes int64
	// MaxDecodedBytes bounds the total bytes produced by decompression
	// (zip members, PDF streams), the defense against decompression bombs.
	MaxDecodedBytes int64
	// MaxTextBytes bounds the text a document holds: the text of its
	// blocks and the cells of its tables, each counted as often as it
	// occurs, in the document and the documents embedded in it together,
	// and BlockCost for every block and CellCost for every cell besides.
	// It is the defense against a small file that says a long text many
	// times over (one string that every cell of a sheet refers to, a
	// form drawn on every page), which the decompression limit does not
	// see: what is repeated is stored once. Text outside blocks counts
	// too where the file decides both its length and how often it
	// occurs (outline titles, a name made for every part, list markers,
	// link targets), unless the extractor holds it to the length of a
	// name. When the limit is reached, the part being read is cut off
	// there with WarnLimitExceeded. The default is DefaultMaxTextBytes.
	// See TextBudget.
	MaxTextBytes int64
	// MaxParts bounds the number of parts extracted. When the input has
	// more, the first MaxParts parts of the requested range are returned
	// with WarnLimitExceeded, also where the count is known up front.
	MaxParts int
	// MaxDepth bounds how deeply embedded documents are followed. The
	// default is DefaultMaxDepth.
	MaxDepth int
}

Limits bounds the work an extractor will do for one input. For every field, zero means the extractor's default and a negative value means no limit.

type Location

type Location struct {
	// BBox is the block's bounding box in the coordinate space of its
	// part as displayed: origin top-left, y increasing downward, units as
	// in Part.Width/Height. A box drawn at these coordinates on a rendered
	// image of the part encloses the block.
	BBox Rect `json:"bbox,omitzero"`
	// Range is a cell range in A1 notation for blocks from a sheet,
	// e.g. "B2:F40".
	Range string `json:"range,omitempty"`
	// Offset and Length give the block's byte span in the source for
	// plain-text formats (txt, md, html).
	Offset int64 `json:"offset,omitempty"`
	Length int64 `json:"length,omitempty"`
	// Anchor is an identifier the source itself gives the block, stable
	// for as long as the source is: a Word paragraph id, an HTML id
	// attribute, the fragment of an e-book link. It is what a citation
	// points at in a format that has no pages and no byte offsets.
	Anchor string `json:"anchor,omitempty"`
}

Location pins a block to its place in the source so that a retrieval hit can be cited and shown in context. Every field is optional; the part a block belongs to is given by its position in Document.Parts.

type Merge

type Merge struct {
	Row     int `json:"row"`
	Col     int `json:"col"`
	RowSpan int `json:"row_span"`
	ColSpan int `json:"col_span"`
}

Merge is a merged cell region. Row and Col are 0-based; RowSpan and ColSpan are at least 1 and at least one of them is greater than 1.

type Metadata

type Metadata struct {
	Title string `json:"title,omitempty"`
	// Authors has one entry per author the source declares. A source with
	// a single free-text author field (PDF) yields one entry, verbatim;
	// extractors must not split a string on guesswork.
	Authors []string `json:"authors,omitempty"`
	Subject string   `json:"subject,omitempty"`
	// Keywords follows the same rule as Authors: a single free-text
	// keywords field yields one entry, verbatim.
	Keywords []string `json:"keywords,omitempty"`
	Language string   `json:"language,omitempty"` // BCP 47, e.g. "en", "pt-BR"
	// Created and Modified are the dates the source declares for the
	// document; zero where it declares none.
	Created  time.Time `json:"created,omitzero"`
	Modified time.Time `json:"modified,omitzero"`
	// Application is the software that produced the file.
	Application string `json:"application,omitempty"`
	// Encrypted reports that the input was encrypted (and was decrypted).
	Encrypted bool `json:"encrypted,omitempty"`
	// Extra carries format-specific properties that have no field above,
	// e.g. email "from"/"to"/"message-id", PDF "producer". Keys are
	// lowercase.
	Extra map[string]string `json:"extra,omitempty"`
}

Metadata holds document-level properties. Every field is optional.

type Options

type Options struct {
	// Workers bounds the goroutines used inside a single document
	// (e.g. PDF pages). 0 means runtime.GOMAXPROCS(0). Pipelines that
	// already parallelize across documents should set 1.
	Workers int

	// Images selects how much image information to extract. The zero
	// value is ImagesMeta: every image is a block.
	Images ImageMode

	// Spans asks for inline formatting and links in Block.Spans. Spans
	// that carry a Display reason are produced whether or not this is set.
	Spans bool

	// Password is tried on encrypted input. It is also passed down to
	// embedded documents, which is what opens an encrypted attachment of
	// an unencrypted email.
	Password string

	// Keys are private keys tried on input encrypted for a certificate
	// (an Office file encrypted for a certificate, a PDF with the
	// public-key security handler): the key whose public half matches a
	// recipient the file names is used. A crypto.Decrypter may keep its
	// key in hardware or in another process. Passed down to embedded
	// documents, as Password is.
	Keys []crypto.Decrypter

	// Cells asks for the formulas of table cells, and the type and the
	// stored value of a cell where its displayed text does not show the
	// value in full, in Table.Cells. On a sheet of numbers that is an
	// entry for every cell, so it is not given unless asked for.
	Cells bool

	// Parts restricts extraction to a range of part numbers. The zero
	// value extracts every part. A range that selects nothing is
	// ErrNoPartsSelected.
	Parts PartRange

	// Limits guards against hostile or oversized input.
	Limits Limits

	// Child extracts embedded documents (email attachments, archive
	// members, files embedded in a PDF). It is how a dispatcher that
	// knows every format is injected into an extractor that knows one,
	// without the extractors importing each other. When nil, embedded
	// documents are listed in Children but not extracted.
	//
	// Extractors do not call Child directly; they call ExtractChild.
	Child ChildFunc

	// Name is recorded as Source.Name.
	Name string

	// Depth is the nesting depth of the document being extracted: 0 for
	// a top-level document. ExtractChild maintains it; callers leave it
	// zero.
	Depth int
}

Options are the settings common to all extractors. The zero value asks for text, structure and a block for every image, for the whole input, using all CPUs.

Settings that only one format understands (for PDF: memory mapping, a cache budget) do not belong here. They are fields on that library's extractor value, e.g. (&gofastpdf.Extractor{...}).Extract(...).

func (*Options) ExtractChild

func (o *Options) ExtractChild(ctx context.Context, name, mime string, r io.ReaderAt, size int64) *Document

ExtractChild extracts one embedded document on behalf of an extractor and always returns a Document to append to Children, so that every embedded file is at least listed with its name and size.

The returned document has no parts and a single warning when the child was not extracted. The warning code says why:

WarnChildNotExtracted  no ChildFunc was supplied, the depth limit was reached, or r is nil
                       (the extractor has nothing to hand over, as when a limit stopped it)
WarnChildUnsupported   the ChildFunc returned ErrUnsupported
WarnChildEncrypted     the ChildFunc returned ErrPasswordRequired, ErrWrongPassword or ErrKeyRequired
WarnChildFailed        the ChildFunc returned any other error

ExtractChild may be called on a nil *Options.

type Origin

type Origin uint8

Origin says how a block's structure (its kind, level and boundaries) was determined. It says nothing about where the text came from.

const (
	// OriginNative: the source declares the structure. A docx style, an
	// HTML tag, a tagged-PDF structure element, a PDF outline entry.
	OriginNative Origin = 0
	// OriginInferred: the extractor deduced the structure from geometry,
	// fonts or other heuristics. A consumer that needs certainty should
	// treat such blocks as plain text and chunk by size.
	OriginInferred Origin = 1
	// OriginUnknown is an origin this version of the package does not know.
	OriginUnknown Origin = 255
)

func (Origin) MarshalText

func (o Origin) MarshalText() ([]byte, error)

func (Origin) String

func (o Origin) String() string

func (*Origin) UnmarshalText

func (o *Origin) UnmarshalText(b []byte) error

func (Origin) Valid

func (o Origin) Valid() bool

Valid reports whether o is an origin an extractor may emit.

type OutlineItem

type OutlineItem struct {
	Title string `json:"title"`
	// Level is the nesting depth, from 1.
	Level int `json:"level"`
	// Part is the Number of the part the entry points to, 0 if the target
	// is unknown. The part may be absent from Parts when only a range was
	// extracted.
	Part int `json:"part,omitempty"`
	// Y is the vertical position of the target within the part, in the
	// part's coordinate space, 0 if unknown.
	Y float64 `json:"y,omitempty"`
}

OutlineItem is one entry of the source's own table of contents: a PDF bookmark, an epub nav point. It is structure the source declares, so it is reliable even where block structure is inferred.

type Part

type Part struct {
	// Kind is the kind of unit: page, slide, sheet, chapter, message,
	// body or stored.
	Kind PartKind `json:"kind"`
	// Number is the 1-based ordinal of this part in the source.
	Number int `json:"number"`
	// Name is what people call the part: the sheet name, slide title,
	// chapter title, or a PDF page label ("iv", "A-3") where it differs
	// from Number. Optional.
	Name string `json:"name,omitempty"`
	// Width and Height give the part's coordinate space for Block.Loc.BBox,
	// as the part is displayed. For PDF: the CropBox after /Rotate and
	// UserUnit are applied, in points. Zero when the part has no geometry.
	Width  float64 `json:"width,omitempty"`
	Height float64 `json:"height,omitempty"`
	// Display gives the reasons the file declares for the whole part: a
	// hidden sheet or slide. Every block of the part carries the same
	// reasons (Finish copies them).
	Display Display `json:"display,omitempty"`
	// Blocks are the part's content in reading order. Never nil once
	// Finish has been called.
	Blocks []Block `json:"blocks"`
	// Warnings are the problems local to this part.
	Warnings []Warning `json:"warnings,omitempty"`
}

Part is a format's natural top-level unit of content.

A part is self-contained: a worker can fill one without touching any shared state, and a part handed on by itself carries its own warnings.

func (*Part) Finish

func (p *Part) Finish()

Finish completes a part. An extractor calls it once per part, after the part's blocks are final. It:

  • copies Part.Display onto every block, so that "b.Display != 0" is the only test a consumer needs;
  • makes Blocks an empty list instead of nil when the part has no blocks (a failed or blank page), so that JSON has [] and not null.

It touches only the part, so page workers can call it concurrently. It is idempotent.

func (*Part) Has

func (p *Part) Has(code string) bool

Has reports whether the part carries a warning with the given code.

func (*Part) Markdown

func (p *Part) Markdown() string

Markdown renders a single part as Markdown with default options. Those leave out stored data and running headers and footers, so a stored part renders as "". To render one with other options, render a Document holding it.

func (*Part) Text

func (p *Part) Text() string

Text renders a single part as plain text with default options, as Markdown does.

func (*Part) Warn

func (p *Part) Warn(severity Severity, code, message string)

Warn appends a warning to the part. It keeps at most MaxWarnings of them; past that it counts the rest in one last warnings.omitted warning (see MaxWarnings), so a call may add no entry.

type PartKind

type PartKind uint8

PartKind is the type of a Part.

const (
	PartInvalid PartKind = iota
	// PartUnknown is a part kind this version of the package does not know.
	PartUnknown
	// PartBody is the single part of a format with no natural division:
	// docx, odt, html, txt, md, rtf.
	PartBody
	PartPage    // pdf
	PartSlide   // pptx, odp
	PartSheet   // xlsx (and xlsb), ods
	PartChapter // epub
	PartMessage // eml, msg; one per message in an mbox
	// PartStored holds what belongs to the file as a whole and to no
	// page, sheet or slide, and is shown on none: macro code, document
	// variables, custom XML data, defined names. A document has at most
	// one, after its other parts and numbered after them. It carries no
	// part-level Display reason: being stored says where text came from,
	// not what the file declares about its display. The renderers leave it
	// out unless RenderOptions.Stored is set. Options.Parts
	// selects it only with the whole document (the zero range); a reader
	// that gives parts one at a time gives it last, after the others.
	PartStored
)

func (PartKind) MarshalText

func (k PartKind) MarshalText() ([]byte, error)

func (PartKind) String

func (k PartKind) String() string

func (*PartKind) UnmarshalText

func (k *PartKind) UnmarshalText(b []byte) error

func (PartKind) Valid

func (k PartKind) Valid() bool

Valid reports whether k is a part kind an extractor may emit.

type PartRange

type PartRange struct {
	First int // the first part number selected; 0 means from the first
	Last  int // the last part number selected; 0 means through the last
}

PartRange selects parts by number, both ends inclusive. A zero First means from the first part; a zero Last means through the last.

func (PartRange) Contains

func (r PartRange) Contains(n int) bool

Contains reports whether part number n is inside the range.

type Rect

type Rect struct {
	X0 float64 `json:"x0"`
	Y0 float64 `json:"y0"`
	X1 float64 `json:"x1"`
	Y1 float64 `json:"y1"`
}

Rect is an axis-aligned rectangle with (X0,Y0) top-left and (X1,Y1) bottom-right.

type RenderFlags

type RenderFlags struct {
	// contains filtered or unexported fields
}

RenderFlags are the command-line flags every go-fast command offers for RenderOptions, with the same names, values and meaning in each:

-furniture                  Furniture
-stored[=kinds]             Stored, StoredKinds
-part-markers               PartMarkers
-exclude-display[=reasons]  ExcludeDisplay
-children (default true)    Children

A command defines them with AddRenderFlags and, after parsing, sets its RenderOptions with Apply.

func AddRenderFlags

func AddRenderFlags(fs *flag.FlagSet) *RenderFlags

AddRenderFlags defines the shared render flags on fs and returns them.

func (*RenderFlags) Apply

func (f *RenderFlags) Apply(o *RenderOptions)

Apply sets the fields of o that the render flags control, and leaves the others.

type RenderOptions

type RenderOptions struct {
	// Furniture includes running headers and footers, which are dropped
	// by default.
	Furniture bool
	// Stored includes stored data: the stored part (macro code, defined
	// names, document variables and other data the file shows nowhere),
	// and blocks of other parts whose Attrs[AttrStored] is set, such as
	// the scripts of a PDF page. Both are left out by default.
	Stored bool
	// StoredKinds includes only the stored data of the kinds named (values
	// of Attrs[AttrStored], such as StoredMarkupComment or
	// StoredFieldCode), wherever it is: in the stored part or in any other
	// part. A block of the stored part with no kind is included only by
	// Stored. Stored includes every kind, whatever StoredKinds says.
	StoredKinds []string
	// PartMarkers emits a line before each part so that positions survive
	// in the rendered text: "<!-- page 3 -->" in Markdown, "[page 3]" in
	// plain text.
	PartMarkers bool
	// ExcludeDisplay leaves out content the file declares with any of the
	// given reasons. The default is to include everything. Excluding
	// DisplayNoInk also leaves out the searchable text layer of scanned
	// PDF pages, which would then render empty.
	ExcludeDisplay Display
	// Children renders the documents in Document.Children after the
	// document's own parts, depth first, each after a line that names it:
	// "<!-- child 2: report.pdf -->" in Markdown, "[child 2: report.pdf]"
	// in plain text. A nested child is numbered by its path ("child 2.1").
	// A child that was listed but not extracted gives its line only. The
	// same options apply to every child. Children nested more than 64
	// deep are not rendered: no extractor nests them so deep, and the
	// bound stops a tree built by hand with a cycle in it.
	Children bool
}

RenderOptions controls Markdown and plain-text output. The zero value is the default.

type Severity

type Severity uint8

Severity says how a warning affects the output. Values are ordered, so "w.Severity >= SeverityError" is meaningful; an unknown severity sorts highest.

const (
	// SeverityInvalid is the zero value: a severity that was never set.
	SeverityInvalid Severity = 0
	// SeverityInfo: something notable happened; the output is complete.
	SeverityInfo Severity = 1
	// SeverityWarning: the output is present but incomplete or degraded,
	// or it is one of more than one way the input can be read.
	SeverityWarning Severity = 2
	// SeverityError: content is missing or untrustworthy.
	SeverityError Severity = 3
	// SeverityUnknown is a severity this version of the package does not
	// know.
	SeverityUnknown Severity = 255
)

func (Severity) MarshalText

func (s Severity) MarshalText() ([]byte, error)

func (Severity) String

func (s Severity) String() string

func (*Severity) UnmarshalText

func (s *Severity) UnmarshalText(b []byte) error

func (Severity) Valid

func (s Severity) Valid() bool

Valid reports whether s is a severity an extractor may emit.

type Source

type Source struct {
	// Format is the short lowercase format name: "pdf", "docx", "eml", ...
	// It is empty only for a child that was listed but not extracted.
	Format string `json:"format,omitempty"`
	// Name is the file name, URL, or, for a child document, the attachment
	// or archive member name. Optional.
	Name string `json:"name,omitempty"`
	// MIME is the media type if known.
	MIME string `json:"mime,omitempty"`
	// Size is the input size in bytes, 0 if unknown.
	Size int64 `json:"size,omitempty"`
}

Source describes the input the document was extracted from.

type Span

type Span struct {
	Start int    `json:"start"`
	End   int    `json:"end"`
	Style Style  `json:"style,omitempty"`
	Href  string `json:"href,omitempty"`
	// Display gives the reasons declared for this range when they apply to
	// only part of the block. Every reason here is also in Block.Display.
	Display Display `json:"display,omitempty"`
}

Span marks the range [Start, End) of Block.Text with inline styling, a link target, or the reasons the file declares that range not shown or not inked. Spans may overlap.

Start and End are byte offsets into the UTF-8 text, not character offsets, and always fall on character boundaries. A consumer in a language that indexes strings by code point must convert; in Python:

text.encode("utf-8")[start:end].decode("utf-8")

type Style

type Style uint8

Style is a set of inline text styles. In JSON it is a "+"-joined list of names, e.g. "bold+italic". Names this version does not know are ignored on decode.

const (
	StyleBold Style = 1 << iota
	StyleItalic
	StyleUnderline
	StyleStrike
	StyleCode
	StyleSub
	StyleSuper
)

func (Style) MarshalText

func (s Style) MarshalText() ([]byte, error)

func (Style) String

func (s Style) String() string

func (*Style) UnmarshalText

func (s *Style) UnmarshalText(b []byte) error

type Table

type Table struct {
	// HeaderRows is the number of leading rows that are column headers.
	HeaderRows int        `json:"header_rows,omitempty"`
	Rows       [][]string `json:"rows"`
	Merges     []Merge    `json:"merges,omitempty"`
	// Display marks the cells the file declares not shown or not inked
	// when that is only part of the table: a hidden row or column. Every
	// reason here is also in Block.Display.
	Display []DisplayCells `json:"display,omitempty"`
	// Cells holds what some cells have besides the text they display, in
	// order of row, then column; a cell with nothing more has no entry.
	// Links come with Options.Spans; formulas, types and stored values
	// with Options.Cells. Everything here counts against
	// Limits.MaxTextBytes. The renderers write links, never formulas or
	// values: a formula can hold text that nobody sees on the sheet.
	Cells []CellDetail `json:"cells,omitempty"`
	// RowLocs says where each row came from, for a source that can say it: a
	// byte span, an anchor the source gives the row, a box on the page. It is
	// empty, or has one entry per row in the order of Rows; a row with
	// nothing to say has a zero Location. Block.Loc still covers the whole table.
	RowLocs []Location `json:"row_locs,omitempty"`
}

Table is a rectangular grid of cell text. Every row has the same number of columns; a merged region stores its text in its top-left cell, leaves the other covered cells empty, and is listed in Merges.

Extractors should split very large sheets into several table blocks (each with its own Loc.Range) rather than emit one giant table.

type TextBudget

type TextBudget struct {
	// contains filtered or unexported fields
}

TextBudget counts the text a document may still produce, against Limits.MaxTextBytes.

A file can be small and say a great deal: one long string that every cell of a sheet refers to, a form drawn on every page. What is repeated is stored once, so the limit on decompressed bytes does not see it, and the document that results holds, or writes out, the text as often as it occurs. The budget is what bounds that.

An extractor gets the budget of the document it is reading from WithTextBudget, takes from it BlockCost and the bytes of the text of every block, CellCost and the bytes of every table cell it produces, and when Take reports false stops reading the part, keeps what it has and raises WarnLimitExceeded there. It calls Close when the document is done.

Text outside blocks is taken from the budget as well, wherever the file decides both how long it is and how often it occurs: outline titles, a name made for every part, list markers, link targets. A string the extractor holds to the length of a name need not be. The outline is counted before the first part and a part's name with the part, so that the place of the cut does not depend on timing.

The budget is the document's and its embedded documents' together. The context WithTextBudget returns carries the budget; an extractor passes that context to Options.ExtractChild, and the child's extractor, of whatever library, gets from WithTextBudget a budget of its own that is no larger than what its parent has left, and on Close takes what it used from its parent. Embedded documents are extracted one after another, so what each may use does not depend on timing.

A nil *TextBudget has no limit. A TextBudget is safe for concurrent use.

func TextBudgetFrom

func TextBudgetFrom(ctx context.Context) *TextBudget

TextBudgetFrom returns the budget ctx carries, or nil.

func WithTextBudget

func WithTextBudget(ctx context.Context, limits Limits) (context.Context, *TextBudget)

WithTextBudget returns the budget for one reading of a document, and ctx carrying it. The budget is limits.MaxTextBytes (DefaultMaxTextBytes if zero, none if negative), or what the document this one is embedded in has left, if ctx carries that and it is less.

func (*TextBudget) Close

func (b *TextBudget) Close()

Close ends the reading: what the document took is taken from the budget of the document it is embedded in, if there is one. Later calls do nothing.

func (*TextBudget) Exhaust

func (b *TextBudget) Exhaust()

Exhaust spends what is left, so that Spent reports true and every later Take reports false: for an extractor that has stopped at the limit by a count of its own (an outline already cut at the limit) and so has nothing left for what follows. It gives nothing back if more was taken than there was.

func (*TextBudget) Left

func (b *TextBudget) Left() int64

Left returns the bytes not yet taken; a negative number once more was asked for than there was.

func (*TextBudget) Reset

func (b *TextBudget) Reset()

Reset gives back everything taken, for an extractor that reads the document again from the start (as one that reads parts side by side may, to cut the document at the same place whatever the number of workers).

func (*TextBudget) Return

func (b *TextBudget) Return(n int64)

Return gives back n bytes that were taken, for an extractor that reads a part again and will take them a second time.

func (*TextBudget) Spent

func (b *TextBudget) Spent() bool

Spent reports whether Take has reported false.

func (*TextBudget) Take

func (b *TextBudget) Take(n int) bool

Take takes n bytes of text from the budget and reports whether they were there to take. Once it has reported false the budget is spent: the extractor keeps what it had before the call and stops. A negative n is taken as 0: Take never gives back (Return does), so Take(0) only reports whether the budget is spent.

type Warning

type Warning struct {
	// Code is a stable machine-readable identifier. The codes shared by
	// all extractors are the Warn* constants; an extractor may add its own
	// under a format prefix, e.g. "pdf.font_missing".
	Code string `json:"code"`
	// Severity says how the problem affects the output.
	Severity Severity `json:"severity"`
	// Message is free text for people. Programs should switch on Code.
	Message string `json:"message,omitempty"`
}

Warning records a non-fatal problem encountered during extraction.

A warning states what happened. It never recommends what to do next: the go-fast libraries do no OCR and call no external service, so a code says "this part has images and no text", not "this part needs OCR". The caller decides what follows from the fact.

Directories

Path Synopsis
cfb
Package cfb reads compound files, the container of the legacy Office formats, and writes them.
Package cfb reads compound files, the container of the legacy Office formats, and writes them.
cfbtest
Package msbintest is the test harness of go-fast-msbin: it builds the files the library reads, so that each behaviour has a small file with exactly known content.
Package msbintest is the test harness of go-fast-msbin: it builds the files the library reads, so that each behaviour has a small file with exactly known content.
Package charset decodes text in the character encodings documents use to UTF-8.
Package charset decodes text in the character encodings documents use to UTF-8.
Package clean turns bytes read from a file into strings that obey the text conventions of the shared document model: valid UTF-8, no control characters other than line feed and tab, and for prose no surrounding white space and no presentation-form ligatures.
Package clean turns bytes read from a file into strings that obey the text conventions of the shared document model: valid UTF-8, no control characters other than line feed and tab, and for prose no surrounding white space and no presentation-form ligatures.
Package hidden has what readers share in placing what the file declares about the display of text (hidden, no ink) on blocks and spans.
Package hidden has what readers share in placing what the file declares about the display of text (hidden, no ink) on blocks and spans.
Package inflate decompresses deflate streams (RFC 1951) held in memory: raw, as zip members are; in zlib's wrapping (RFC 1950), as PDF streams are; and in gzip's (RFC 1952).
Package inflate decompresses deflate streams (RFC 1951) held in memory: raw, as zip members are; in zlib's wrapping (RFC 1950), as PDF streams are; and in gzip's (RFC 1952).
Package label writes the labels a reader sees in front of list items: bullets, and numbers as letters and Roman numerals.
Package label writes the labels a reader sees in front of list items: bullets, and numbers as letters and Roman numerals.
Package numfmt renders a spreadsheet cell's value the way the cell shows it: through its number format.
Package numfmt renders a spreadsheet cell's value the way the cell shows it: through its number format.
Package opc reads the container of the formats built on the Open Packaging Conventions (ECMA-376 Part 2): a zip archive holding parts, a table of their content types, and relationship parts that link them.
Package opc reads the container of the formats built on the Open Packaging Conventions (ECMA-376 Part 2): a zip archive holding parts, a table of their content types, and relationship parts that link them.
Package symbol translates the characters of symbol fonts to Unicode.
Package symbol translates the characters of symbol fonts to Unicode.
vba
Package vba reads the source code of a VBA project: the modules of macros an Office file carries in a storage of its compound file (a presentation, in a compound file of its own within its stream).
Package vba reads the source code of a VBA project: the modules of macros an Office file carries in a storage of its compound file (a presentation, in a compound file of its own within its stream).
vbatest
Package vbatest builds VBA projects for tests ([MS-OVBA]): compressed containers and the streams of a project, in a compound file.
Package vbatest builds VBA projects for tests ([MS-OVBA]): compressed containers and the streams of a project, in a compound file.
Package xmlscan is a streaming pull tokenizer for XML.
Package xmlscan is a streaming pull tokenizer for XML.
Package ziprecover opens a zip archive, and one cut short in transit whose directory is lost, the same way for every go-fast library.
Package ziprecover opens a zip archive, and one cut short in transit whose directory is lost, the same way for every go-fast library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL