% \iffalse
% Copyright 2026 Lukas C. Bossert
%
% This work may be distributed and/or modified under the conditions of the
% LaTeX Project Public License, either version 1.3c of this license or (at
% your option) any later version. The latest version of this license is at
% https://www.latex-project.org/lppl.txt and version 1.3c or later is part
% of all distributions of LaTeX version 2005/12/01 or later.
%
% This work has the LPPL maintenance status `maintained'.
% The Current Maintainer of this work is Lukas C. Bossert.
%
% This work consists of dfg-crc.dtx,
% dfg-crc.ins, README.md, and the derived
% dfg-crc.cls, the dfg-*.sty module packages, dfg-modules.md, and dfg-crc.pdf,
% together with the extracted example files.
%
%<*internal|cls>
%<cls>% ChkTeX's prose-oriented rules do not understand expl3 or embedded Lua.
%<cls>% chktex-file 1
%<cls>% chktex-file 8
%<cls>% chktex-file 9
%<cls>% chktex-file 13
%<cls>% Literal bracket tokens in expl3 parsers are not bracket pairs.
%<cls>% chktex-file 15
%<cls>% chktex-file 17
%<cls>% chktex-file 18
%<cls>% chktex-file 24
%<cls>% chktex-file 26
%<cls>% chktex-file 27
%<cls>% chktex-file 32
%<cls>% chktex-file 36
%<cls>% chktex-file 37
%<cls>% chktex-file 39
\def\dfgVersion{0.4.0}
\def\dfgVersionDate{2026-11-24}
%</internal|cls>
%<*internal>
\iffalse
%</internal>
%<*driver>
\preparesFile{\jobname.dtx}
%</driver>
%<@@=dfg>
%<*readme>
# dfg-crc — Collaborative Research Centre proposal class

Current release: **0.4.0 (2026-11-24)**.

Release 0.4.0 extracts eight reusable LaTeX packages for plots, workpackages,
timelines, distributions, registered icons, bibliography highlighting, and
the thumbindex. The class uses the same packages as standalone documents.
The manual includes complete examples and DTX-style command/option references.

The `dfg-crc` LuaLaTeX class provides the proposal and CV structure for a
German Research Foundation (DFG) Collaborative Research Centre (CRC). It uses
structured metadata to generate project heads, staff and funding tables,
project lists, collaboration plots, Gantt charts, and proposal-wide totals.

This is an independent, unofficial template. It is not published, endorsed,
or maintained by the DFG; applicants remain responsible for checking the
current DFG forms and programme rules.

The PDF manual combines this introduction with the detailed user and code
documentation. Its Change history appendix is generated by LaTeX from
`\changes` entries in the documented source.

The supplied proposal template is designed for five calendar years and
supports one or more applicant universities. The project types `research`,
`service`, `mgk`, and `admin` are supported; see the documentation for the
corresponding metadata and generated sections.

It is appreciated when in the colophon of your proposal a reference to this
template and its author is given.

## Requirements

The class requires LuaLaTeX and a LaTeX kernel dated 2022-06-01 or newer.
Biber is required for bibliographies. The default setup uses Arimo, Roboto
for the explicitly configured sansserif font variants, and the example
images supplied by the `mwe` bundle. A full
[TeX Live](https://tug.org/texlive/) installation is recommended and contains
the class's runtime dependencies.

Repository: <https://gitlab.git.nrw/rpdm/projects-and-services/dfg-crc-template>

Issue tracker:
<https://gitlab.git.nrw/rpdm/projects-and-services/dfg-crc-template/-/issues>

## Installation

TeX Live and MiKTeX installations obtained after the first CTAN release can
install `dfg-crc` through their normal package managers. To install from the
CTAN source archive manually, run:

```
luatex dfg-crc.ins
```

This generates `dfg-crc.cls`, its independent `dfg-*.sty` module packages,
the standalone guide `dfg-modules.md`, and sixteen complete
`dfg-*-example.tex` documents with their companion data and build helper.
The PDF manual starts with the proposal/CV user guide, followed by the
implementation reference and the independent package chapters. Keep the class and packages together
beside the proposal's main `.tex` file, or install them in a TeX search directory. The complete generated example
proposal is maintained in the repository and can be extracted with
`make files`.

## Start the program from the repository

For a first local compile, generate the derived files and then compile the
proposal and CV examples from the `local/` folder.

```
make files
cd local
latexmk -lualatex crc-proposal.tex
latexmk -lualatex crc-cv.tex
```

The class is designed for LuaLaTeX. Use `lualatex` or `latexmk -lualatex`;
do not call `LaTeX` with a capital `L`.

Keep static metadata as plain text and apply presentation settings in tables
or reference commands. Avoid formatting macros such as `\mbox`, `\textbf`
or `\emph` in IDs, person names and roles. Even one macro-valued person name
or role disables the name-disambiguation index for the entire person database,
causing a full scan for every PI reference. Macro-valued IDs also use the
original row lookup. These fallbacks can substantially increase every compile
pass. Use `firstname={Verena}` and control wrapping in the table layout.

The default base font size is KOMA-Script's nominal `11pt` setting.
Two-sided pages reserve 25 mm on the binding edge by default: a 20 mm inner
margin plus `BCOR=5mm`. Pass a different KOMA `BCOR` class option to adjust
the binding correction; `BCOR=8mm` gives 28 mm on the inner edge and a 162 mm
text block. The default 165 mm text block leaves a 20 mm outer margin for the
rotated thumb index and marginal notes.
The top and bottom margins are 20 mm and 15 mm, respectively. The footer is
included in the page layout; `footskip=12mm` leaves a 250 mm high text block.
Paragraphs have no first-line indentation and a 3.5 pt gap
(`3.5pt plus 1pt minus 0.5pt`), configurable with KOMA-Script's `\setparsizes`.
To override settings for one project, put setup code in the optional argument
of its head, for example
`\printProject[\changeSettings{journalTitle=shortjournal}]{{Head}{B02}}`.
The matching `\printProject{{Tail}}` restores the previous settings. This
applies to settings read during rendering; bibliography styles and font-family
setup must still be configured before the class loads the relevant packages.
Projects with metadata `project-status=E` automatically use
`emphasizeAuthors=true,emphasizeEntries=false`. Explicit project setup runs
after these defaults and can override either setting.
By default, the thumb-index tabs span the text block from top to bottom and
divide its current height into equal slots. Set `thumbindex@topmargin` or
`thumbindex@bottommargin` to a page-edge distance to override either end.
Use `\changeSettings{thumbindex@orientation=inwards}` to turn the labels
180 degrees towards the text block. The default `outwards` points the tops
of the letters towards the outer page edge on both left and right pages.
Labels sit 2 mm towards the text block from the center of each tab.
Use `\printThumbIndex[bg=black!20,fg=black]{1}` to set the background and
label colours for one tab and its following pages. A bare colour remains
background shorthand: `\printThumbIndex[blue-100]{A01}` equals
`\printThumbIndex[bg=blue-100]{A01}`. Each call restores unspecified colours
from `color@thumbindex@bg` and `color@thumbindex@font`; overrides do not carry
over to the next tab or alter those configured defaults. With no options or
`[]`, both configured colours are used.
Tabs and their labels are drawn in the page background, below document text
and graphics. Tab positions are correct on the first LuaLaTeX pass; no extra
pass is needed for saved TikZ coordinates. The table of contents, cross-references and
bibliography may still require further compilation runs.
Project metadata accept an optional `short-title` alongside the full `name`.
Use `\changeSettings{projectTitle={runningHead=short}}` for short running-head
titles only. The independent `toc`, `runningHead` and `projectStart` choices
all default to `full`; `short` falls back to `name` when no short title is
provided. These settings also support local project setup overrides.
With `theme=main`, wrapped table remarks (including `\printTable[note=...]`)
have no hanging indent; continuation lines start at the remark's left edge.
Left-aligned table cells use standard `\raggedright` through the shared
theme setup; choose `halign=l`, `halign=c` or `halign=r` and keep `font`
for typography. Main-theme headers use `valign=m` for vertical centring,
including multirow headings.
Numbered section and subsection titles start at the same horizontal position
after a shared 12 mm number column. Section, subsection, and subsubsection
headings have one baseline of space above them; following text starts on the
next line without an additional blank line. The paragraph gap immediately
after a heading is rigid; ordinary paragraph gaps retain their stretch and shrink.
Tables, including `FundingDirectCostsTable` breakdowns, share the normal
subsection-to-text gap, including the requested-funding staff roster.
Direct-cost breakdowns can continue across pages between rows; their optional
unnumbered heading stays with the first row. Individual rows stay together.
The class derives it from the final document fonts and paragraph spacing.
Set a nonnegative `\dfgTablePreSep` in the customization file or preamble
(e.g. `\setlength{\dfgTablePreSep}{12pt}`) to use a fixed gap instead.
Do not insert `\null` before `\printTable`: its extra interline gap would
make the spacing inconsistent.

Add a call-specific table note with, for example,
`\printTable[note={Additional information.}]{{RequestedFunding}{A01}}`.
The footnote-sized `Note:` appears below the last part of the table, before
any roster legend or job descriptions. It adds to existing table notes;
`note={}` adds no text or spacing. Footnotes within a note retain their
text and hyperlinks in the normal page footer without a wrapper environment.
Notes can be combined with target options,
for example `\printTable[all-sexes,note={Additional information.}]{GenderEqualityProjectLeaders}`.

Personnel category names are written out by default. Use
`\changeSettings{categoryAbbreviations=true}` for compact English labels
such as Postdoc and Prof.; `false` restores the full names. This applies
to project funding tables, the Category column of the project staff roster,
and CV category fallbacks. In the staff roster, an omitted `positionText`
inherits the person's position text or uses the category label if no position
text is available. That automatic position label follows the same abbreviation
setting. Explicit or inherited `positionText` values retain their supplied text;
an explicitly empty roster value hides the position line. Metadata keep the
same category IDs in either mode.

Useful make targets:

> `make files`: extracts `dfg-crc.cls` and the local template files from
the documented source. <br>
> `make update-class TARGET_DIR=/path/to/proposal-worktree`: regenerates and
copies `dfg-crc.cls` and its `dfg-*.sty` packages into a separate Git worktree. <br>
> `make update-all TARGET_DIR=/path/to/proposal-worktree`: rebuilds and copies
`dfg-crc.cls`, `dfg-crc.pdf`, and the standalone
`dfg-crc-proposal-example.pdf` and `dfg-crc-cv-example.pdf` into that worktree. <br>
> `make test`: compiles the generated template test document. <br>
> `make test-table-notes`: checks table notes, option forwarding, pagination,
and early-career row styles and former-project references. <br>
> `make test-contract-information`: checks conditional PI contract dates and
funding sources for single and multiple project leaders. <br>
> `make test-plot-section-order`: checks collaboration/Gantt plots below their
> preceding headings at page boundaries, including both caption forms and fast
> project builds with images. <br>
> `make test-direct-costs`: compiles the focused two-pass regression for DFG
> table 2.1.1. <br>
> `make test-workpackage-metadata`: checks old and grouped WP keys, mixed-key
> precedence, empty labels, deferred values, headings and nested references in
> normal, focused/image and focused/text compilation.
>
> `make test-project-short-titles`: checks full/short selection independently
> in TOC, running heads and project-start titles, formatted values, missing/blank
> fallback, scoped setup and frozen two-pass TOC writes. <br>
> `make test-project-head-layout`: compares body positions and counters after
> recorded header placeholders, including page breaks, repeated fast builds and
> missing or outdated page dimensions. It checks that header metadata stay unloaded. <br>
> `make test-workpackage-references`: compiles the focused nested-work-package
reference and range-formatting regression. <br>
> `make test-aim-references`: checks custom aim labels, forward references,
plural references, ranges, and list option scope. <br>
> `make test-bibliography-highlights`: checks frame and project entry
highlighting, font sizes, options, and isolation from ordinary lists. <br>
> `make proposal-example`: compiles the generated local proposal example. <br>
> `make cv-example`: compiles the generated local CV example. <br>
> `make check`: runs the test and compiles both examples. <br>
> `make proposal-doc-example`: builds the complete documentation consortium proposal in final
mode as `dfg-crc-proposal-example.pdf`. <br>
> `make cv-doc-example`: builds the complete twelve-PI CV appendix in final
mode as `dfg-crc-cv-example.pdf`. <br>
> `make doc`: builds both PDFs first, then includes all their pages in the user
documentation, followed by the implementation reference. <br>
> `make ctan-check`: builds the curated CTAN archive and verifies a clean
installer extraction and minimal LuaLaTeX compile. <br>
> `make ctan-validate`: runs the official online CTAN validator without
submitting the archive.

For a focused project-text build, select the project with `\includeonly` and
use these class options:

```tex
\documentclass[
  fastcompile-project=true,
  fastcompile-project-show-images=false,
  fastcompile-project-show-publications=false,
  fastcompile-project-show-funding-tables=true,
  english
]{dfg-crc}
```

`fastcompile-project` skips metadata loading and most `\addEntry` execution,
calculated project heads, generated tables/lists and plots, embedded graphics,
and other front-matter work while retaining authored sections,
paragraphs, aims, work packages, labels, and citation commands. Skipped
generated tables and lists retain the same visible placeholder and
log note as ordinary `fastcompile` builds. Project identifiers in focused
fast compilation are red typewriter placeholders such as `<A03>`.

A normal build records each complete project header's occupied space in its
ordinary `.aux` file. Focused builds reuse that space for a single labeled
`<Q02-header>` placeholder, with one block on each page for a multi-page
header. They retain the following text's position and section numbering
without reading header metadata or laying out the real title, names, research
areas or contact details. Keep the auxiliary files when switching modes.
After changing header metadata, fonts or layout, run normally again until the
header layout settles. The record is a snapshot; fast mode does not inspect
those changes. A different text width or height rejects the snapshot. Without
a matching record, the placeholder reserves half of the current `\textheight`
and is explicitly marked `approximate half text height`. A warning identifies
the fallback; its space is then only an estimate.
For example, build once with `fastcompile-project=false` (repeat if the normal
PI-card layout still changes), then use the focused options above with the
same auxiliary files. No extra cache file or metadata declaration is needed.

Set
`fastcompile-project-show-images=true` to load the project metadata and render
images and generated plots encountered in the selected project while retaining
the other fast-mode reductions. Set
`fastcompile-project-show-publications=true` when the selected project's publication headings,
explicit `\nocite` entries, and bibliography should be included. Use
`\printProjectBibliography` for project publication lists; plain
`\printbibliography` uses biblatex's normal font and bypasses the
project-publication switch.

Journal names use `journaltitle` by default. Store an established abbreviation
in the standard BibLaTeX field `shortjournal` and select it with
`\changeSettings{journalTitle=shortjournal}`. Missing abbreviations fall back to
the full title. Use `\changeSettings{journalTitle=journaltitle}` to return to
full titles. The choice also applies to full citations, can be grouped locally,
and preserves the bibliography style's typography. It performs no online
lookups during compilation.

To use footnote-sized text and remove extra space between bibliography entries,
add this hook to `preamble/dfg-customization.tex` (outside `\changeSettings`):

```latex
\AddToHook{package/biblatex/after}{%
  \renewcommand*{\bibfont}{\normalfont\footnotesize}%
  \setlength{\bibitemsep}{0pt}%
}
```

The hook waits until `biblatex` has loaded because the customization file is
read earlier. `\bibitemsep` controls the extra gap between entries; change
`0pt` to `2pt`, for example, for a small gap. It does not change line spacing
within an entry. Without an override, the bibliography style supplies its
spacing; the alphabetic styles inherit the current `\itemsep` when
`biblatex` loads. Depending on the class and list configuration, this may
already be zero. Other styles can supply different defaults. The CV's
custom `DFGlist` already uses `nosep` and is configured separately through
its `itemsep` list option.

With `emphasizeEntries=true`, a full project bibliography entry is bold when
its `.bib` keywords include the current project ID followed by `-highlight`,
for example `B06-highlight`. One such keyword is enough even if two PIs from
Project B06 coauthor the entry. An entry may also carry another project's
highlight keyword when it should be bold in that project's list. The
`B06-project` keyword is optional project metadata; it does not trigger bold
type. Other keywords, including CV selectors such as `pabst-A`, can remain in
the same field. To use only whole-entry highlighting, set
`emphasizeAuthors=false` and `emphasizeEntries=true`.

For the frame-text references in chapter 1, use `\printFrameBibliography`
with the same options as `\printbibliography`. With `emphasizeEntries=true`,
entries tagged `frametext-highlight` are bold in this list. Project-specific
highlight keywords do not affect it, and the normal bibliography font size
is preserved. For example:

```latex
\changeSettings{emphasizeEntries=true}
\defbibnote{frame-references}{%
  \usekomafont{subsection}%
  \bfseries\sffamily References
}
\printFrameBibliography[prenote={frame-references},heading=none]
```

The `.bib` entry may combine keywords, for example
`keywords = {pabst-A,B06-highlight,frametext-highlight}`. The keyword selects
formatting only; cite the entry or use `\nocite` to include it as usual.
Existing chapter 1 files need the command replacement above because template
updates preserve edited chapter files.

Wrap optional
metadata and front matter with `\dfgIfFastCompileProjectF{...}` so those files
are not even read in this mode. With publications disabled, bibliography source
files and stale `.bbl` data are also left unread; inline citations display their
keys as lightweight drafting markers. The three project-local funding tables
remain visible by default. Set
`fastcompile-project-show-funding-tables=false` to suppress them too. Focused
mode processes their local rows and sums but does not restore or populate
proposal-wide overview databases. Compile a document using these options
with its own build command; the template Makefile deliberately operates only on
the generated test and example documents in `local/`.

## Template validation workflow

Run `make check` to regenerate the template files, compile the test document,
and compile both local examples. Run `make all` to perform those checks and
build the complete implementation and user documentation. These targets use
only files maintained or generated by this repository.

GitLab CI runs the same compile-based checks for branches and merge requests.
After a successful default-branch pipeline, GitLab Pages publishes the newest
generated `local/crc-proposal.pdf`. The Pages site is rebuilt from an empty
`public/` directory each time and therefore exposes only the latest dummy
proposal, not an archive of earlier PDFs. CI job artifacts retain the current
logs and example outputs temporarily for diagnosing failed pipelines.

## Updating a separate proposal repository

Edit the maintained `.dtx` source, then install the regenerated class into a
separately controlled proposal worktree:

```
make update-class TARGET_DIR=/path/to/proposal-worktree
# Or update the class, compiled manual, and complete example PDF:
make update-all TARGET_DIR=/path/to/proposal-worktree
```

Both targets verify that `TARGET_DIR` is the root of a different Git worktree,
copy the requested release files, and show their resulting Git status.
`update-class` copies `dfg-crc.cls` and its `dfg-*.sty` packages; `update-all` first rebuilds the manual
and then copies the class and packages, `dfg-crc.pdf`, and
`dfg-crc-proposal-example.pdf` and `dfg-crc-cv-example.pdf`. Neither
target overwrites the proposal repository's README, changelog, or licence. They
do not store the destination, inspect its remote, commit, or push. Review and
commit the updates from inside that proposal repository.

## Repository boundary

This repository is intentionally limited to the reusable proposal template.
Project-specific source, synchronization configuration, credentials, remote
identifiers, and private working copies must remain in separately controlled
repositories or local worktrees and must not be added here as submodules.

## Structure of the files and folders

The maintained source is `dfg-crc.dtx`.
Generated files such as `local/dfg-crc.cls`,
`local/test-existing-funds-direct-costs.tex`,
`local/test-project-collaboration.tex`,
`local/test-workpackage-references.tex`, `local/test-participating-institutions.tex`,
`local/test-command-options.tex`, `local/test-reference-lookups.tex`,
`README.md` and the local example files are extracted from that source.
Edit the `.dtx` for template or documentation changes, then regenerate the
derived files with `make files` or by building the documentation.

The manual uses `dfg-crc` itself, with `documentation=true` to load only its
explicit fictional fixtures. The DTX driver maintains executable `dfgExample`
boxes: code on the left, rendered output on the right. Add `[dfg wide]` for
wide results below their code. `make doc` regenerates the fixtures and compiles
the examples; incomplete setup fragments remain code-only. This does not
read or overwrite the manual scratch file `local/test.tex`.

The manual and local examples share the DTX `meta` records: twelve PIs, six institutions,
four affiliations, and fifteen active projects (A01--A06, B01--B06, Q01--Q03),
plus a former project. The embedded proposal uses these same metadata in
`local/`, with individual files for all fifteen active projects and the former
project A00. The local CV uses the same twelve PIs, with matching career records
and explicitly fictional publications for each person. Examples use `dfg project=A03` when they need the context
normally established by a project heading. Project overviews and the PI roster follow their code boxes at normal size
and may span pages; collaboration plots retain the available text width.

`make test-participating-institutions` checks flowing/raster column widths,
active-PI filtering, shared-institution deduplication, sorting, spacing above
columns, and option scope. `make test-command-options` checks omitted/empty,
leading/legacy options, precedence, grouped command specifications, mandatory
arguments, custom databases, boolean flags, and per-call defaults for lists,
tables, plots, and PI rasters. `make test-reference-lookups` covers generic
reference paths, branching ID lists, destination deduplication, diagnostics,
and focused-build placeholders.
`make test-animal-totals` checks custom animal types, grouped/separate
subtotals, direct count/cost queries, legacy rates, independent databases,
missing values, and pagination.

The standalone regression document is maintained in `ci/test-template.tex`.
`make test` copies it to `local/test-template.tex` before compiling it.
`local/test.tex` is reserved for manual experiments and is neither generated
nor compiled by the template checks.

## Generated project templates

The generated `local/content/03_project.tex` is a small master file that loads
separate, complete project examples. They are intended to be copied and adapted
rather than reduced to a list of headings:

`03_project_A01.tex`: continuing research project (`project-status=C`).

`03_project_A02.tex`: new research project (`project-status=N`).

`03_project_B01.tex`: second continuing research-project example.

`03_project_B02.tex`: ending project (`project-status=E`), including the report
bibliography, the three published-result categories, and the staff roster for
the ending funding period.

`03_project_Q01.tex`: continuing service project.

`03_project_Q02.tex`: continuing Integrated Research Training Group
(`project-type=mgk`), including existing funds, fellowships, and global funds.

`03_project_Q03.tex`: central administrative project with its dedicated
documentation and funding structure.

Every example starts with `\printProjectHead{<id>}`. That command already
generates the general-information heading, project title, project leaders, and
the applicable contract and legal-information blocks from metadata. The source
files therefore begin with the first status-specific authored heading: `Summary`
for active projects and `Project history` for ending projects.

The generated proposal-wide example follows the February 2026 continuation
template, including the ecological-sustainability section, separate
coordinating and co-applicant universities, the current legal-issues wording,
and one rector, chancellor, or president signature per applicant university.

> `bib/`: all bibliography files.  <br>
> `content/`: all files which are part of the actual content of the proposal,
e.g. all project textfiles.  <br>
>  `figures`: folder contains all figures of the projects.  <br>
>  `img`: folder can be used for logo files etc.  <br>
>  `metadata`: if you collect all database entries in specific external  
  files, they are placed in this folder (e.g. `dfg-metadata.tex`).  <br>
> `preamble`: all files for the proposal and CV setup, especially
  `dfg-customization.tex` for customized things or re-newed settings.<br>

## Minimal metadata relationship

Most commands resolve data by following ids through the small databases:

```
person.ref-institution-id -> institution.id
institution.ref-affiliation-id -> affiliation.id
project.collaborations -> project.id
```

For example, a person may list one or more institution ids in
`ref-institution-id`. Each institution points to its parent affiliation via
`ref-affiliation-id`. Once this relationship exists, commands such as
`\printList{{Institutions}{<person-id>}}` can print the institution and affiliation
data without further manual wiring.  Each institution can also provide an
`abbreviation`; generated table cells use this compact label while descriptive
lists and legends retain the full `name`.

The same relationship is reused by `RequestedFundingStaff`: when a staff row
contains `ref-person-id`, its category and institution are taken from the
person's `position` and `ref-institution-id` fields unless the staff row
explicitly overrides them. The legend below the table prints each institution
once as `abbreviation: full institution name (affiliation abbreviation)`.
The note then expands affiliation abbreviations as
`affiliation abbreviation: full affiliation name`. All entries use semicolon
separators. Existing- and requested-staff tables share this footnote-size
`Abbreviations:` note, including its regular font weight and spacing.
A row without `ref-person-id` must provide
`ref-institution-id`; otherwise the class warns because it cannot resolve the
institution or assign existing staff to an affiliation in the proposal-wide
overview. Existing and requested non-research staff may omit
`field-of-research`; that empty table cell is then greyed out as not applicable
without a warning. Empty
staff positions are omitted without a warning or an empty line. The job
descriptions printed below each requested-funding staff table use flush-left
number labels and a hanging indent so continuation lines align with the first
line of description text. A normal interword space separates the bold name
from the description.

Project collaboration plots follow the comma-separated project ids stored in
each project's `collaboration` key (`collaborations` remains an alias).
Relations are undirected, so declaring
the same pair in both project rows is harmless but unnecessary. Ending,
reference-only, and list-excluded project rows remain available elsewhere but
are omitted from these plots.

## Information retrieval command overview

The following commands can be used directly in proposal text and tables. In
the signatures below, square brackets are optional and braces are mandatory.
The complete descriptions and examples are in
`dfg-crc.pdf`.

### General database access

Command `\get[database]{id}{field}` prints a metadata field. Add reference
steps to retrieve fields from linked rows, for example
`\get[person]{MM}{institution}{name}` or
`\get[person]{MM}{institution}{affiliation}{name}`. Each step follows
`ref-<database>-id`; the full key spelling is also accepted, as in
`\get[person]{MM}{ref-institution-id}{name}`. This works from any source
database, including named databases populated with a separate keyset.
Multiple reference IDs are followed in their stored order and the resulting
values are separated by commas. A destination row reached more than once is
printed only once; different rows with identical names remain separate.
Missing or empty references warn and contribute no value. The terminal field
keeps its formatting and `showtags` annotation. Focused fast compilation uses
the source ID placeholder, as with `\getEntry`. `\get*` retains the starred
multi-field assignment syntax of `\getEntry*`.

Command `\getEntry` with `[database]` `{id}` `{field}` `[id-field]` prints one field from one
  database row.

Starred command `\getEntry*` with `[database]` `{id}`
`{assignments}` `[id-field]` fetches several fields in one lookup and assigns
them without printing. For example, fetch person `MM` with
`\getEntry*[person]{MM}` and pass the third argument
`{\theFirstName=firstname,\theLastName=lastname}`.

Command `\compareEntry` with `[database]` `{id}` `{field}` `{value}` `{true}`
  `{false}` chooses text or
  code according to a field comparison.

### People, institutions, and projects

Commands `\getName` and `\getFullName*` with `{person-id}` print the last name or full name;
  the star adds the academic degree.

Command `\getPI*` with `{person-id-list}` `[text]` prints a linked PI reference; the star includes
  first names. Unstarred references distinguish shared PI surnames with the first given-name
  initial (K. Schneider / C. Schneider), or the full given name when initials also match.
  This rule applies across projects and funding periods, including project-first references.
  Explicit display text bypasses it; starred references retain full given names.

Command `\getORCiD` with `[database]` `{person-id}` prints a linked, formatted ORCiD from a person row.

Command `\getORCiDvalue` with `[database]` `{person-id}` stores the unformatted ORCiD in
  `\theORCiDValue`.

Command `\printList{{Institutions}{<person-id>}}` prints institutions and
  parent affiliations assigned to a person. Put formatting and database options
  before the specification, for example
  `\printList[database=person,abbreviation,narrow]{{Institutions}{MM}}`.

Command `\printList{ParticipatingInstitutions}` lists participating institutions
  across the proposal, with affiliation names in bold. Use `columns=2` (or
  `columns=3`, etc.) to flow whole affiliation groups down balanced columns.
  Short groups follow one another without being padded to the height of a
  neighbouring group. Groups stay together; reading order is down each column.
  `column sep=16pt` changes the gap (default: 12 pt). Flowing lists start a
  new paragraph with a medium vertical skip above the columns.
  The default layout remains a one-column raster, with 12 pt between columns
  and 10 pt between rows. For aligned rows, pass `raster columns=2` or another
  `tcbraster` option through the optional list argument. Sorting defaults to
  `order=count`; use `order=alpha` for alphabetical affiliation order. The
  legacy bare `count` and `alpha` options remain supported.

Put all list options before the specification, as with `\printPlot`.
Plain and grouped list names are both accepted. Older trailing options remain
supported; leading settings take precedence when the same key occurs twice.

```latex
\printList[columns=2]{ParticipatingInstitutions}
\printList[columns=3,column sep=16pt,order=alpha]{ParticipatingInstitutions}
\printList[order=alpha,raster columns=2]{{ParticipatingInstitutions}}
```

Command `\getPersonInformation` with `[database]` `{person-id-list}` prints complete formatted
  PI/contact-information blocks. Project heads use a full-width one-column raster
  for one PI and a two-column raster with a 12 pt column gap for several PIs.
  Both use the same spacing below the project-leader heading.

Command `\getPIsWithRole` with `[options]` `{role}` prints formatted current-period people
  carrying a given role. Put database and raster settings in the leading options,
  for example `\getPIsWithRole[database=person,raster columns=2]{PI}`.
  Use `\getPIsWithRole[academicdegree-below]{steering-committee-member}`
  to put the degree on a separate line below the name within the same PI box.
  The option applies only to that call; the default (or `academicdegree-below=false`)
  keeps the degree inline after the name.
  The default three-column raster has a 12 pt column gap;
  rows and the following content are separated by 20 pt. Explicit raster options
  can override that spacing.

PI-box titles are ragged right and top-aligned. All titles within one raster
reserve the height of its tallest title, so wrapped names or academic degrees
do not misalign the contact information. Recompile until the equal-height
layout settles; a clean build can require three LaTeX passes. Phone and email
stay individually unbroken, with a one-em gap that permits a line break
between them when they do not fit together.

Use `\getPIWithProject*` with `{person-id-list}` to print each PI with their
  assigned project identifiers in parentheses, without repeating the projects'
  PI names; the star includes first names. The older
  `\getPIProject` command remains available but warns that it is deprecated.

Use `\getProjectWithPI*` with `{project-id-list}` to print each project with
  its assigned PIs; the star includes first names. The older `\getProjectPI`
  command remains available but warns that it is deprecated. By default, the
  shared first `\getProject` or
  `\getProjectPI` reference to a project within one section includes its PIs;
  later references print only the project. Set
  `projectPIOncePerSection=false` in `\changeSettings` to repeat the PI names.

Command `\getPIofProject` with `[properties]` `{project-id}` `[delimiter]` prints selected PI name
  properties for one project. The starred form defaults to first and last names,
  separating earlier names with commas and only the last with “and”.

Command `\getProject*` with `{project-id-list}` `[text]` prints a linked project
  reference. The star always prints project identifiers only, independently of
  `projectPIOncePerSection`. Optional `text` replaces the displayed project number while
  retaining its link target and is best used with a single project. A
  reference-only project is marked and deliberately left unlinked. Multiple
  projects are joined with commas and a final `and` in prose, but use compact
  slash separators inside table cells, for example `A02/B01`. With the
  default `projectPIOncePerSection=true`, this command shares
  `\getProjectPI`'s first-reference PI expansion and per-section state.

Command `\getProjectCount` with `[area]` prints the active, list-considered
project count; omit `area` for all projects. Any explicit or ID-derived
`project-area` value is accepted.

Command `\printPlot{{collaboration}{A01}}` prints the default
full-width arc layout for A01, with project nodes and unlabelled area rules.
Its boxes align with the text edge on both sides of a two-sided page.
Its caption appears below the plot by default; a final optional argument adds
caption text.
Add `[arcs=true]` before the plot specification to draw the connecting arcs,
or use `[layout=heatmap]` for the heatmap. The optional
`project-area` field creates rows dynamically and falls back to the first
character of the project ID. Configure proposal-wide colors with
`collaborationAreaColors` and `collaborationAreaPalette` in `\changeSettings`,
or use the per-plot `area-colors` and `area-palette` options. Gantt charts use
the same dispatcher as `\printPlot{{gantt}{A01}}`. Inside a project, omit
the ID: `\printPlot{{gantt}}` and `\printPlot{{collaboration}}` use the
current project. Options precede the plot specification, for example
`\printPlot[caption={Additional details}]{{gantt}}` or
`\printPlot[arcs=true]{{collaboration}{B06}}`. With an explicit ID, use the
same leading caption option:
`\printPlot[caption={Additional details}]{{gantt}{B06}}`. The older `Gantt` and
`ProjectCollaboration` type names remain available. Use the singular
`collaboration` for the plot type, project metadata key, and local connection
override; `collaborations` remains a compatibility alias. The optional
`show-projects={A01,A02}` filters displayed nodes, always including the focus;
its former `projects` spelling remains an alias. In project source files,
`caption={}` marks where optional caption text can be added to either plot;
left empty, the default caption is still printed.
Use `plotOptions`, `ganttPlotOptions`, and `collaborationPlotOptions` in
`\changeSettings` to set shared and type-specific defaults, including native
`hvFloat` options such as `floatPos`, `capPos`, and `style`. Precedence is
built-in defaults, shared defaults, type-specific defaults, then per-call
options. For example:

```latex
\changeSettings{
  plotOptions={floatPos=!t,capPos=bottom},
  ganttPlotOptions={floatCapSep=8pt},
  collaborationPlotOptions={layout=heatmap,arcs=true}
}
\printPlot[capPos=top]{{gantt}{Q01}}
```

The class also supplies the native `hvFloat` style `proposalPlots`
(`floatPos=!t,capPos=top,floatCapSep=8pt`). Select it with
`\changeSettings{plotOptions={style=proposalPlots}}`; its definition is
provided by the class, so no hook is needed in customization.

Gantt charts always use `fig:gantt-<project-id>` as their figure label,
for example `\cref{fig:gantt-A02}`, with or without additional caption text.
This also applies to the compatibility command `\printGantt`.
Update older caption-free references such as `fig:ganttA02` to `fig:gantt-A02`.

Command `\dfgResearchAreasList` with `{code}` prints a DFG research-area code and its description.
`\printList{ResearchAreasFromProjects}` collects the codes from non-ending
research and service projects, matching the project tables. Projects excluded
from lists and explicitly excluded project numbers are omitted. Each call
rebuilds the list, sorts the codes, and removes duplicates.
The project tables center these codes as text in a 15 mm column, including
cells with several codes.

Commands `\getAim` and `\getWP` with `[project-id]` `{id-list}`
  cross-references to project aims or work packages; the current project is
  the default. `\getWP` places a narrow, unbreakable space after `WP` or `WPs`.

The `aims` environment accepts a custom prefix shared by the numbered items
and references:

```tex
\begin{aims}[label={RDM Aims}]
  \addAim{data} Document research data.
  \addAim{reuse} Publish reusable datasets.
\end{aims}
See \getAim{data,reuse}.
```

This prints `RDM Aims 1:` and `RDM Aims 2:`, with `RDM Aims 1 and 2` in
the reference. `\cref` and `\Cref` also use the custom prefix. Its text is
used unchanged for single and multiple references; ordinary `aims` lists
retain `Aim`/`Aims`. Other list options, such as `start=3`, remain available.
Compile twice after changing labels to update forward references.

Use `resume` to continue numbering from the previous `aims` list. Repeat
the custom label to keep it in both the items and their cross-references:

```tex
\begin{aims}[label={RDM Aims},resume]
  \addAim{archive} Archive the datasets for long-term access.
\end{aims}
See \getAim{archive}.
```

Following the two-item list above, this prints `RDM Aims 3:` and references
it as `RDM Aims 3`. `[resume]` alone continues the number with the default
`Aim`/`Aims` prefix. Numbering resumes from the previous `aims` list,
regardless of its label text; custom labels do not create separate counters.

### Person statistics

Command `\getPositionGenderPhaseAmount` with `[database]` `{position}` `{gender}` `{period}` prints the number
  of people for one position/gender/period tuple.

Command `\getPositionPhaseTotal` with `[database]` `{position}` `{period}` prints the all-gender total for a
  position and funding period.

Command `\getGenderPhaseTotal` with `[database]` `{gender}` `{period}` prints the all-position total for a
  gender and funding period.

Command `\getPositionGenderPhasePercentage` with `[database]` `{position}` `{gender}` `{period}` prints the
  rounded integer percentage within one position.

Command `\getGenderPhasePercentage` with `[database]` `{gender}` `{period}` prints the rounded integer
  percentage across all counted positions.

The optional database defaults to `person`. Counts include people whose
`role` list contains `PI` and whose `period` list contains the requested
funding period. The total-row commands sum `postDoc`, `groupLeader`,
`prof-W2`, and `prof-W3`. Gender is `f`, `m`, or `d`; percentages are rounded
integers without a percent sign and return zero when the denominator is zero.

```tex
% First-period table values: women across all four career categories.
\getGenderPhaseTotal{f}{1}
\getGenderPhasePercentage{f}{1}\%
% Female W3 professors: number, percentage, and all-gender total.
\getPositionGenderPhaseAmount{prof-W3}{f}{1}
\getPositionGenderPhasePercentage{prof-W3}{f}{1}\%
\getPositionPhaseTotal{prof-W3}{1}
```

Change the last argument to `2` or `3` to query another funding period.
These commands are available independently of the current proposal period.
Section 1.4.2 B adds the first-period Number and Percentage columns only for
proposals with `fundingPeriodNumeral = {3}`. Maintain historical PI records
with their appropriate `period` membership to populate these columns.
The statistics count people; the share of projects with female leadership
requires a separate calculation.

The project-leader table defaults to the female-only DFG layout. For a
third-period proposal, periods 1 and 2 each show Number/Percentage; period 3
shows its original objective (from `future-objective-percentage-female`) and
current Number/Percentage. The person records' period-3 membership supplies
these current counts. Percentages always use all genders as the denominator.
Select the expanded f/m/d comparison, including third-period counts and
percentages alongside its objective columns, for a single table:

```tex
\printTable{GenderEqualityProjectLeaders}            % female-only DFG view
\printTable[all-sexes]{GenderEqualityProjectLeaders} % expanded f/m/d view
```

Each call starts in female-only mode; `[all-sexes]` affects only that table.
Put options before the table name. Combine `database=MyObjectives,all-sexes`
to use a custom
objectives database. The prose count and percentage commands are unaffected.

### Funding and staff totals

The similarly named funding commands have different scopes: names ending in
`RequestedFunding` use the proposal-wide overview by default, while names
ending in `RequestedFunds` use project-level funding rows and require a
project id.

Command `\getCountRequestedStaff` with `[project]` `{year}` `{category}` prints the requested staff
  quantity for a category, optionally restricted to a project.

Command `\getSumRequestedFunding` with `[database]` `{year}` `{type}` prints the proposal-wide total for one
  funding type and one year; `{all}` as the year totals all five years.

Command `\getTotalSumRequestedFunding` with `[database]` `{year}` `{type}` prints the proposal-wide total
  with `{all}` as the type available for a grand total.

Command `\getSumPreviousRequestedFunding` with `[database]` `{year}` `{fields}` prints the previous-period
  total for one year row, or all rows with `{all}` as the year.

Command `\getSumRequestedFunds` with `[database]` `{project}` `{type}` `{sum-fields}` prints the project total
  for one funding type and one or several `sum-yearN` fields.

Command `\getTotalSumRequestedFunds` with `[database]` `{project}` `{sum-fields}` prints the project total
  across all funding types for the supplied `sum-yearN` fields.

Command `\getSumRequestedFundsInstrumentation` with `[project]` `{sum-fields}` prints the instrumentation
  total, proposal-wide or for the optional project.

Command `\getSumRequestedFundingDirectCosts` with `[database]` `{year}` `{group}` prints the direct-cost
  total for `applicant`, `participant`, `other-funds`, or `all`. Its default
  database is the auxiliary-file-backed
  `RequestedAndExistingFundingDirectCostsOverview`, and its displayed result
  is a full euro amount without decimal places.

Command `\getSumExistingFunds` with `[database]` `{project}` `{sum-fields}` prints the existing direct-cost
  funding for a project and the supplied year fields.

Typical calls are:

```tex
\getProjectCount[A]                            % active A projects
\getSumRequestedFunding{all}{staff}            % proposal-wide staff total
\getTotalSumRequestedFunding{all}{all}         % proposal-wide grand total
\getSumRequestedFunds{A02}{staff}{sum-year1}   % A02 staff total, year 1
\getTotalSumRequestedFunds{A02}{sum-year1}     % A02 grand total, year 1
```

Funding entries, including requested instrumentation, use EUR as their input
unit. Their tables state `Figures in EUR.` and display whole euro amounts with
thousands separators. The non-aggregated `existingInstrumentation/cost` field
instead uses thousands of EUR and its table states `Figures in thousands`;
one decimal place is retained when supplied. Explicitly fractional
animal-housing rates and per-animal purchase prices also retain decimals.
The requested/existing funding columns remain whole euros.

### Laboratory-animal types and totals

The animal table derives its subtotals and grand total from its own rows.
Only represented groups appear. The built-in types are `mouse`,
`mouse-gnotobiotic`, and `rat`; gnotobiotic mice count toward `mouse`.
Declare additional types in `preamble/dfg-customization.tex`:

~~~latex
\DeclareAnimalType{zebrafish}{
  label={Zebrafish},
  label-plural={Zebrafish},
  housing-rate=0.12
}
\DeclareAnimalType{mouse-gnotobiotic}{total-group=mouse}
~~~

`total-group` names the type itself or an already registered type; that type
supplies the subtotal's plural label, without changing the row's own label or
housing rate.
When omitted for a new type, it defaults to that type's own ID. IDs use lowercase
letters, digits, and hyphens, starting with a letter. Redeclaring a type updates
only the supplied fields. New types require a label and a non-negative housing
rate in EUR per animal per week; the plural defaults to the label.
Declarations and rates respect TeX groups. Existing `animalHousing@...`
settings and `\dfgMouseHousing`/`\dfgRatHousing` accessors remain supported.

Keep existing `\addEntry{UpkeepLaboratoryAnimals}{...}` records and the usual
`\printTable{UpkeepLaboratoryAnimals}` call. To separate housing types, use
`\printTable[totals-by=type]{UpkeepLaboratoryAnimals}`. A custom database can
be selected with `database=MyAnimals`; the old bare `[MyAnimals]` argument also
works. All totals are rebuilt per call, using only that database's rows.
Funding totals sum the supplied requested/existing amounts, without inferring
them from animal counts or unit costs. Blank or invalid numbers print a dash;
affected subtotals/totals carry an asterisk and a note explaining that only
known valid amounts are included. Explicit zero is retained. A row without a
registered species remains visible and contributes to `Unclassified`.

Read counts and costs directly after declaring the data, without printing a table:
~~~latex
\getAnimalCount                       % All animals
\getAnimalCount[group=mouse]          % Mouse group, including gnotobiotic mice
\getAnimalCount[type=mouse]           % Only the mouse type
\getAnimalCosts[group=mouse,cost=requested] % Default cost selection
\getAnimalCosts[group=mouse,cost=existing]
\getAnimalCosts[group=mouse,cost=purchase]
\getAnimalCosts[group=mouse,cost=housing]
\getAnimalCosts[group=mouse,cost=total]
~~~
Both commands accept `database=MyAnimals` and either `group` or `type`.
Omit the selector for the entire database. Purchase costs are quantity times
unit purchase price; housing costs are quantity times weeks times each row's
own housing rate. `total` combines these calculated costs. Requested/existing
funds remain the supplied amounts. Funding displays use whole EUR; calculated
costs retain up to two decimal places. Add the currency unit in surrounding text.
Missing inputs mark partial results with an asterisk; only known components
are summed. Unknown IDs/options produce a warning and a dash.

### Existing direct-cost support in section 2.1.1

Declare institutional and other existing direct-cost support once, next to
the corresponding project table:

```tex
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {B06},
  ref-affiliation-id = {aff1},
  financed-by        = {Faculty core support},
  sum = {
    year1 = {5000},
    year2 = {5000},
    year3 = {5000},
    year4 = {5000},
    year5 = {5000}
  }
}
```

The sums are stored and displayed in euros. Table 2.1.1 therefore prints
`5000` as `5,000`; monetary values are rounded to the nearest euro for display
and never acquire a redundant decimal part. An affiliation listed in
`meta/crc.ref-affiliation-id` contributes to the applicant-university column;
another affiliation contributes to the other-participating-institutions
column; and the special value `other-funds` contributes to Other funds.
`financed-by` is the human-readable funding-source description and does not
select the aggregate column.

The declarations may remain in project files even though section 2.1.1 comes
earlier. They are restored into a separate overview database through the
LaTeX auxiliary files. A normal multipass build such as `latexmk` is therefore
required after adding or changing a row; no duplicate chapter-2 declaration
is needed.

## Open-access markers in bibliography entries

The class loads `biblatex-ext-oa` so bibliography entries can show
open-access markers in final documents. The DOI API integration is only
available with LuaLaTeX. With LuaTeX 1.17.0 or newer, the socket library must
also be enabled on the command line, for example with `lualatex --socket`.
Provide the contact address required by the API in the customization file:

```tex
\changeSettings{
  doiAPIMail = researcher@example.org
}
```

The class enables DOI lookups only when `final=true`, `doiAPIMail` is not
empty, and LuaSocket is available. Otherwise it retains manual open-access
annotations without making network requests.

The open-access symbol links to the detected accessible version. The class
suppresses the package's additional `open access version at` text and URL;
ordinary DOI, eprint, and URL output follows the bibliography style. The
suppression is applied only when the DOI API backend is enabled.

If the API-based open-access request does not work for a publication, add the
manual fallback annotation to the relevant `.bib` entry:

```
options         = {openaccess=auto},
doi+an:default  = {=openaccess},
```

## Troubleshooting

Use `latexmk -lualatex ...` or `lualatex ...`. The command `LaTeX` asks TeX for
a format named `LaTeX.fmt` and will usually fail.

If you see `Not allowed in LR mode`, check whether vertical material such as
`\vspace`, `\addvspace`, or a paragraph break was inserted inside a table cell
that only accepts horizontal material. Prefer the documented commands and
options instead of adding raw vertical spacing in table cells.

`Unknown database name` means the requested database has not been loaded or the
database name was misspelled. Check the relevant file in `metadata/` and make
sure it is input by the document class.

Missing-key or empty-value warnings mean the row exists, but the requested
field is empty. This is intentional for fields where the template needs to
alert you, such as missing ORCiD values.

If a change has no visible effect, check which `dfg-crc.cls` is being used.
Regenerate the class and local examples with `make files`, then compile the
relevant example again.

%<dev>## Maintainer release checklist
%<dev>
%<dev>1. Update `\dfgVersion`, `\dfgVersionDate`, the README release line,
%<dev>   add a `\changes{version}{date}{description}` entry, and update
%<dev>   `dfg-crc.pkg` in one commit.
%<dev>2. For CTAN updates after the initial release, set `\update{true}` in
%<dev>   `dfg-crc.pkg`. Keep the CTAN path
%<dev>   `/macros/luatex/latex/dfg-crc`, and omit `\home` when it duplicates
%<dev>   the repository URL.
%<dev>3. Do not include the generated `dfg-crc.cls` in the CTAN archive. CTAN
%<dev>   requires files generated from a documented source and installer to be
%<dev>   omitted; the PDF manual and example PDF are documentation exceptions.
%<dev>   Licensing is recorded at the top of the DTX; change history is generated
%<dev>   with `\changes` and included in the manual. Do not ship separate
%<dev>   generated changelog or license files.
%<dev>4. Confirm that `bossert@itc.rwth-aachen.de` is registered as the second
%<dev>   address of CTAN member `lukascbossert`. Keep release information in
%<dev>   separate Announcement and Note fields; CTAN explicitly accepted that
%<dev>   structure for the initial release.
%<dev>5. Build the documentation and the CTAN archive, then run the portable
%<dev>   installer and minimal-class smoke test:
%<dev>
%<dev>   ```
%<dev>   make ctan-check
%<dev>   ```
%<dev>
%<dev>6. Run at least one proposal/CV smoke build from `local/`:
%<dev>
%<dev>   ```
%<dev>   cd local
%<dev>   latexmk -lualatex -g -halt-on-error crc-cv.tex
%<dev>   ```
%<dev>
%<dev>7. Before a public release, run the complete template check:
%<dev>
%<dev>   ```
%<dev>   make check
%<dev>   ```
%<dev>
%<dev>8. Run the official online validator with
%<dev>   `make ctan-validate`.
%<dev>9. Review `git status --short`, `git diff --check`, and the archive file
%<dev>   list before committing and tagging the exact release version.
%<dev>
## Support

The current maintainer is
[Lukas C. Bossert](mailto:bossert@itc.rwth-aachen.de).

## License

This material is subject to the LaTeX Project Public License 1.3c or later.
The work has the LPPL maintenance status *maintained*. The complete notice
is at the top of `dfg-crc.dtx`; the current
maintainer is Lukas C. Bossert.
%</readme>
%<*modules-guide>
# Reusable LaTeX modules

Development branch: `feature/standalone-proposal-modules` in both repositories.
The maintained source is `dfg-crc.dtx` in the
template repository. Its installer generates the class and all packages.
`dfg-crc.cls` loads the packages and adds adapters for proposal metadata,
references, colours, bibliography scopes, and fast compilation. There is one
implementation of each renderer.

## Packages and dependencies

| Package | Purpose | Main dependencies |
|---|---|---|
| `dfg-plots` | Plot dispatch, shared/type-specific defaults, native float styles | `hvfloat` |
| `dfg-collaboration` | Arc diagrams and focus heatmaps | `dfg-plots`, TikZ `calc` |
| `dfg-gantt` | Workpackages, references, configurable quarter grids | `dfg-plots`, `pgfgantt`, `datatool`, `enumitem`, `etoolbox` |
| `dfg-timeline` | Event timelines, date ranges, categories, details | TikZ, `fontawesome5`, `enumitem` |
| `dfg-distribution` | Segmented distributions with registered vector icons/categories | TikZ, LaTeX3 |
| `dfg-icons` | Registered graphic variants and paragraph wrapping | `graphicx`, `wrapstuff`, `etoolbox` |
| `dfg-bib-highlights` | Selected authors and whole bibliography entries in bold | `biblatex`, `xcolor`; Biber for name hashes |
| `dfg-thumbindex` | Coloured page-edge tabs, facing-page rotation, configurable slots | TikZ, `scrlayer-scrpage` |

These packages work with standard document classes and pdfLaTeX or LuaLaTeX.
The proposal class continues to require LuaLaTeX. Load only the packages you
need. They do not load proposal metadata, use a project-specific font, fetch
data from a network service, or require RWTH colour definitions. Graphic
assets remain the responsibility of the document using them.

To install from source, run the portable `.ins` file. Keep the generated
packages beside the document or install them in a TeX search directory.
The plotting packages need `dfg-plots.sty` as well as their own `.sty` file.
The class must be distributed together with all generated packages.

Both installers export sixteen complete `dfg-*-example.tex` files, a companion
bibliography, and `dfg-module-examples.md` with the exact package
files needed for each example. The portable installer writes them beside the
packages; the developer installer uses `local/module-examples`.
The main PDF manual starts with the proposal/CV user guide. The final part,
**Independent LaTeX packages**, has one chapter per package, complete source
listings, and separately compiled results.

In this proposal repository, build the minimal and option-variation examples with `make module-examples`,
or compile individual files directly:

```sh
cd docs/examples
TEXINPUTS=../..: latexmk -lualatex -halt-on-error dfg-gantt-example.tex
TEXINPUTS=../..: latexmk -lualatex -halt-on-error dfg-bib-highlights-example.tex
```

Each package has a minimal `dfg-<name>-example.tex` and a configured
`dfg-<name>-options-example.tex`. The latter shows alternate option combinations.
`dfg-plots-example.tex` demonstrates shared defaults for collaboration and
Gantt charts. The bibliography examples use their included companion data; the icon example uses standard TeX sample graphics.
The extracted `dfg-build-module-examples.py` helper builds the portable
examples in isolated directories. It needs Python 3, latexmk, a TeX engine,
and Biber. Preview cropping is optional when pdfcrop and Ghostscript are
available. The template's `make doc` builds and embeds these results.
`make test-modules` checks independent use with both LaTeX engines.

## Collaboration: projects, edges, and display selection

There are three different pieces of information:

1. **Project declarations** supply the available project IDs, areas, active
   state, and stored connections.
2. **`collaboration={...}`** replaces the focus project's undirected
   connections for one rendering. Incoming declarations are replaced too.
   `{}` deliberately means no connections. The plural `collaborations` is
   accepted as an alias.
3. **`show-projects={...}`** optionally restricts the projects displayed in
   that rendering. The focus is included automatically. It does not define extra edges.

Use the singular `collaboration` consistently for the plot type, declaration
key, and local connection override. `collaborations` remains a compatibility
alias in all three places. The old `projects` filter is an alias for
`show-projects`.

For a one-off figure without a registered dataset, the explicit connection
list supplies the other IDs, and the focus supplies its own ID:

```latex
\documentclass{article}
\usepackage{dfg-collaboration}
\begin{document}
\printPlot[arcs=true,collaboration={A01,A02}]
  {{collaboration}{Q01}}
\end{document}
```

This creates exactly three ID-only projects. Areas default to the first
character of each ID. For richer data and for projects that are not connected
to the focus, declare the complete dataset:

```latex
\DeclareCollaborationProject{Q01}{area=Services,collaboration={A01}}
\DeclareCollaborationProject{A01}{area=Research}
\DeclareCollaborationProject{A02}{area=Research,collaboration={Q01}}
\DeclareCollaborationProject{X01}{area=External,active=false}
\CollaborationSetup{area-colors={Services=orange,Research=blue}}

\printPlot[layout=heatmap]{{collaboration}{Q01}}
\printPlot[arcs=true,collaboration={A02}]
  {{collaboration}{Q01}}
```

No separate project list is needed for these calls. To display only a subset
of a larger declared dataset, use the optional display filter:

```latex
\printPlot[show-projects={A01,A02}]{{collaboration}{Q01}}
```

This displays A01, A02, and the focus Q01, with their stored connections.

Declarations replace a previous declaration with the same ID. They follow
TeX grouping. `\clearCollaborationProjects` starts an independent dataset.
IDs may contain letters, digits, and hyphens. Connections are undirected;
self-links and repeated edges are ignored. Declared inactive projects are
excluded. Unknown targets in a declared dataset produce a diagnostic rather
than silently adding a project. An inactive/unknown focus is an error.

In `dfg-crc.cls`, the adapter obtains the complete dataset from the `project`
database and preserves its current/ending/reference-only filters. The same
local `collaboration` and `show-projects` options then apply. The project
metadata also accepts `collaboration`, with `collaborations` retained as an
alias. Colours retain the existing `collaborationAreaColors`/`collaborationAreaPalette` settings.

## Shared and separate plot defaults

```latex
\dfgPlotSetup{
  plotOptions={floatPos=!t,capPos=bottom},
  ganttPlotOptions={caption={Shared additional Gantt caption.}},
  collaborationPlotOptions={arcs=true}
}
```

In the class, use the existing `\changeSettings` with these keys. In a
standalone document, `\changeSettings` is also supplied if that command is
not already defined by the host. Native `hvFloat` keys are forwarded after
plot-specific keys are consumed.

Precedence is built-in defaults, shared defaults, type defaults, then
per-call options. `caption` appends text to the automatic caption; an empty
per-call `caption={}` removes inherited additional text. The built-in
`proposalPlots` style selects `floatPos=!t,capPos=top,floatCapSep=8pt`.
Use `plotOptions={style=proposalPlots}` to select it. No hook is needed.
`\dfgPlotProject{ID}` sets the standalone default focus for omitted IDs.

When the class is loaded, direct package commands `\GanttPlotFigure` and
`\CollaborationPlot` read the same live shared/type-specific plot defaults as
`\printPlot`. Both `\changeSettings` and `\dfgPlotSetup` support grouped
overrides. The dataset still follows the command: class `\printPlot` reads
proposal metadata, while direct `\CollaborationPlot` reads the independently
declared collaboration dataset. `\GanttChart` renders only a graphic and
does not apply float options.

## Gantt charts and workpackages

```latex
\usepackage{dfg-gantt}
\GanttSetup{slots=12,first-quarter=1,year-labels={2027,2028,2029}}
% In the document:
\GanttProject{Study}
\begin{workpackages}
  \addWP{methods}{title={Methods},gantt={label={Set up},start=1,end=3}}
  Develop and validate the methods.
  \begin{workpackages}
    \addWP{validation}{gantt={label={Validation},start=2,end=4}}
    Describe the nested workpackage here.
  \end{workpackages}
  \addWP{analysis}{title={Analysis},gantt={start=4,end=12,style=striped}}
  Analyse the results.
\end{workpackages}

See \getWP{methods,validation,analysis}.

\printPlot{{gantt}{Study}}
```

Workpackage declarations provide both narrative headings and Gantt rows;
the data are not entered twice. Legacy `name`, `description`, `periodStart`,
`periodEnd`, and `style` fields remain accepted. Grouped `title`/`gantt` fields
take precedence over their legacy counterparts. Styles are `default`,
`alternative`, `important`, `crosshatch`, and `striped`.

For a chart without narrative workpackages, use
`\DeclareWorkPackage{Study}{methods}{title={Methods},gantt={start=1,end=3}}`.
Use `\GanttChart[slots=12,first-quarter=1]{Study}` for the graphic without a
float wrapper. `\GanttProject{Study}` also sets the default `\printPlot`
project. Use explicit IDs when switching between multiple projects.

The grid counts quarters. `first-quarter` must be 1--4 and `slots` positive;
`year-labels` supplies successive group titles. Defaults preserve the class's
16-quarter grid beginning in Q3. Equal start/end values omit a bar, as in the
existing class. Reversed/non-integer ranges are rejected. References need
the usual second LaTeX pass. The class retains its Cleveref references,
debug tags, metadata database, and fast-mode behavior through adapters.

Invalid grids are rejected in `\GanttSetup` and before chart geometry is
calculated, so `slots=0` reports a grid error rather than an arithmetic
failure. If compilation continues after that error, the grid recovers to
the default 16 slots beginning in Q3. Per-chart grid settings remain local.

## Timeline

```latex
\usepackage{dfg-timeline}
% In the document:
\addEvent{date=2027-03-12,category=progress,title={Progress meeting},
  description={Discuss the first results.}}
\addEvent{start date=2027-06-20,end date=2027-06-22,
  category=symposium,title={Research symposium}}
\printEventTimeline[width=\linewidth,rotation=45]
\printEventDetails[format=prose]
```

The existing month/day validation, date ranges, year filters, automatic and
manual label placement, category declarations, and aggregated descriptions
remain available. `\clearEvents` starts another collection. Declare new
categories with `\DeclareEventCategory{key}{label}{colour}{icon command}`.
The old `preamble/dfg-event-timeline.tex` path is a compatibility loader.

## Distribution charts

```latex
\usepackage{dfg-distribution}
\DeclareDistributionIcon{triangle}{%
  \fill[white](-.5,-.4)--(.5,-.4)--(0,.5)--cycle;}
\DeclareDistributionCategory{academic}{Academic}{blue}{triangle}
\distributionSetup{order={academic,industry},unit width=5mm}
% In the document:
\setDistribution{academic=4,industry=2}
\DistributionChart
```

Categories and vector icons are registered, not restricted to the defaults.
Counts are nonnegative integers; omitted registered categories become zero.
Data and geometry remain separate. Per-chart options are grouped.

## Registered paragraph icons

```latex
\usepackage{dfg-icons}
\DeclareIcon{my-service}{
  square={assets/service-square.pdf},
  vertical={assets/service-vertical.pdf},
  aliases={service}
}
\DeclareIcon{partner}{file={assets/partner-logo.png}}
% In the document:
\getIcon[height=3,gap=.8em]{service,partner}
Paragraph text wraps alongside the registered graphics.
```

The package contains no whitelist of icon names or proposal-specific assets.
`\DeclareIcon` registers exact names and files in property lists. A single
`file` serves both shapes; one supplied variant also acts as the fallback
for the other. Registration also records filename aliases, including SVG
source-name aliases for registered PDFs. Graphic options are forwarded to
`graphicx`. `\IconIfRegisteredTF{name}{yes}{no}` checks registration.
The proposal's existing assets are declared in `preamble/dfg-icons.tex`.

Registering an existing icon name replaces its files and complete alias list;
old aliases are removed. Registrations are global, including inside a TeX
group. Names are exact and case-sensitive; surrounding spaces are ignored.
A blank name or a registration without an asset is an error.

Explicit names and aliases take precedence over automatic filename aliases.
An explicit alias already owned by another icon is an error; the rejected
declaration leaves the registry unchanged. For ambiguous automatic filename
aliases, the first registration wins. Use an explicit alias or the full
registered file path to disambiguate assets with identical basenames.

## Bibliography highlighting

```latex
\usepackage[backend=biber,style=numeric]{biblatex}
\usepackage{dfg-bib-highlights}
\addbibresource{references.bib}
\addboldnames{{Doe, Jane},{Smith, John}}
\BibHighlightSetup{emphasizeAuthors=true,emphasizeEntries=true,
  keyword=important,color=black}
% In the document:
\printbibliography
```

Entries whose `keywords` contain `important` are completely bold. Author
emphasis independently matches names through Biber hashes; brace names that
contain commas and declare aliases in the same way as the current class.
`\resetboldnames` clears the active hash registry.
`\printHighlightedBibliography[heading=none]{another-keyword}` selects a
keyword for one list. Ordinary BibLaTeX filters/styles continue to apply.

The package creates `\jobname-boldAuthors.bib` beside the job by default.
Run LaTeX, Biber, then LaTeX twice. The class supplies its existing auxiliary
file location, switches, name colour, and project/frame highlight keywords.
With package option `noauthors`, the auxiliary hash backend is disabled and
the author registration commands remain harmless no-ops.

## Thumbindex

```latex
\documentclass[twoside]{article}
\usepackage{dfg-thumbindex}
\pagestyle{scrheadings}
\ThumbIndexSetup{pattern=6,width=10mm,topmargin=20mm,bottommargin=20mm,
  orientation=outwards,bg=blue,fg=white}
\begin{document}
\printThumbIndex{Introduction}
Text on this and the following pages.
\clearpage
\printThumbIndex[bg=red]{Methods}
More text.
\end{document}
```

The package handles outer edges, facing-page rotation, slot wrapping, and
physical page offsets. `topmargin=auto,bottommargin=auto` follows the live
text block. `\printThumbIndexOff` removes tabs from the running heads;
`\resetThumbIndex` restarts the slot sequence. The class continues to expose
its existing `thumbindex` customization keys and shares the live settings.

<!-- BEGIN COMPLETE MODULE OPTIONS -->
## Complete option reference

These are standalone defaults. Use command options rather than package-load
options, except for `noauthors` on `dfg-bib-highlights`. Boolean keys accept
`true`/`false`; a bare boolean key means `true`, with inverse aliases noted.

### `dfg-plots`

`\dfgPlotSetup{options}`

Set shared and type-specific defaults; their precedence is described below.

`\dfgPlotProject{ID}`

Select the default focus for plots whose specification omits an ID.

`\dfgDeclarePlotType{name}{renderer}`

Register a plot renderer globally. It receives an optional options argument and a mandatory project ID.

`\printPlot[options]{plot specification}`

Render a registered plot type, for example {{gantt}{Study}}. A missing ID uses the current default focus.

#### Shared and type-specific setup

Pass these keys to \dfgPlotSetup; standalone \changeSettings is an alias when the host has not defined it. Changes follow TeX grouping. Each renderer consumes its own keys and forwards remaining keys to hvFloat.

##### `plotOptions`

Shared options for both plot types, including native float keys. Replaces the previous shared list.
Accepts Key-value list. Initially `{}`.

##### `ganttPlotOptions`

Additional Gantt-only defaults. Overrides shared values and is overridden by the individual call.
Accepts Key-value list. Initially `{}`.

##### `collaborationPlotOptions`

Additional collaboration-only defaults, including layout, connection overrides, and float placement. An empty list clears earlier type defaults.
Accepts Key-value list. Initially `{}`.

#### Native float options and extension commands

Both floating plot wrappers accept native hvFloat keys in the same option list. The complete backend reference is available with texdoc hvfloat. This includes placement, caption position, rotation, non-floating output, and named styles; the package does not introduce a separate whitelist.

##### `floatPos`

The wrapper defaults to source/bottom placement. A later style or explicit call can override it.
Accepts Native hvFloat placement value. Initially `!hb`.

##### `capPos`

The wrapper places captions below by default; for example top changes their position.
Accepts Native hvFloat caption position. Initially `bottom`.

##### `style`

The supplied proposalPlots style sets floatPos=!t, capPos=top, floatCapSep=8pt. Native styles and remaining keys retain hvFloat semantics.
Accepts An hvFloat style name. Initially `No named style selected`.

#### Command arguments and customization hooks

\dfgPlotProject{ID} changes the default focus in its TeX group. \dfgDeclarePlotType{name}{renderer} globally registers an exact type name; its renderer is called with [options]{project}. Built-in type aliases are gantt/Gantt and collaboration/collaborations/ProjectCollaboration. Explicit IDs override the default only for that rendering. Packages other than bib-highlights have no package-load options; pass their settings to the setup/render commands.

### `dfg-collaboration`

`\DeclareCollaborationProject{ID}{fields}`

Declare or replace project data in the current group.

`\CollaborationSetup{options}`

Set persistent area-colour defaults in the current group.

`\CollaborationPlot[options]{ID}`

Render the independent project registry, with optional per-call connection and display overrides.

`\clearCollaborationProjects`

Clear the independent project registry in the current group.

#### Project declarations

Options for \DeclareCollaborationProject{ID}{options}. Each declaration replaces that ID in the current TeX group. IDs contain letters, digits, and hyphens and start with a letter or digit.

##### `area`

Groups projects and selects their area colour; it need not match the ID prefix.
Accepts Area name. Initially `First character of ID`.

##### `collaboration`

Stored undirected connections. Duplicate and self-links are ignored; reverse declarations need not be repeated.
Accepts Comma-separated project IDs. Initially `{}`.

##### `collaborations`

Compatibility alias for the singular declaration key.
Accepts Same as collaboration. Initially `{}`.

##### `active`

False omits this project and incident edges from plots.
Accepts true or false. Initially `true`.

#### Area setup

Options for \CollaborationSetup; follow TeX grouping. Per-plot area options override these defaults. With the class loaded this setup also updates its area-colour settings.

##### `area-colors`

Explicit area colours. Local plots merge individual mappings with the setup mappings.
Accepts Area=colour pairs. Initially `{}`.

##### `area-palette`

Rotating fallback palette for areas without an explicit colour.
Accepts Nonempty colour list. Initially `blue!70!black, teal!80!black, orange!85!black, violet, brown`.

#### Per-plot options

Options for \CollaborationPlot or the collaboration type of \printPlot. Each rendering resets built-in defaults, then applies shared, type-specific, and local options. Float keys also pass through to hvFloat.

##### `layout`

Selects the visual layout. arc-diagram is a value alias for arc.
Accepts arc, arc-diagram, or heatmap. Initially `arc`.

##### `arc`

Shorthand for layout=arc.
Accepts Bare key. Initially `Not selected separately`.

##### `arc-diagram`

Shorthand for layout=arc.
Accepts Bare key. Initially `Not selected separately`.

##### `heatmap`

Shorthand for layout=heatmap.
Accepts Bare key. Initially `Not selected separately`.

##### `arcs`

Draws connecting arcs in the arc layout.
Accepts true or false; bare key means true. Initially `false`.

##### `no-arcs`

Shorthand for arcs=false.
Accepts Bare key. Initially `Not selected separately`.

##### `area-colors`

Overrides or adds individual area colours for this rendering.
Accepts Area=colour pairs. Initially `Setup mappings`.

##### `area-colours`

British-spelling alias.
Accepts Same as area-colors. Initially `Setup mappings`.

##### `area-palette`

Replaces the fallback palette for this call. An empty per-call list leaves the palette unchanged.
Accepts Colour list. Initially `Setup palette`.

##### `caption`

Appends text to the automatic caption. An empty value clears inherited additional caption text.
Accepts TeX text. Initially `{}`.

##### `collaboration`

Replaces all edges incident to the focus for this rendering, including incoming edges. With no dataset, supplies the other one-off node IDs.
Accepts Comma-separated IDs; {} allowed. Initially `Stored connections`.

##### `collaborations`

Compatibility alias for the local connection override.
Accepts Same as collaboration. Initially `Stored connections`.

##### `show-projects`

Filters displayed nodes. The focus is always included; an empty list shows only the focus.
Accepts Comma-separated IDs; {} allowed. Initially `All active projects`.

##### `projects`

Compatibility alias for the display filter; it does not define connections.
Accepts Same as show-projects. Initially `All active projects`.

##### `width`

Requested plot width; layout measurement uses this width.
Accepts TeX dimension. Initially `\linewidth`.

#### Command arguments and customization hooks

\CollaborationPlot[options]{ID} uses the independent registry. \clearCollaborationProjects clears that registry in the current group. The class adds \ProjectCollaborationPlot, \collaborationPlot and its plural alias; its \printPlot reads class metadata. Node IDs are not arbitrary TeX labels. Edges between filtered or inactive nodes are not shown.

### `dfg-gantt`

`\GanttSetup{options}`

Set the quarter grid defaults in the current group.

`\GanttProject{ID}`

Select the project for narrative workpackages and the default plot focus.

`\addWP{ID}{fields}`

Add a narrative item inside workpackages, with the same data supplying its Gantt row.

`\DeclareWorkPackage{project}{ID}{fields}`

Declare a chart row without a narrative list item.

`\getWP[project]{IDs}`

Reference one or more narrative workpackages. The optional project replaces the current project for this call.

`\GanttChart[options]{project}`

Draw a graphic only, without the float wrapper.

`\GanttPlotFigure[options]{project}`

Draw a chart with automatic caption and native hvFloat options.

#### Narrative workpackage fields

Fields for \addWP{ID}{fields} and \DeclareWorkPackage{project}{ID}{fields}. Set a project before narrative declarations with \GanttProject. Grouped title/gantt fields take precedence over corresponding legacy fields.

##### `title`

Narrative heading; normalizes to name. It also supplies the chart description when no chart label/description was given.
Accepts TeX text. Initially `{}`.

##### `gantt`

Sets the workpackage chart fields without entering a second dataset.
Accepts Nested label, start, end, style keys. Initially `No grouped chart fields`.

##### `id`

Accepted by normalization for compatibility; standalone storage uses the mandatory command ID and ignores this field. Prefer the mandatory argument.
Accepts Legacy ID field. Initially `Mandatory command argument`.

##### `name`

Legacy narrative heading. title overrides it.
Accepts TeX text. Initially `{}`.

##### `description`

Legacy chart label. gantt/label overrides it.
Accepts TeX text. Initially `{}; falls back to title/name in grouped syntax`.

##### `periodStart`

Legacy first chart slot. gantt/start overrides it.
Accepts Nonnegative integer. Initially `1`.

##### `periodEnd`

Legacy final chart slot. gantt/end overrides it. Equal endpoints omit the bar.
Accepts Nonnegative integer, at least start. Initially `1`.

##### `style`

Legacy bar appearance. gantt/style overrides it.
Accepts default, alternative, important, crosshatch, striped. Initially `default`.

#### Nested gantt fields

Use inside gantt={...} in a workpackage declaration. Start/end are chart-slot indices, not calendar dates.

##### `label`

Label printed inside the bar.
Accepts TeX text. Initially `Workpackage title/name when present`.

##### `start`

First slot. A value greater than end is an error.
Accepts Nonnegative integer. Initially `1`.

##### `end`

Last slot. Equal start/end values omit the bar.
Accepts Nonnegative integer. Initially `1`.

##### `style`

Solid default/alternative/important colours, a crosshatch pattern, or alternating stripes.
Accepts default, alternative, important, crosshatch, striped. Initially `default`.

#### Grid setup and individual charts

Use \GanttSetup for grouped persistent defaults, \GanttChart for a graphic, or the standalone Gantt plot wrapper for a floating graphic. The standalone wrapper also consumes caption and forwards remaining float keys to hvFloat. The class retains its own plot adapter.

##### `slots`

Number of quarter slots. Validated before geometry calculations.
Accepts Positive integer. Initially `16`.

##### `first-quarter`

First quarter label. Subsequent labels cycle Q1 to Q4.
Accepts Integer 1 to 4. Initially `3`.

##### `year-labels`

Successive year-group titles. Missing labels use the funding-year formatter, whose standalone default is Year followed by the group number.
Accepts Comma-separated TeX labels. Initially `{}`.

##### `caption`

Appends to the automatic Gantt caption. An empty value clears inherited additional text; it is not a graphic-only GanttChart option.
Accepts TeX text; floating wrapper only. Initially `{}`.

#### Command arguments and customization hooks

\GanttProject{ID} selects the workpackage project and generic plot focus. \getWP[project]{IDs} references workpackages, with the optional project replacing the current one for that call. \GanttPlotFigure[options]{ID} wraps a chart in hvFloat. \GanttChart and legacy \dfgGanttEnvironment render graphics only. \dfgGanttContent renders stored rows, and \DFGGanttTitles renders grid headings inside pgfgantt. Standalone formatter hooks are \dfgFundingYear{number}, \DFGGanttLabel{project}{id}, \DFGGanttTag{project}{field}{text}{tag}, and \dfgGanttShowQs{quarter}{slot}. The class supplies its own reference/debug formatters. Gantt colours can be redefined through the xcolor names tableHeadingsBG, tableHeadingsFont, tableOuterLines, color@gantt@frame, color@gantt@default, color@gantt@alternative, color@gantt@important, color@gantt@crosshatch, color@gantt@stripe-one, color@gantt@stripe-two.

### `dfg-timeline`

`\addEvent[formatting]{data}`

Register one dated event. Formatting can be overridden when rendering.

`\printEventTimeline[options]`

Render the selected events as a horizontal timeline.

`\printEventDetails[options]`

Render the same event data as individual or aggregated details.

`\DeclareEventCategory{key}{label}{colour}{icon}`

Register or replace a global category.

`\clearEvents`

Clear event data and stored formatting, preserving categories.

#### Event data

Mandatory data argument of \addEvent[formatting]{data}. Events and clearEvents follow TeX grouping; category registrations are global. The optional formatting argument is documented separately below.

##### `id`

Stable key for later per-render overrides. Duplicate IDs warn and retain the first event.
Accepts Unique ID. Initially `Automatically generated event-N`.

##### `date`

Point date, or beginning of a date range. Month-only dates are positioned mid-month; days and leap years are validated.
Accepts YYYY-MM or YYYY-MM-DD. Initially `Required`.

##### `start date`

Alias for the start date. If both forms are given, the later assignment wins.
Accepts Same as date. Initially `Required when date is absent`.

##### `end date`

End of a range, not before its beginning.
Accepts YYYY-MM or YYYY-MM-DD. Initially `Start date`.

##### `category`

Selects colour, legend label, and default icon. Built-ins are retreat, progress, networking, graduate, symposium.
Accepts Registered category key. Initially `Required`.

##### `title`

Full event title and details heading.
Accepts TeX text. Initially `Required nonempty text`.

##### `label`

Short chart label when labels=label.
Accepts TeX text. Initially `Title`.

##### `abbreviation`

Used when labels=abbreviation and a value is supplied.
Accepts TeX text. Initially `Falls back to label/title`.

##### `summary`

Optional second line in the chart when summary=true; also available to aggregated detail rendering.
Accepts Short TeX text. Initially `{}`.

##### `description`

Long details text; kept separate from the chart summary.
Accepts TeX text. Initially `{}`.

##### `icon`

Overrides the category icon for this event.
Accepts TeX icon command. Initially `Category icon`.

#### Timeline rendering

Options for \printEventTimeline. Each call resets the following defaults; changes are local to that rendering. Labels occupy lanes above the axis; date labels use independent lanes below it.

##### `width`

Total requested width including label fitting. Insufficient width produces a diagnostic.
Accepts Positive dimension. Initially `\linewidth`.

##### `year`

Filters to events intersecting that year; a range can intersect several years.
Accepts all or four-digit year. Initially `all`.

##### `rotation`

Upper event-label angle.
Accepts Angle in degrees. Initially `30`.

##### `date rotation`

Auto follows the effective event-label angle unless independently overridden.
Accepts auto or angle in degrees. Initially `auto`.

##### `labels`

Selects the event text, with the fallbacks documented above.
Accepts title, label, abbreviation. Initially `label`.

##### `summary`

Adds a nonempty summary below the chart label.
Accepts true or false. Initially `false`.

##### `icons`

Displays the event icons.
Accepts true or false. Initially `true`.

##### `legend`

Shows the categories used by the selected events.
Accepts true or false. Initially `true`.

##### `show labels`

Displays upper label text; icons can remain visible independently.
Accepts true or false. Initially `true`.

##### `show dates`

Displays date or date-range labels below the axis.
Accepts true or false. Initially `true`.

##### `label width`

Zero uses natural text width; positive values constrain/wrap label text.
Accepts Nonnegative dimension. Initially `0pt`.

##### `label distance`

Distance from the axis to the first upper label lane.
Accepts Nonnegative dimension. Initially `1.8mm`.

##### `lane`

Default upper lane request. Lane numbering begins at zero; auto avoids collisions.
Accepts auto or nonnegative integer. Initially `auto`.

##### `lane spacing`

Auto uses measured upper-label height plus gap.
Accepts auto or positive dimension. Initially `auto`.

##### `date lane`

Default date-label lane request, independent of upper lanes.
Accepts auto or nonnegative integer. Initially `auto`.

##### `date distance`

Distance from the axis to the first lower date lane.
Accepts Nonnegative dimension. Initially `1.8mm`.

##### `date lane spacing`

Auto uses measured date-label height plus gap.
Accepts auto or positive dimension. Initially `auto`.

##### `gap`

Collision/automatic-lane gap.
Accepts Nonnegative dimension. Initially `.8mm`.

##### `font`

Upper-label font.
Accepts TeX font commands. Initially `\sffamily\fontsize{7.4}{9}\selectfont`.

##### `date font`

Date-label font.
Accepts TeX font commands. Initially `\sffamily\fontsize{6.5}{8}\selectfont`.

##### `line color`

Main timeline axis colour.
Accepts xcolor colour expression. Initially `EventMuted!40`.

##### `line width`

Main axis stroke.
Accepts Nonnegative dimension. Initially `.6pt`.

##### `connector width`

Upper-label connector stroke.
Accepts Nonnegative dimension. Initially `.35pt`.

##### `date connector width`

Date-label connector stroke.
Accepts Nonnegative dimension. Initially `.3pt`.

##### `range width`

Date-range segment stroke.
Accepts Nonnegative dimension. Initially `1.2pt`.

##### `dot radius`

Radius of event dots.
Accepts Nonnegative dimension. Initially `.9mm`.

##### `events`

Overrides specific registered event IDs for this rendering. These overrides take precedence over stored optional addEvent formatting.
Accepts ID={formatting keys} pairs. Initially `{}`.

#### Per-event formatting

Use in the optional argument of \addEvent or under events={id={...}} in \printEventTimeline. Values inherit the timeline settings unless listed otherwise. Local events overrides win over stored formatting.

##### `lane`

Upper-label lane for this event.
Accepts auto or nonnegative integer. Initially `Timeline lane`.

##### `xshift`

Horizontal upper-label shift; does not change the event date.
Accepts Signed dimension. Initially `0pt`.

##### `yshift`

Vertical upper-label shift.
Accepts Signed dimension. Initially `0pt`.

##### `rotation`

Event label/icon angle. When show labels=false, upper icons remain upright.
Accepts Angle in degrees. Initially `Timeline rotation`.

##### `date rotation`

Independent date-label rotation. Auto follows the effective per-event label rotation.
Accepts auto or angle. Initially `Timeline date rotation`.

##### `date direction`

Chooses which end/digit of the date label aligns with its connector.
Accepts left or right. Initially `left`.

##### `label width`

Per-event text wrapping width.
Accepts Nonnegative dimension. Initially `Timeline label width`.

##### `label`

Overrides the rendered short label.
Accepts TeX text. Initially `Selected event label`.

##### `icon`

Overrides the rendered icon.
Accepts TeX icon command. Initially `Event/category icon`.

##### `font`

Per-event upper-label font.
Accepts TeX font commands. Initially `Timeline upper font`.

##### `date lane`

Per-event lower date lane.
Accepts auto or nonnegative integer. Initially `Timeline date lane`.

##### `date xshift`

Horizontal date-label shift.
Accepts Signed dimension. Initially `0pt`.

##### `date yshift`

Vertical date-label shift.
Accepts Signed dimension. Initially `0pt`.

##### `node options`

Additional upper-label node styling. These are TikZ options, not timeline keys.
Accepts TikZ node options. Initially `{}`.

#### Event details

Options for \printEventDetails. Every call resets the listed defaults. Aggregated rendering groups selected events by category; category override text is applied in that aggregated mode.

##### `format`

Description-list layout or continuous prose.
Accepts list or prose. Initially `list`.

##### `year`

Same intersection filter as the chart.
Accepts all or four-digit year. Initially `all`.

##### `icons`

Shows icons in detail headings/prose.
Accepts true or false. Initially `true`.

##### `show dates`

Shows event dates or collected dates.
Accepts true or false. Initially `true`.

##### `nodate`

Inverse alias: nodate=true means show dates=false.
Accepts true or false; bare means true. Initially `false`.

##### `aggregated`

Combines events by category and common text rather than printing each event separately.
Accepts true or false. Initially `false`.

##### `categories`

Overrides aggregate category headings/descriptions; it is not a category-selection filter.
Accepts Category={title=...,description=...} pairs. Initially `{}`.

#### Aggregate category overrides

Nested keys under categories={category={...}} for \printEventDetails. The category must already be registered.

##### `title`

Replaces the aggregate heading for this category.
Accepts TeX text. Initially `Registered/generated category heading`.

##### `description`

Replaces the aggregate category description.
Accepts TeX text. Initially `Automatically combined event text`.

#### Command arguments and customization hooks

\DeclareEventCategory{key}{label}{colour}{icon} registers or replaces a global category. \EventCategoryIcon{key} prints its coloured icon. Built-ins are retreat (Annual retreat, EventRetreat, users), progress (Progress day, EventProgress, comments), networking (Networking, EventNetworking, handshake), graduate (Graduate school retreat, EventGraduate, graduation cap), and symposium (International symposium, EventSymposium, globe). Redefine the EventRetreat, EventProgress, EventNetworking, EventGraduate, EventSymposium, EventInk, EventMuted, EventTalk, or EventMisc xcolor names to customize their colours. \clearEvents clears event data and stored formatting, preserving categories. There is no persistent timeline setup command: rendering settings reset on every call.

### `dfg-distribution`

`\DeclareDistributionIcon{name}{TikZ code}`

Register a normalized vector icon.

`\DeclareDistributionCategory{key}{label}{colour}{icon}`

Register a category using an existing icon.

`\distributionSetup{options}`

Set geometry and row-order defaults.

`\setDistribution{counts}`

Replace category counts; omitted registered categories become zero.

`\DistributionChart[options]`

Render the current dataset with optional local geometry settings.

#### Chart geometry, labels, and order

Use \distributionSetup for defaults or \DistributionChart[options] for a single grouped chart. Registered categories initially are postdoc, industry, other, with cap, factory, bulb icons. The additional none icon draws no symbol.

##### `unit width`

Width of one count segment.
Accepts Dimension. Initially `7.5mm`.

##### `bar height`

Height of each bar.
Accepts Dimension. Initially `7.8mm`.

##### `row spacing`

Distance between row centres.
Accepts Dimension. Initially `10mm`.

##### `label x`

Horizontal icon/label anchor relative to the axis.
Accepts Signed dimension. Initially `-8mm`.

##### `label width`

Text width of the category label.
Accepts Dimension. Initially `15mm`.

##### `label drop`

Downward text offset when label position=below.
Accepts Dimension. Initially `4.8mm`.

##### `label position`

Category text to the left of the icon, or below it.
Accepts left or below. Initially `left`.

##### `label gap`

Gap between left-positioned label and icon.
Accepts Dimension. Initially `2mm`.

##### `icon radius`

Radius of the category icon background.
Accepts Dimension. Initially `3.4mm`.

##### `icon raise`

Auto is 0pt for left labels and 2.3mm for below labels.
Accepts auto or signed dimension. Initially `auto`.

##### `value gap`

Gap from the end of a bar to its numeric count.
Accepts Dimension. Initially `3mm`.

##### `axis padding`

Axis extension beyond the first and last bars.
Accepts Dimension. Initially `2mm`.

##### `axis width`

Axis stroke width.
Accepts Dimension. Initially `.45pt`.

##### `axis dot radius`

Radius of the dots at the axis ends.
Accepts Dimension. Initially `.4mm`.

##### `separator width`

White strokes between count segments.
Accepts Dimension. Initially `.4pt`.

##### `text color`

Category and count text colour.
Accepts xcolor colour expression. Initially `DistributionText`.

##### `axis color`

Axis and endpoint-dot colour.
Accepts xcolor colour expression. Initially `DistributionAxis`.

##### `label font`

Category-label font.
Accepts TeX font commands. Initially `\sffamily\bfseries\fontsize{8.8}{10}\selectfont`.

##### `value font`

Numeric-count font.
Accepts TeX font commands. Initially `\sffamily\bfseries\fontsize{11}{12}\selectfont`.

##### `order`

Selects and orders displayed rows. Unknown or repeated categories are errors.
Accepts Nonempty list of distinct registered categories. Initially `postdoc, industry, other; new categories append`.

#### Command arguments and customization hooks

\DeclareDistributionIcon{name}{TikZ code} declares a normalized vector symbol; cap, factory, bulb, and none are built in. \DeclareDistributionCategory{key}{label}{colour}{icon} adds or replaces a category; its icon must exist. \setDistribution{category=count,...} replaces counts, treating omitted registered categories as zero. Negative/non-integer counts, unknown categories, and duplicates are errors; rejected data leave the last valid counts intact. \DistributionChart[options] renders the current dataset. Colour hooks are DistributionPostdoc, DistributionIndustry, DistributionOther, DistributionText, and DistributionAxis. The stock geometry has no sign/range validation; use sensible positive sizes for bars and spacing.

### `dfg-icons`

`\DeclareIcon{name}{assets}`

Globally register graphic variants and explicit aliases.

`\getIcon[options]{names}`

Place registered icons side by side next to the following paragraph.

`\IconIfRegisteredTF{name}{yes}{no}`

Test registration of a name or alias after trimming spaces.

#### Icon registration

Options for \DeclareIcon{name}{options}. Names and aliases are registered globally. At least one asset is needed; redeclaration replaces the complete alias list.

##### `file`

Default asset for both shapes unless a variant is supplied.
Accepts Graphics filename/path. Initially `{}`.

##### `square`

Square-shape asset.
Accepts Graphics filename/path. Initially `file or supplied vertical variant`.

##### `vertical`

Portrait-shape asset.
Accepts Graphics filename/path. Initially `file or supplied square variant`.

##### `aliases`

Additional explicit names. Conflicts with another icon are errors and leave the registry unchanged. Filename, basename, and PDF-to-SVG aliases are also registered automatically, without overriding explicit names.
Accepts Comma-separated exact names. Initially `{}`.

#### Paragraph icon placement

Options for \getIcon[options]{comma-separated names}. All placement options reset per call. Remaining options are forwarded to graphicx includegraphics for every image; see texdoc graphics for its complete backend reference.

##### `shape`

Selects the registered variant, with the registration fallback rules.
Accepts square or vertical. Initially `square`.

##### `square`

Shorthand for shape=square.
Accepts Bare key; no value. Initially `Not selected separately`.

##### `vertical`

Shorthand for shape=vertical.
Accepts Bare key; no value. Initially `Not selected separately`.

##### `gap`

Spacing between grouped images and between the image group and paragraph text.
Accepts Dimension. Initially `.6em`.

##### `height`

Reserved paragraph lines. Total image height is capital-H height plus (height-1) baselines. This computed totalheight is applied after forwarded graphicx keys.
Accepts Positive integer. Initially `4 lines for square; 5 for vertical`.

#### Command arguments and customization hooks

\IconIfRegisteredTF{name}{yes}{no} tests a registered name or alias after trimming spaces. Missing graphics files produce a warning and example-image fallback at rendering time, rather than failing registration. Graphics lookup follows graphicspath and driver extension order. The computed totalheight is appended after forwarded graphicx options, so it controls the final icon height; width, trim, clip, page, and angle retain graphicx semantics.

### `dfg-bib-highlights`

`\BibHighlightSetup{options}`

Set independent author and entry highlighting options.

`\addboldnames{names}`

Register selected authors; brace names containing commas.

`\resetboldnames`

Clear the active author-hash registry.

`\printHighlightedBibliography[bibliography options]{keyword}`

Select the highlight keyword locally and forward list options to BibLaTeX. This does not filter the list by keyword.

#### Package loading

Only noauthors is a load-time package option. Load biblatex first to choose its backend/style. Setup options below are passed to BibHighlightSetup, not to usepackage.

##### `noauthors`

Disables creation/registration of the auxiliary author-hash bibliography. Author registration/reset commands become no-ops. Whole-entry highlighting remains available.
Accepts Bare load-time option. Initially `Not selected: hash backend enabled`.

#### Highlight setup

Options for \BibHighlightSetup. Settings follow TeX grouping. The class connects the two switches and author colour to its own live customization.

##### `emphasizeAuthors`

Turns matching-author bold/colour emphasis on or off independently of whole-entry emphasis.
Accepts true or false. Initially `true`.

##### `emphasizeEntries`

Enables bold type for entries carrying the selected keyword.
Accepts true or false. Initially `true`.

##### `keyword`

Selects entries for complete bold type. printHighlightedBibliography supplies a local keyword for one list; it does not filter out other entries.
Accepts BibLaTeX keyword. Initially `{}; no whole-entry keyword selected`.

##### `color`

Colour of matching author names; does not recolour the entire entry.
Accepts xcolor colour expression. Initially `black`.

#### Command arguments and customization hooks

\addboldnames{{Family, Given},...} registers names through Biber hashes. \resetboldnames clears the active hash registry. Declare \DFGBoldNamesFile before loading the package to change the auxiliary .bib path; the default is \jobname-boldAuthors.bib and its directory must exist. \printHighlightedBibliography[options]{keyword} uses the keyword locally and forwards all bracketed options to BibLaTeX printbibliography (see texdoc biblatex); it does not add a keyword filter. Advanced adapter hooks are \DFGBibIfAuthorsTF{yes}{no}, \DFGBibIfEntriesTF{yes}{no}, and expandable \DFGBibNameColor. Match-name aliases must be registered explicitly with addboldnames.

### `dfg-thumbindex`

`\ThumbIndexSetup{options}`

Set live tab geometry, appearance, and orientation.

`\printThumbIndex[colours]{label}`

Advance to the next slot and install a tab in normal and plain running heads.

`\printThumbIndexOff`

Remove installed tab heads without resetting the slot counter.

`\resetThumbIndex`

Reset the slot counter without removing the current tab.

#### Live thumbindex setup

Options for \ThumbIndexSetup; follow TeX grouping and share the class live state when used with dfg-crc. Defaults here describe an ordinary standalone document. Activate a scrlayer-scrpage page style to use the running heads.

##### `enabled`

Controls whether printThumbIndex installs a new tab. Turning this false does not remove a tab already installed; use printThumbIndexOff for that.
Accepts true or false. Initially `true`.

##### `pattern`

Number of vertical slots before wrapping to the first slot.
Accepts Positive integer. Initially `8`.

##### `width`

Nominal tab width; edge overhang is handled internally.
Accepts Dimension. Initially `12mm`.

##### `font`

Tab-label font.
Accepts TeX font commands. Initially `\sffamily\bfseries`.

##### `bg`

Default background for subsequent printThumbIndex calls.
Accepts xcolor colour expression. Initially `black`.

##### `fg`

Default tab text colour.
Accepts xcolor colour expression. Initially `white`.

##### `orientation`

Inwards adds 180 degrees to the odd/even outward rotations.
Accepts outwards or inwards. Initially `outwards`.

##### `topmargin`

Physical distance from the page top; auto follows the live text block.
Accepts auto or dimension. Initially `auto`.

##### `bottommargin`

Physical distance from the page bottom; auto follows the live text block. The remaining height is divided into pattern equal slots.
Accepts auto or dimension. Initially `auto`.

#### Individual tabs

Options for \printThumbIndex[options]{label}. Each call begins from the current setup colours and installs the selected tab on subsequent normal/plain pages until another call or printThumbIndexOff. A bare colour without an equals sign is background shorthand.

##### `bg`

Background override for this tab; does not change the setup default.
Accepts xcolor colour expression. Initially `Current setup background`.

##### `fg`

Text-colour override for this tab; does not change the setup default.
Accepts xcolor colour expression. Initially `Current setup foreground`.

#### Command arguments and customization hooks

\printThumbIndexOff removes installed tab heads without resetting the slot counter. \resetThumbIndex resets the counter without removing a displayed tab. Lower-level \evenpageletterthumb{label} and \oddpageletterthumb{label} draw the left/right edge tab. Normal and plain heads are both installed by printThumbIndex. Width and explicit margins are dimension inputs without additional sign validation; margins must leave room on the page. Standalone defaults apply here; class defaults may differ and are read live.

<!-- END COMPLETE MODULE OPTIONS -->

## Other candidates

The guest-speaker dashboard and publication-network renderer are the next
small modules to consider. The latter also needs its Lua backend and a clear
publication-data contract. Facing-page figures remain a prototype requiring
more page-layout verification. CV sections, funding tables, leadership
statistics, and metadata references could also be extracted, but require a
larger, explicit metadata interface. They remain outside this extraction.

## Verification

`python3 __admin/scripts/test_standalone_modules.py -v` compiles isolated
standard documents with both engines, including a real Biber cycle. Existing
plot, icon, timeline, and CV regressions check compatibility with the class.
Set `MODULE_TEST_ARTIFACTS` to retain the isolated jobs for visual inspection.

%</modules-guide>
%<*module-option-catalog>
{
  "plots": [
    {
      "title": "Shared and type-specific setup",
      "families": [
        "dfgplots/setup"
      ],
      "scope": "Pass these keys to \\dfgPlotSetup; standalone \\changeSettings is an alias when the host has not defined it. Changes follow TeX grouping. Each renderer consumes its own keys and forwards remaining keys to hvFloat.",
      "options": [
        {
          "name": "plotOptions",
          "default": "{}",
          "values": "Key-value list",
          "effect": "Shared options for both plot types, including native float keys. Replaces the previous shared list."
        },
        {
          "name": "ganttPlotOptions",
          "default": "{}",
          "values": "Key-value list",
          "effect": "Additional Gantt-only defaults. Overrides shared values and is overridden by the individual call."
        },
        {
          "name": "collaborationPlotOptions",
          "default": "{}",
          "values": "Key-value list",
          "effect": "Additional collaboration-only defaults, including layout, connection overrides, and float placement. An empty list clears earlier type defaults."
        }
      ],
      "commands": [
        {
          "name": "dfgPlotSetup",
          "signature": "\\marg{options}",
          "description": "Set shared and type-specific defaults; their precedence is described below."
        },
        {
          "name": "dfgPlotProject",
          "signature": "\\marg{ID}",
          "description": "Select the default focus for plots whose specification omits an ID."
        },
        {
          "name": "dfgDeclarePlotType",
          "signature": "\\marg{name}\\marg{renderer}",
          "description": "Register a plot renderer globally. It receives an optional options argument and a mandatory project ID."
        },
        {
          "name": "printPlot",
          "signature": "\\oarg{options}\\marg{plot specification}",
          "description": "Render a registered plot type, for example {{gantt}{Study}}. A missing ID uses the current default focus."
        }
      ]
    },
    {
      "title": "Native float options and extension commands",
      "families": [],
      "scope": "Both floating plot wrappers accept native hvFloat keys in the same option list. The complete backend reference is available with texdoc hvfloat. This includes placement, caption position, rotation, non-floating output, and named styles; the package does not introduce a separate whitelist.",
      "options": [
        {
          "name": "floatPos",
          "default": "!hb",
          "values": "Native hvFloat placement value",
          "effect": "The wrapper defaults to source/bottom placement. A later style or explicit call can override it."
        },
        {
          "name": "capPos",
          "default": "bottom",
          "values": "Native hvFloat caption position",
          "effect": "The wrapper places captions below by default; for example top changes their position."
        },
        {
          "name": "style",
          "default": "No named style selected",
          "values": "An hvFloat style name",
          "effect": "The supplied proposalPlots style sets floatPos=!t, capPos=top, floatCapSep=8pt. Native styles and remaining keys retain hvFloat semantics."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\dfgPlotProject{ID} changes the default focus in its TeX group. \\dfgDeclarePlotType{name}{renderer} globally registers an exact type name; its renderer is called with [options]{project}. Built-in type aliases are gantt/Gantt and collaboration/collaborations/ProjectCollaboration. Explicit IDs override the default only for that rendering. Packages other than bib-highlights have no package-load options; pass their settings to the setup/render commands.",
      "options": []
    }
  ],
  "collaboration": [
    {
      "title": "Project declarations",
      "families": [
        "dfgcollab/project"
      ],
      "scope": "Options for \\DeclareCollaborationProject{ID}{options}. Each declaration replaces that ID in the current TeX group. IDs contain letters, digits, and hyphens and start with a letter or digit.",
      "options": [
        {
          "name": "area",
          "default": "First character of ID",
          "values": "Area name",
          "effect": "Groups projects and selects their area colour; it need not match the ID prefix."
        },
        {
          "name": "collaboration",
          "default": "{}",
          "values": "Comma-separated project IDs",
          "effect": "Stored undirected connections. Duplicate and self-links are ignored; reverse declarations need not be repeated."
        },
        {
          "name": "collaborations",
          "default": "{}",
          "values": "Same as collaboration",
          "effect": "Compatibility alias for the singular declaration key."
        },
        {
          "name": "active",
          "default": "true",
          "values": "true or false",
          "effect": "False omits this project and incident edges from plots."
        }
      ],
      "commands": [
        {
          "name": "DeclareCollaborationProject",
          "signature": "\\marg{ID}\\marg{fields}",
          "description": "Declare or replace project data in the current group."
        },
        {
          "name": "CollaborationSetup",
          "signature": "\\marg{options}",
          "description": "Set persistent area-colour defaults in the current group."
        },
        {
          "name": "CollaborationPlot",
          "signature": "\\oarg{options}\\marg{ID}",
          "description": "Render the independent project registry, with optional per-call connection and display overrides."
        },
        {
          "name": "clearCollaborationProjects",
          "signature": "",
          "description": "Clear the independent project registry in the current group."
        }
      ]
    },
    {
      "title": "Area setup",
      "families": [
        "dfgcollab/setup"
      ],
      "scope": "Options for \\CollaborationSetup; follow TeX grouping. Per-plot area options override these defaults. With the class loaded this setup also updates its area-colour settings.",
      "options": [
        {
          "name": "area-colors",
          "default": "{}",
          "values": "Area=colour pairs",
          "effect": "Explicit area colours. Local plots merge individual mappings with the setup mappings."
        },
        {
          "name": "area-palette",
          "default": "blue!70!black, teal!80!black, orange!85!black, violet, brown",
          "values": "Nonempty colour list",
          "effect": "Rotating fallback palette for areas without an explicit colour."
        }
      ]
    },
    {
      "title": "Per-plot options",
      "families": [
        "dfg/project-collaboration-plot"
      ],
      "scope": "Options for \\CollaborationPlot or the collaboration type of \\printPlot. Each rendering resets built-in defaults, then applies shared, type-specific, and local options. Float keys also pass through to hvFloat.",
      "options": [
        {
          "name": "layout",
          "default": "arc",
          "values": "arc, arc-diagram, or heatmap",
          "effect": "Selects the visual layout. arc-diagram is a value alias for arc."
        },
        {
          "name": "arc",
          "default": "Not selected separately",
          "values": "Bare key",
          "effect": "Shorthand for layout=arc."
        },
        {
          "name": "arc-diagram",
          "default": "Not selected separately",
          "values": "Bare key",
          "effect": "Shorthand for layout=arc."
        },
        {
          "name": "heatmap",
          "default": "Not selected separately",
          "values": "Bare key",
          "effect": "Shorthand for layout=heatmap."
        },
        {
          "name": "arcs",
          "default": "false",
          "values": "true or false; bare key means true",
          "effect": "Draws connecting arcs in the arc layout."
        },
        {
          "name": "no-arcs",
          "default": "Not selected separately",
          "values": "Bare key",
          "effect": "Shorthand for arcs=false."
        },
        {
          "name": "area-colors",
          "default": "Setup mappings",
          "values": "Area=colour pairs",
          "effect": "Overrides or adds individual area colours for this rendering."
        },
        {
          "name": "area-colours",
          "default": "Setup mappings",
          "values": "Same as area-colors",
          "effect": "British-spelling alias."
        },
        {
          "name": "area-palette",
          "default": "Setup palette",
          "values": "Colour list",
          "effect": "Replaces the fallback palette for this call. An empty per-call list leaves the palette unchanged."
        },
        {
          "name": "caption",
          "default": "{}",
          "values": "TeX text",
          "effect": "Appends text to the automatic caption. An empty value clears inherited additional caption text."
        },
        {
          "name": "collaboration",
          "default": "Stored connections",
          "values": "Comma-separated IDs; {} allowed",
          "effect": "Replaces all edges incident to the focus for this rendering, including incoming edges. With no dataset, supplies the other one-off node IDs."
        },
        {
          "name": "collaborations",
          "default": "Stored connections",
          "values": "Same as collaboration",
          "effect": "Compatibility alias for the local connection override."
        },
        {
          "name": "show-projects",
          "default": "All active projects",
          "values": "Comma-separated IDs; {} allowed",
          "effect": "Filters displayed nodes. The focus is always included; an empty list shows only the focus."
        },
        {
          "name": "projects",
          "default": "All active projects",
          "values": "Same as show-projects",
          "effect": "Compatibility alias for the display filter; it does not define connections."
        },
        {
          "name": "width",
          "default": "\\linewidth",
          "values": "TeX dimension",
          "effect": "Requested plot width; layout measurement uses this width."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\CollaborationPlot[options]{ID} uses the independent registry. \\clearCollaborationProjects clears that registry in the current group. The class adds \\ProjectCollaborationPlot, \\collaborationPlot and its plural alias; its \\printPlot reads class metadata. Node IDs are not arbitrary TeX labels. Edges between filtered or inactive nodes are not shown.",
      "options": []
    }
  ],
  "gantt": [
    {
      "title": "Narrative workpackage fields",
      "families": [
        "dfg/workpackage",
        "dfggantt/record"
      ],
      "scope": "Fields for \\addWP{ID}{fields} and \\DeclareWorkPackage{project}{ID}{fields}. Set a project before narrative declarations with \\GanttProject. Grouped title/gantt fields take precedence over corresponding legacy fields.",
      "options": [
        {
          "name": "title",
          "default": "{}",
          "values": "TeX text",
          "effect": "Narrative heading; normalizes to name. It also supplies the chart description when no chart label/description was given."
        },
        {
          "name": "gantt",
          "default": "No grouped chart fields",
          "values": "Nested label, start, end, style keys",
          "effect": "Sets the workpackage chart fields without entering a second dataset."
        },
        {
          "name": "id",
          "default": "Mandatory command argument",
          "values": "Legacy ID field",
          "effect": "Accepted by normalization for compatibility; standalone storage uses the mandatory command ID and ignores this field. Prefer the mandatory argument."
        },
        {
          "name": "name",
          "default": "{}",
          "values": "TeX text",
          "effect": "Legacy narrative heading. title overrides it."
        },
        {
          "name": "description",
          "default": "{}; falls back to title/name in grouped syntax",
          "values": "TeX text",
          "effect": "Legacy chart label. gantt/label overrides it."
        },
        {
          "name": "periodStart",
          "default": "1",
          "values": "Nonnegative integer",
          "effect": "Legacy first chart slot. gantt/start overrides it."
        },
        {
          "name": "periodEnd",
          "default": "1",
          "values": "Nonnegative integer, at least start",
          "effect": "Legacy final chart slot. gantt/end overrides it. Equal endpoints omit the bar."
        },
        {
          "name": "style",
          "default": "default",
          "values": "default, alternative, important, crosshatch, striped",
          "effect": "Legacy bar appearance. gantt/style overrides it."
        }
      ],
      "commands": [
        {
          "name": "GanttSetup",
          "signature": "\\marg{options}",
          "description": "Set the quarter grid defaults in the current group."
        },
        {
          "name": "GanttProject",
          "signature": "\\marg{ID}",
          "description": "Select the project for narrative workpackages and the default plot focus."
        },
        {
          "name": "addWP",
          "signature": "\\marg{ID}\\marg{fields}",
          "description": "Add a narrative item inside workpackages, with the same data supplying its Gantt row."
        },
        {
          "name": "DeclareWorkPackage",
          "signature": "\\marg{project}\\marg{ID}\\marg{fields}",
          "description": "Declare a chart row without a narrative list item."
        },
        {
          "name": "getWP",
          "signature": "\\oarg{project}\\marg{IDs}",
          "description": "Reference one or more narrative workpackages. The optional project replaces the current project for this call."
        },
        {
          "name": "GanttChart",
          "signature": "\\oarg{options}\\marg{project}",
          "description": "Draw a graphic only, without the float wrapper."
        },
        {
          "name": "GanttPlotFigure",
          "signature": "\\oarg{options}\\marg{project}",
          "description": "Draw a chart with automatic caption and native hvFloat options."
        }
      ]
    },
    {
      "title": "Nested gantt fields",
      "families": [
        "dfg/workpackage/gantt"
      ],
      "scope": "Use inside gantt={...} in a workpackage declaration. Start/end are chart-slot indices, not calendar dates.",
      "options": [
        {
          "name": "label",
          "default": "Workpackage title/name when present",
          "values": "TeX text",
          "effect": "Label printed inside the bar."
        },
        {
          "name": "start",
          "default": "1",
          "values": "Nonnegative integer",
          "effect": "First slot. A value greater than end is an error."
        },
        {
          "name": "end",
          "default": "1",
          "values": "Nonnegative integer",
          "effect": "Last slot. Equal start/end values omit the bar."
        },
        {
          "name": "style",
          "default": "default",
          "values": "default, alternative, important, crosshatch, striped",
          "effect": "Solid default/alternative/important colours, a crosshatch pattern, or alternating stripes."
        }
      ]
    },
    {
      "title": "Grid setup and individual charts",
      "families": [
        "dfggantt/chart",
        "dfggantt/plot"
      ],
      "scope": "Use \\GanttSetup for grouped persistent defaults, \\GanttChart for a graphic, or the standalone Gantt plot wrapper for a floating graphic. The standalone wrapper also consumes caption and forwards remaining float keys to hvFloat. The class retains its own plot adapter.",
      "options": [
        {
          "name": "slots",
          "default": "16",
          "values": "Positive integer",
          "effect": "Number of quarter slots. Validated before geometry calculations."
        },
        {
          "name": "first-quarter",
          "default": "3",
          "values": "Integer 1 to 4",
          "effect": "First quarter label. Subsequent labels cycle Q1 to Q4."
        },
        {
          "name": "year-labels",
          "default": "{}",
          "values": "Comma-separated TeX labels",
          "effect": "Successive year-group titles. Missing labels use the funding-year formatter, whose standalone default is Year followed by the group number."
        },
        {
          "name": "caption",
          "default": "{}",
          "values": "TeX text; floating wrapper only",
          "effect": "Appends to the automatic Gantt caption. An empty value clears inherited additional text; it is not a graphic-only GanttChart option."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\GanttProject{ID} selects the workpackage project and generic plot focus. \\getWP[project]{IDs} references workpackages, with the optional project replacing the current one for that call. \\GanttPlotFigure[options]{ID} wraps a chart in hvFloat. \\GanttChart and legacy \\dfgGanttEnvironment render graphics only. \\dfgGanttContent renders stored rows, and \\DFGGanttTitles renders grid headings inside pgfgantt. Standalone formatter hooks are \\dfgFundingYear{number}, \\DFGGanttLabel{project}{id}, \\DFGGanttTag{project}{field}{text}{tag}, and \\dfgGanttShowQs{quarter}{slot}. The class supplies its own reference/debug formatters. Gantt colours can be redefined through the xcolor names tableHeadingsBG, tableHeadingsFont, tableOuterLines, color@gantt@frame, color@gantt@default, color@gantt@alternative, color@gantt@important, color@gantt@crosshatch, color@gantt@stripe-one, color@gantt@stripe-two.",
      "options": []
    }
  ],
  "timeline": [
    {
      "title": "Event data",
      "families": [
        "crc/event"
      ],
      "scope": "Mandatory data argument of \\addEvent[formatting]{data}. Events and clearEvents follow TeX grouping; category registrations are global. The optional formatting argument is documented separately below.",
      "options": [
        {
          "name": "id",
          "default": "Automatically generated event-N",
          "values": "Unique ID",
          "effect": "Stable key for later per-render overrides. Duplicate IDs warn and retain the first event."
        },
        {
          "name": "date",
          "default": "Required",
          "values": "YYYY-MM or YYYY-MM-DD",
          "effect": "Point date, or beginning of a date range. Month-only dates are positioned mid-month; days and leap years are validated."
        },
        {
          "name": "start date",
          "default": "Required when date is absent",
          "values": "Same as date",
          "effect": "Alias for the start date. If both forms are given, the later assignment wins."
        },
        {
          "name": "end date",
          "default": "Start date",
          "values": "YYYY-MM or YYYY-MM-DD",
          "effect": "End of a range, not before its beginning."
        },
        {
          "name": "category",
          "default": "Required",
          "values": "Registered category key",
          "effect": "Selects colour, legend label, and default icon. Built-ins are retreat, progress, networking, graduate, symposium."
        },
        {
          "name": "title",
          "default": "Required nonempty text",
          "values": "TeX text",
          "effect": "Full event title and details heading."
        },
        {
          "name": "label",
          "default": "Title",
          "values": "TeX text",
          "effect": "Short chart label when labels=label."
        },
        {
          "name": "abbreviation",
          "default": "Falls back to label/title",
          "values": "TeX text",
          "effect": "Used when labels=abbreviation and a value is supplied."
        },
        {
          "name": "summary",
          "default": "{}",
          "values": "Short TeX text",
          "effect": "Optional second line in the chart when summary=true; also available to aggregated detail rendering."
        },
        {
          "name": "description",
          "default": "{}",
          "values": "TeX text",
          "effect": "Long details text; kept separate from the chart summary."
        },
        {
          "name": "icon",
          "default": "Category icon",
          "values": "TeX icon command",
          "effect": "Overrides the category icon for this event."
        }
      ],
      "commands": [
        {
          "name": "addEvent",
          "signature": "\\oarg{formatting}\\marg{data}",
          "description": "Register one dated event. Formatting can be overridden when rendering."
        },
        {
          "name": "printEventTimeline",
          "signature": "\\oarg{options}",
          "description": "Render the selected events as a horizontal timeline."
        },
        {
          "name": "printEventDetails",
          "signature": "\\oarg{options}",
          "description": "Render the same event data as individual or aggregated details."
        },
        {
          "name": "DeclareEventCategory",
          "signature": "\\marg{key}\\marg{label}\\marg{colour}\\marg{icon}",
          "description": "Register or replace a global category."
        },
        {
          "name": "clearEvents",
          "signature": "",
          "description": "Clear event data and stored formatting, preserving categories."
        }
      ]
    },
    {
      "title": "Timeline rendering",
      "families": [
        "crc/timeline"
      ],
      "scope": "Options for \\printEventTimeline. Each call resets the following defaults; changes are local to that rendering. Labels occupy lanes above the axis; date labels use independent lanes below it.",
      "options": [
        {
          "name": "width",
          "default": "\\linewidth",
          "values": "Positive dimension",
          "effect": "Total requested width including label fitting. Insufficient width produces a diagnostic."
        },
        {
          "name": "year",
          "default": "all",
          "values": "all or four-digit year",
          "effect": "Filters to events intersecting that year; a range can intersect several years."
        },
        {
          "name": "rotation",
          "default": "30",
          "values": "Angle in degrees",
          "effect": "Upper event-label angle."
        },
        {
          "name": "date rotation",
          "default": "auto",
          "values": "auto or angle in degrees",
          "effect": "Auto follows the effective event-label angle unless independently overridden."
        },
        {
          "name": "labels",
          "default": "label",
          "values": "title, label, abbreviation",
          "effect": "Selects the event text, with the fallbacks documented above."
        },
        {
          "name": "summary",
          "default": "false",
          "values": "true or false",
          "effect": "Adds a nonempty summary below the chart label."
        },
        {
          "name": "icons",
          "default": "true",
          "values": "true or false",
          "effect": "Displays the event icons."
        },
        {
          "name": "legend",
          "default": "true",
          "values": "true or false",
          "effect": "Shows the categories used by the selected events."
        },
        {
          "name": "show labels",
          "default": "true",
          "values": "true or false",
          "effect": "Displays upper label text; icons can remain visible independently."
        },
        {
          "name": "show dates",
          "default": "true",
          "values": "true or false",
          "effect": "Displays date or date-range labels below the axis."
        },
        {
          "name": "label width",
          "default": "0pt",
          "values": "Nonnegative dimension",
          "effect": "Zero uses natural text width; positive values constrain/wrap label text."
        },
        {
          "name": "label distance",
          "default": "1.8mm",
          "values": "Nonnegative dimension",
          "effect": "Distance from the axis to the first upper label lane."
        },
        {
          "name": "lane",
          "default": "auto",
          "values": "auto or nonnegative integer",
          "effect": "Default upper lane request. Lane numbering begins at zero; auto avoids collisions."
        },
        {
          "name": "lane spacing",
          "default": "auto",
          "values": "auto or positive dimension",
          "effect": "Auto uses measured upper-label height plus gap."
        },
        {
          "name": "date lane",
          "default": "auto",
          "values": "auto or nonnegative integer",
          "effect": "Default date-label lane request, independent of upper lanes."
        },
        {
          "name": "date distance",
          "default": "1.8mm",
          "values": "Nonnegative dimension",
          "effect": "Distance from the axis to the first lower date lane."
        },
        {
          "name": "date lane spacing",
          "default": "auto",
          "values": "auto or positive dimension",
          "effect": "Auto uses measured date-label height plus gap."
        },
        {
          "name": "gap",
          "default": ".8mm",
          "values": "Nonnegative dimension",
          "effect": "Collision/automatic-lane gap."
        },
        {
          "name": "font",
          "default": "\\sffamily\\fontsize{7.4}{9}\\selectfont",
          "values": "TeX font commands",
          "effect": "Upper-label font."
        },
        {
          "name": "date font",
          "default": "\\sffamily\\fontsize{6.5}{8}\\selectfont",
          "values": "TeX font commands",
          "effect": "Date-label font."
        },
        {
          "name": "line color",
          "default": "EventMuted!40",
          "values": "xcolor colour expression",
          "effect": "Main timeline axis colour."
        },
        {
          "name": "line width",
          "default": ".6pt",
          "values": "Nonnegative dimension",
          "effect": "Main axis stroke."
        },
        {
          "name": "connector width",
          "default": ".35pt",
          "values": "Nonnegative dimension",
          "effect": "Upper-label connector stroke."
        },
        {
          "name": "date connector width",
          "default": ".3pt",
          "values": "Nonnegative dimension",
          "effect": "Date-label connector stroke."
        },
        {
          "name": "range width",
          "default": "1.2pt",
          "values": "Nonnegative dimension",
          "effect": "Date-range segment stroke."
        },
        {
          "name": "dot radius",
          "default": ".9mm",
          "values": "Nonnegative dimension",
          "effect": "Radius of event dots."
        },
        {
          "name": "events",
          "default": "{}",
          "values": "ID={formatting keys} pairs",
          "effect": "Overrides specific registered event IDs for this rendering. These overrides take precedence over stored optional addEvent formatting."
        }
      ]
    },
    {
      "title": "Per-event formatting",
      "families": [
        "crc/timeline/event"
      ],
      "scope": "Use in the optional argument of \\addEvent or under events={id={...}} in \\printEventTimeline. Values inherit the timeline settings unless listed otherwise. Local events overrides win over stored formatting.",
      "options": [
        {
          "name": "lane",
          "default": "Timeline lane",
          "values": "auto or nonnegative integer",
          "effect": "Upper-label lane for this event."
        },
        {
          "name": "xshift",
          "default": "0pt",
          "values": "Signed dimension",
          "effect": "Horizontal upper-label shift; does not change the event date."
        },
        {
          "name": "yshift",
          "default": "0pt",
          "values": "Signed dimension",
          "effect": "Vertical upper-label shift."
        },
        {
          "name": "rotation",
          "default": "Timeline rotation",
          "values": "Angle in degrees",
          "effect": "Event label/icon angle. When show labels=false, upper icons remain upright."
        },
        {
          "name": "date rotation",
          "default": "Timeline date rotation",
          "values": "auto or angle",
          "effect": "Independent date-label rotation. Auto follows the effective per-event label rotation."
        },
        {
          "name": "date direction",
          "default": "left",
          "values": "left or right",
          "effect": "Chooses which end/digit of the date label aligns with its connector."
        },
        {
          "name": "label width",
          "default": "Timeline label width",
          "values": "Nonnegative dimension",
          "effect": "Per-event text wrapping width."
        },
        {
          "name": "label",
          "default": "Selected event label",
          "values": "TeX text",
          "effect": "Overrides the rendered short label."
        },
        {
          "name": "icon",
          "default": "Event/category icon",
          "values": "TeX icon command",
          "effect": "Overrides the rendered icon."
        },
        {
          "name": "font",
          "default": "Timeline upper font",
          "values": "TeX font commands",
          "effect": "Per-event upper-label font."
        },
        {
          "name": "date lane",
          "default": "Timeline date lane",
          "values": "auto or nonnegative integer",
          "effect": "Per-event lower date lane."
        },
        {
          "name": "date xshift",
          "default": "0pt",
          "values": "Signed dimension",
          "effect": "Horizontal date-label shift."
        },
        {
          "name": "date yshift",
          "default": "0pt",
          "values": "Signed dimension",
          "effect": "Vertical date-label shift."
        },
        {
          "name": "node options",
          "default": "{}",
          "values": "TikZ node options",
          "effect": "Additional upper-label node styling. These are TikZ options, not timeline keys."
        }
      ]
    },
    {
      "title": "Event details",
      "families": [
        "crc/event-details"
      ],
      "scope": "Options for \\printEventDetails. Every call resets the listed defaults. Aggregated rendering groups selected events by category; category override text is applied in that aggregated mode.",
      "options": [
        {
          "name": "format",
          "default": "list",
          "values": "list or prose",
          "effect": "Description-list layout or continuous prose."
        },
        {
          "name": "year",
          "default": "all",
          "values": "all or four-digit year",
          "effect": "Same intersection filter as the chart."
        },
        {
          "name": "icons",
          "default": "true",
          "values": "true or false",
          "effect": "Shows icons in detail headings/prose."
        },
        {
          "name": "show dates",
          "default": "true",
          "values": "true or false",
          "effect": "Shows event dates or collected dates."
        },
        {
          "name": "nodate",
          "default": "false",
          "values": "true or false; bare means true",
          "effect": "Inverse alias: nodate=true means show dates=false."
        },
        {
          "name": "aggregated",
          "default": "false",
          "values": "true or false",
          "effect": "Combines events by category and common text rather than printing each event separately."
        },
        {
          "name": "categories",
          "default": "{}",
          "values": "Category={title=...,description=...} pairs",
          "effect": "Overrides aggregate category headings/descriptions; it is not a category-selection filter."
        }
      ]
    },
    {
      "title": "Aggregate category overrides",
      "families": [
        "crc/event-details-category"
      ],
      "scope": "Nested keys under categories={category={...}} for \\printEventDetails. The category must already be registered.",
      "options": [
        {
          "name": "title",
          "default": "Registered/generated category heading",
          "values": "TeX text",
          "effect": "Replaces the aggregate heading for this category."
        },
        {
          "name": "description",
          "default": "Automatically combined event text",
          "values": "TeX text",
          "effect": "Replaces the aggregate category description."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\DeclareEventCategory{key}{label}{colour}{icon} registers or replaces a global category. \\EventCategoryIcon{key} prints its coloured icon. Built-ins are retreat (Annual retreat, EventRetreat, users), progress (Progress day, EventProgress, comments), networking (Networking, EventNetworking, handshake), graduate (Graduate school retreat, EventGraduate, graduation cap), and symposium (International symposium, EventSymposium, globe). Redefine the EventRetreat, EventProgress, EventNetworking, EventGraduate, EventSymposium, EventInk, EventMuted, EventTalk, or EventMisc xcolor names to customize their colours. \\clearEvents clears event data and stored formatting, preserving categories. There is no persistent timeline setup command: rendering settings reset on every call.",
      "options": []
    }
  ],
  "distribution": [
    {
      "title": "Chart geometry, labels, and order",
      "families": [
        "/distribution"
      ],
      "scope": "Use \\distributionSetup for defaults or \\DistributionChart[options] for a single grouped chart. Registered categories initially are postdoc, industry, other, with cap, factory, bulb icons. The additional none icon draws no symbol.",
      "options": [
        {
          "name": "unit width",
          "default": "7.5mm",
          "values": "Dimension",
          "effect": "Width of one count segment."
        },
        {
          "name": "bar height",
          "default": "7.8mm",
          "values": "Dimension",
          "effect": "Height of each bar."
        },
        {
          "name": "row spacing",
          "default": "10mm",
          "values": "Dimension",
          "effect": "Distance between row centres."
        },
        {
          "name": "label x",
          "default": "-8mm",
          "values": "Signed dimension",
          "effect": "Horizontal icon/label anchor relative to the axis."
        },
        {
          "name": "label width",
          "default": "15mm",
          "values": "Dimension",
          "effect": "Text width of the category label."
        },
        {
          "name": "label drop",
          "default": "4.8mm",
          "values": "Dimension",
          "effect": "Downward text offset when label position=below."
        },
        {
          "name": "label position",
          "default": "left",
          "values": "left or below",
          "effect": "Category text to the left of the icon, or below it."
        },
        {
          "name": "label gap",
          "default": "2mm",
          "values": "Dimension",
          "effect": "Gap between left-positioned label and icon."
        },
        {
          "name": "icon radius",
          "default": "3.4mm",
          "values": "Dimension",
          "effect": "Radius of the category icon background."
        },
        {
          "name": "icon raise",
          "default": "auto",
          "values": "auto or signed dimension",
          "effect": "Auto is 0pt for left labels and 2.3mm for below labels."
        },
        {
          "name": "value gap",
          "default": "3mm",
          "values": "Dimension",
          "effect": "Gap from the end of a bar to its numeric count."
        },
        {
          "name": "axis padding",
          "default": "2mm",
          "values": "Dimension",
          "effect": "Axis extension beyond the first and last bars."
        },
        {
          "name": "axis width",
          "default": ".45pt",
          "values": "Dimension",
          "effect": "Axis stroke width."
        },
        {
          "name": "axis dot radius",
          "default": ".4mm",
          "values": "Dimension",
          "effect": "Radius of the dots at the axis ends."
        },
        {
          "name": "separator width",
          "default": ".4pt",
          "values": "Dimension",
          "effect": "White strokes between count segments."
        },
        {
          "name": "text color",
          "default": "DistributionText",
          "values": "xcolor colour expression",
          "effect": "Category and count text colour."
        },
        {
          "name": "axis color",
          "default": "DistributionAxis",
          "values": "xcolor colour expression",
          "effect": "Axis and endpoint-dot colour."
        },
        {
          "name": "label font",
          "default": "\\sffamily\\bfseries\\fontsize{8.8}{10}\\selectfont",
          "values": "TeX font commands",
          "effect": "Category-label font."
        },
        {
          "name": "value font",
          "default": "\\sffamily\\bfseries\\fontsize{11}{12}\\selectfont",
          "values": "TeX font commands",
          "effect": "Numeric-count font."
        },
        {
          "name": "order",
          "default": "postdoc, industry, other; new categories append",
          "values": "Nonempty list of distinct registered categories",
          "effect": "Selects and orders displayed rows. Unknown or repeated categories are errors."
        }
      ],
      "commands": [
        {
          "name": "DeclareDistributionIcon",
          "signature": "\\marg{name}\\marg{TikZ code}",
          "description": "Register a normalized vector icon."
        },
        {
          "name": "DeclareDistributionCategory",
          "signature": "\\marg{key}\\marg{label}\\marg{colour}\\marg{icon}",
          "description": "Register a category using an existing icon."
        },
        {
          "name": "distributionSetup",
          "signature": "\\marg{options}",
          "description": "Set geometry and row-order defaults."
        },
        {
          "name": "setDistribution",
          "signature": "\\marg{counts}",
          "description": "Replace category counts; omitted registered categories become zero."
        },
        {
          "name": "DistributionChart",
          "signature": "\\oarg{options}",
          "description": "Render the current dataset with optional local geometry settings."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\DeclareDistributionIcon{name}{TikZ code} declares a normalized vector symbol; cap, factory, bulb, and none are built in. \\DeclareDistributionCategory{key}{label}{colour}{icon} adds or replaces a category; its icon must exist. \\setDistribution{category=count,...} replaces counts, treating omitted registered categories as zero. Negative/non-integer counts, unknown categories, and duplicates are errors; rejected data leave the last valid counts intact. \\DistributionChart[options] renders the current dataset. Colour hooks are DistributionPostdoc, DistributionIndustry, DistributionOther, DistributionText, and DistributionAxis. The stock geometry has no sign/range validation; use sensible positive sizes for bars and spacing.",
      "options": []
    }
  ],
  "icons": [
    {
      "title": "Icon registration",
      "families": [
        "dfgicons/declare"
      ],
      "scope": "Options for \\DeclareIcon{name}{options}. Names and aliases are registered globally. At least one asset is needed; redeclaration replaces the complete alias list.",
      "options": [
        {
          "name": "file",
          "default": "{}",
          "values": "Graphics filename/path",
          "effect": "Default asset for both shapes unless a variant is supplied."
        },
        {
          "name": "square",
          "default": "file or supplied vertical variant",
          "values": "Graphics filename/path",
          "effect": "Square-shape asset."
        },
        {
          "name": "vertical",
          "default": "file or supplied square variant",
          "values": "Graphics filename/path",
          "effect": "Portrait-shape asset."
        },
        {
          "name": "aliases",
          "default": "{}",
          "values": "Comma-separated exact names",
          "effect": "Additional explicit names. Conflicts with another icon are errors and leave the registry unchanged. Filename, basename, and PDF-to-SVG aliases are also registered automatically, without overriding explicit names."
        }
      ],
      "commands": [
        {
          "name": "DeclareIcon",
          "signature": "\\marg{name}\\marg{assets}",
          "description": "Globally register graphic variants and explicit aliases."
        },
        {
          "name": "getIcon",
          "signature": "\\oarg{options}\\marg{names}",
          "description": "Place registered icons side by side next to the following paragraph."
        },
        {
          "name": "IconIfRegisteredTF",
          "signature": "\\marg{name}\\marg{yes}\\marg{no}",
          "description": "Test registration of a name or alias after trimming spaces."
        }
      ]
    },
    {
      "title": "Paragraph icon placement",
      "families": [
        "crc/icons"
      ],
      "scope": "Options for \\getIcon[options]{comma-separated names}. All placement options reset per call. Remaining options are forwarded to graphicx includegraphics for every image; see texdoc graphics for its complete backend reference.",
      "options": [
        {
          "name": "shape",
          "default": "square",
          "values": "square or vertical",
          "effect": "Selects the registered variant, with the registration fallback rules."
        },
        {
          "name": "square",
          "default": "Not selected separately",
          "values": "Bare key; no value",
          "effect": "Shorthand for shape=square."
        },
        {
          "name": "vertical",
          "default": "Not selected separately",
          "values": "Bare key; no value",
          "effect": "Shorthand for shape=vertical."
        },
        {
          "name": "gap",
          "default": ".6em",
          "values": "Dimension",
          "effect": "Spacing between grouped images and between the image group and paragraph text."
        },
        {
          "name": "height",
          "default": "4 lines for square; 5 for vertical",
          "values": "Positive integer",
          "effect": "Reserved paragraph lines. Total image height is capital-H height plus (height-1) baselines. This computed totalheight is applied after forwarded graphicx keys."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\IconIfRegisteredTF{name}{yes}{no} tests a registered name or alias after trimming spaces. Missing graphics files produce a warning and example-image fallback at rendering time, rather than failing registration. Graphics lookup follows graphicspath and driver extension order. The computed totalheight is appended after forwarded graphicx options, so it controls the final icon height; width, trim, clip, page, and angle retain graphicx semantics.",
      "options": []
    }
  ],
  "bib-highlights": [
    {
      "title": "Package loading",
      "families": [
        "package-options"
      ],
      "scope": "Only noauthors is a load-time package option. Load biblatex first to choose its backend/style. Setup options below are passed to BibHighlightSetup, not to usepackage.",
      "options": [
        {
          "name": "noauthors",
          "default": "Not selected: hash backend enabled",
          "values": "Bare load-time option",
          "effect": "Disables creation/registration of the auxiliary author-hash bibliography. Author registration/reset commands become no-ops. Whole-entry highlighting remains available."
        }
      ],
      "commands": [
        {
          "name": "BibHighlightSetup",
          "signature": "\\marg{options}",
          "description": "Set independent author and entry highlighting options."
        },
        {
          "name": "addboldnames",
          "signature": "\\marg{names}",
          "description": "Register selected authors; brace names containing commas."
        },
        {
          "name": "resetboldnames",
          "signature": "",
          "description": "Clear the active author-hash registry."
        },
        {
          "name": "printHighlightedBibliography",
          "signature": "\\oarg{bibliography options}\\marg{keyword}",
          "description": "Select the highlight keyword locally and forward list options to BibLaTeX. This does not filter the list by keyword."
        }
      ]
    },
    {
      "title": "Highlight setup",
      "families": [
        "dfgbib/setup"
      ],
      "scope": "Options for \\BibHighlightSetup. Settings follow TeX grouping. The class connects the two switches and author colour to its own live customization.",
      "options": [
        {
          "name": "emphasizeAuthors",
          "default": "true",
          "values": "true or false",
          "effect": "Turns matching-author bold/colour emphasis on or off independently of whole-entry emphasis."
        },
        {
          "name": "emphasizeEntries",
          "default": "true",
          "values": "true or false",
          "effect": "Enables bold type for entries carrying the selected keyword."
        },
        {
          "name": "keyword",
          "default": "{}; no whole-entry keyword selected",
          "values": "BibLaTeX keyword",
          "effect": "Selects entries for complete bold type. printHighlightedBibliography supplies a local keyword for one list; it does not filter out other entries."
        },
        {
          "name": "color",
          "default": "black",
          "values": "xcolor colour expression",
          "effect": "Colour of matching author names; does not recolour the entire entry."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\addboldnames{{Family, Given},...} registers names through Biber hashes. \\resetboldnames clears the active hash registry. Declare \\DFGBoldNamesFile before loading the package to change the auxiliary .bib path; the default is \\jobname-boldAuthors.bib and its directory must exist. \\printHighlightedBibliography[options]{keyword} uses the keyword locally and forwards all bracketed options to BibLaTeX printbibliography (see texdoc biblatex); it does not add a keyword filter. Advanced adapter hooks are \\DFGBibIfAuthorsTF{yes}{no}, \\DFGBibIfEntriesTF{yes}{no}, and expandable \\DFGBibNameColor. Match-name aliases must be registered explicitly with addboldnames.",
      "options": []
    }
  ],
  "thumbindex": [
    {
      "title": "Live thumbindex setup",
      "families": [
        "dfgthumb/setup"
      ],
      "scope": "Options for \\ThumbIndexSetup; follow TeX grouping and share the class live state when used with dfg-crc. Defaults here describe an ordinary standalone document. Activate a scrlayer-scrpage page style to use the running heads.",
      "options": [
        {
          "name": "enabled",
          "default": "true",
          "values": "true or false",
          "effect": "Controls whether printThumbIndex installs a new tab. Turning this false does not remove a tab already installed; use printThumbIndexOff for that."
        },
        {
          "name": "pattern",
          "default": "8",
          "values": "Positive integer",
          "effect": "Number of vertical slots before wrapping to the first slot."
        },
        {
          "name": "width",
          "default": "12mm",
          "values": "Dimension",
          "effect": "Nominal tab width; edge overhang is handled internally."
        },
        {
          "name": "font",
          "default": "\\sffamily\\bfseries",
          "values": "TeX font commands",
          "effect": "Tab-label font."
        },
        {
          "name": "bg",
          "default": "black",
          "values": "xcolor colour expression",
          "effect": "Default background for subsequent printThumbIndex calls."
        },
        {
          "name": "fg",
          "default": "white",
          "values": "xcolor colour expression",
          "effect": "Default tab text colour."
        },
        {
          "name": "orientation",
          "default": "outwards",
          "values": "outwards or inwards",
          "effect": "Inwards adds 180 degrees to the odd/even outward rotations."
        },
        {
          "name": "topmargin",
          "default": "auto",
          "values": "auto or dimension",
          "effect": "Physical distance from the page top; auto follows the live text block."
        },
        {
          "name": "bottommargin",
          "default": "auto",
          "values": "auto or dimension",
          "effect": "Physical distance from the page bottom; auto follows the live text block. The remaining height is divided into pattern equal slots."
        }
      ],
      "commands": [
        {
          "name": "ThumbIndexSetup",
          "signature": "\\marg{options}",
          "description": "Set live tab geometry, appearance, and orientation."
        },
        {
          "name": "printThumbIndex",
          "signature": "\\oarg{colours}\\marg{label}",
          "description": "Advance to the next slot and install a tab in normal and plain running heads."
        },
        {
          "name": "printThumbIndexOff",
          "signature": "",
          "description": "Remove installed tab heads without resetting the slot counter."
        },
        {
          "name": "resetThumbIndex",
          "signature": "",
          "description": "Reset the slot counter without removing the current tab."
        }
      ]
    },
    {
      "title": "Individual tabs",
      "families": [
        "dfg/thumb-index"
      ],
      "scope": "Options for \\printThumbIndex[options]{label}. Each call begins from the current setup colours and installs the selected tab on subsequent normal/plain pages until another call or printThumbIndexOff. A bare colour without an equals sign is background shorthand.",
      "options": [
        {
          "name": "bg",
          "default": "Current setup background",
          "values": "xcolor colour expression",
          "effect": "Background override for this tab; does not change the setup default."
        },
        {
          "name": "fg",
          "default": "Current setup foreground",
          "values": "xcolor colour expression",
          "effect": "Text-colour override for this tab; does not change the setup default."
        }
      ]
    },
    {
      "title": "Command arguments and customization hooks",
      "families": [],
      "scope": "\\printThumbIndexOff removes installed tab heads without resetting the slot counter. \\resetThumbIndex resets the counter without removing a displayed tab. Lower-level \\evenpageletterthumb{label} and \\oddpageletterthumb{label} draw the left/right edge tab. Normal and plain heads are both installed by printThumbIndex. Width and explicit margins are dimension inputs without additional sign validation; margins must leave room on the page. Standalone defaults apply here; class defaults may differ and are read live.",
      "options": []
    }
  ]
}

%</module-option-catalog>
%<*docindex>
actual '='
quote '!'
level '>'
preamble "\n \\begin{theindex}\n \\makeatletter\\scan@allowedfalse\n"
postamble "\n\n \\end{theindex}\n"
item_x1 "\\efill\n \\subitem "
item_x2 "\\efill\n \\subsubitem "
delim_0 "\\pfill "
delim_1 "\\pfill "
delim_2 "\\pfill "
heading_prefix "{\\bfseries\\hfil "
heading_suffix "\\hfil}\\nopagebreak\n"
headings_flag 1
%</docindex>
%<*internalbib>
%%
%% Encoding: UTF-8
%%
@InCollection{Hoare1973,
  author    = {Charles Antony Richard Hoare},
  title     = {Hints on programming language design},
  editor    = {C. Bunyan},
  booktitle = {Computer Systems Reliability},
  series    = {State of the Art Report},
  number    = {20},
  pages     = {193--216},
  year      = {1973},
  url       = {http://flint.cs.yale.edu/cs428/documentation/HintsPL.pdf},
  urlyear   = {2018},
  comment   = {\blockcquote[195]{Hoare1973}{Documentation must be regarded as an integral part of the process of design and coding. A good programming language will encourage and assist the programmer to write clear, self-documenting code, and even perhaps to develop and display a pleasant style of writing.}}
}
%</internalbib>
%<*internal>
\fi
\def\nameofplainTeX{plain}
\ifx\fmtname\nameofplainTeX\else
  \expandafter\begingroup
\fi
\iffalse
%</internal>
%<*install|devinstall>
%% dfg-crc.ins
%% Copyright 2026 Lukas C. Bossert
%%
%% This work may be distributed and/or modified under the conditions of the
%% LaTeX Project Public License, either version 1.3c of this license or (at
%% your option) any later version.
%%
%% \CharacterTable
%%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%%   Digits        \0\1\2\3\4\5\6\7\8\9
%%   Exclamation   \!     Double quote  \"     Hash (number) \#
%%   Dollar        \$     Percent       \%     Ampersand     \&
%%   Acute accent  \'     Left paren    \(     Right paren   \)
%%   Asterisk      \*     Plus          \+     Comma         \,
%%   Minus         \-     Point         \.     Solidus       \/
%%   Colon         \:     Semicolon     \;     Less than     \<
%%   Equals        \=     Greater than  \>     Question mark \?
%%   Commercial at \@     Left bracket  \[     Backslash     \\
%%   Right bracket \]     Circumflex    \^     Underscore    \_
%%   Grave accent  \|     Left brace    \{     Vertical bar  \|
%%   Right brace   \}     Tilde         \~}

\input docstrip.tex
\keepsilent
\askforoverwritefalse
\catcode9=12
\preamble
------------------------------------------------------------------------
DFG CRC proposal class
Copyright: 2026 Lukas C. Bossert
Author:    Lukas C. Bossert
E-mail:    bossert@itc.rwth-aachen.de
License:   LaTeX Project Public License v1.3c or later
See:       https://www.latex-project.org/lppl.txt
------------------------------------------------------------------------
>>>>> DO NOT CHANGE THIS FILE >>> IT WILL BE OVERWRITTEN BY ANY UPDATE !
\endpreamble
\postamble
Copyright (C) 2026 Lukas C. Bossert
\endpostamble
%</install|devinstall>
%<*install>
\generate{
  \file{dfg-crc.cls}
    {\from{dfg-crc.dtx}{file,cls}}
  \file{dfg-plots.sty}
    {\from{dfg-crc.dtx}{file,plot-core}}
  \file{dfg-collaboration.sty}
    {\from{dfg-crc.dtx}{file,collaboration-package}}
  \file{dfg-gantt.sty}
    {\from{dfg-crc.dtx}{file,gantt-package}}
  \file{dfg-timeline.sty}
    {\from{dfg-crc.dtx}{file,timeline-package}}
  \file{dfg-distribution.sty}
    {\from{dfg-crc.dtx}{file,distribution-package}}
  \file{dfg-icons.sty}
    {\from{dfg-crc.dtx}{file,icons-package}}
  \file{dfg-bib-highlights.sty}
    {\from{dfg-crc.dtx}{file,bib-highlights-package}}
  \file{dfg-thumbindex.sty}
    {\from{dfg-crc.dtx}{file,thumbindex-package}}
}
%</install>
%<*devinstall>
% Keep the output directory separate from the filename in generated comments.
\BaseDirectory{.}
\UseTDS
\usedir{local}
\generate{
  \file{dfg-crc.cls}
    {\from{dfg-crc.dtx}{file,cls}}
  \file{dfg-plots.sty}
    {\from{dfg-crc.dtx}{file,plot-core}}
  \file{dfg-collaboration.sty}
    {\from{dfg-crc.dtx}{file,collaboration-package}}
  \file{dfg-gantt.sty}
    {\from{dfg-crc.dtx}{file,gantt-package}}
  \file{dfg-timeline.sty}
    {\from{dfg-crc.dtx}{file,timeline-package}}
  \file{dfg-distribution.sty}
    {\from{dfg-crc.dtx}{file,distribution-package}}
  \file{dfg-icons.sty}
    {\from{dfg-crc.dtx}{file,icons-package}}
  \file{dfg-bib-highlights.sty}
    {\from{dfg-crc.dtx}{file,bib-highlights-package}}
  \file{dfg-thumbindex.sty}
    {\from{dfg-crc.dtx}{file,thumbindex-package}}
}
\usedir{}
\nopreamble
\nopostamble
\generate{
  \file{local/bib/dfg-base.bib}{\from{dfg-crc.dtx}{file,bib,base}}
  \file{local/bib/dfg-strings.bib}{\from{dfg-crc.dtx}{file,bib,strings}}
  \file{local/README.md}{\from{dfg-crc.dtx}{readme}}
  \file{local/dfg-modules.md}{\from{dfg-crc.dtx}{modules-guide}}
  \file{local/dfg-module-options.json}{\from{dfg-crc.dtx}{module-option-catalog}}
  \file{local/test-module-options.py}{\from{dfg-crc.dtx}{file,test-module-options}}
  \file{local/update-module-option-docs.py}{\from{dfg-crc.dtx}{file,update-module-options}}
  \file{local/test-standalone-modules.py}{\from{dfg-crc.dtx}{file,test-module-script}}
  \file{local/build-module-examples.py}{\from{dfg-crc.dtx}{file,build-module-script}}
  \file{local/module-examples/dfg-plots-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-plots}}
  \file{local/module-examples/dfg-collaboration-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-collaboration}}
  \file{local/module-examples/dfg-gantt-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-gantt}}
  \file{local/module-examples/dfg-timeline-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-timeline}}
  \file{local/module-examples/dfg-distribution-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-distribution}}
  \file{local/module-examples/dfg-icons-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-icons}}
  \file{local/module-examples/dfg-bib-highlights-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-bib-highlights}}
  \file{local/module-examples/dfg-thumbindex-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-thumbindex}}
  \file{local/module-examples/README.md}{\from{dfg-crc.dtx}{file,example-module-readme}}
  \file{local/module-examples/dfg-plots-example.tex}{\from{dfg-crc.dtx}{file,example-module-plots}}
  \file{local/module-examples/dfg-bib-highlights-example.tex}{\from{dfg-crc.dtx}{file,example-module-bibliography}}
  \file{local/module-examples/dfg-collaboration-example.tex}{\from{dfg-crc.dtx}{file,example-module-collaboration}}
  \file{local/module-examples/dfg-distribution-example.tex}{\from{dfg-crc.dtx}{file,example-module-distribution}}
  \file{local/module-examples/dfg-gantt-example.tex}{\from{dfg-crc.dtx}{file,example-module-gantt}}
  \file{local/module-examples/dfg-icons-example.tex}{\from{dfg-crc.dtx}{file,example-module-icons}}
  \file{local/module-examples/dfg-bib-highlights-example.bib}{\from{dfg-crc.dtx}{file,example-module-references}}
  \file{local/module-examples/dfg-thumbindex-example.tex}{\from{dfg-crc.dtx}{file,example-module-thumbindex}}
  \file{local/module-examples/dfg-timeline-example.tex}{\from{dfg-crc.dtx}{file,example-module-timeline}}
  \file{local/preamble/dfg-customization.tex}{\from{dfg-crc.dtx}{file,custom}}
  \file{local/metadata/dfg-metadata.tex}{\from{dfg-crc.dtx}{file,meta,example-data}}
  \file{local/metadata/dfg-metadata-cv.tex}{\from{dfg-crc.dtx}{file,meta-cv}}
  \file{local/metadata/dfg-metadata-tables.tex}{\from{dfg-crc.dtx}{file,meta-tables}}
  \file{local/test-existing-funds-direct-costs.tex}{\from{dfg-crc.dtx}{file,test-existing-funds-direct-costs}}
  \file{local/test-project-collaboration.tex}{\from{dfg-crc.dtx}{file,test-project-collaboration}}
  \file{local/test-workpackage-references.tex}{\from{dfg-crc.dtx}{file,test-workpackage-references}}
  \file{local/test-workpackage-metadata.tex}{\from{dfg-crc.dtx}{file,test-workpackage-metadata}}
  \file{local/test-reference-lookups.tex}{\from{dfg-crc.dtx}{file,test-reference-lookups}}
  \file{local/test-command-options.tex}{\from{dfg-crc.dtx}{file,test-command-options}}
  \file{local/test-participating-institutions.tex}{\from{dfg-crc.dtx}{file,test-participating-institutions}}
%
% template adjusted below
%
  \file{local/crc-proposal.tex}{\from{dfg-crc.dtx}{file,main}}
  \file{local/dfg-crc-proposal-example.tex}{\from{dfg-crc.dtx}{file,doc-proposal}}
  \file{local/dfg-crc-cv-example.tex}{\from{dfg-crc.dtx}{file,doc-cv}}
  \file{local/crc-cv.tex}{\from{dfg-crc.dtx}{file,cv}}
  \file{local/content/00_titlepage.tex}{\from{dfg-crc.dtx}{file,00}}
  \file{local/content/01_general-information.tex}{\from{dfg-crc.dtx}{file,01}}
  \file{local/content/02_existing-funds-and-requested-funds.tex}{\from{dfg-crc.dtx}{file,02}}
  \file{local/content/03_project.tex}{\from{dfg-crc.dtx}{file,doc-projects}}
  \file{local/content/03_project_research-example.tex}{\from{dfg-crc.dtx}{file,research-example}}
  \file{local/content/03_project_A00.tex}{\from{dfg-crc.dtx}{file,03-project-ending}}
  \file{local/content/03_project_A03.tex}{\from{dfg-crc.dtx}{file,03-project-a03}}
  \file{local/content/03_project_A04.tex}{\from{dfg-crc.dtx}{file,03-project-a04}}
  \file{local/content/03_project_A05.tex}{\from{dfg-crc.dtx}{file,03-project-a05}}
  \file{local/content/03_project_A06.tex}{\from{dfg-crc.dtx}{file,03-project-a06}}
  \file{local/content/03_project_B03.tex}{\from{dfg-crc.dtx}{file,03-project-b03}}
  \file{local/content/03_project_B04.tex}{\from{dfg-crc.dtx}{file,03-project-b04}}
  \file{local/content/03_project_B05.tex}{\from{dfg-crc.dtx}{file,03-project-b05}}
  \file{local/content/03_project_B06.tex}{\from{dfg-crc.dtx}{file,03-project-b06}}
  \file{local/content/03_project_A01.tex}{\from{dfg-crc.dtx}{file,03-project-a01}}
  \file{local/content/03_project_A02.tex}{\from{dfg-crc.dtx}{file,03-project-a02}}
  \file{local/content/03_project_B01.tex}{\from{dfg-crc.dtx}{file,03-project-b01}}
  \file{local/content/03_project_B02.tex}{\from{dfg-crc.dtx}{file,03-project-b02-new}}
  \file{local/content/03_project_Q01.tex}{\from{dfg-crc.dtx}{file,03-project-q01}}
  \file{local/content/03_project_Q02.tex}{\from{dfg-crc.dtx}{file,03-project-q02}}
  \file{local/content/03_project_Q03.tex}{\from{dfg-crc.dtx}{file,03-project-q03}}
  \file{local/content/04_bylaws-of-the-crc.tex}{\from{dfg-crc.dtx}{file,04}}
  \file{local/content/05_declarations.tex}{\from{dfg-crc.dtx}{file,05}}
  \file{local/content/99_backmatter.tex}{\from{dfg-crc.dtx}{file,99}}
}
%</devinstall>
%<install>\nopreamble
%<install>\nopostamble
%<install>\generate{
%<install>  \file{dfg-plots-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-plots}}
%<install>  \file{dfg-collaboration-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-collaboration}}
%<install>  \file{dfg-gantt-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-gantt}}
%<install>  \file{dfg-timeline-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-timeline}}
%<install>  \file{dfg-distribution-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-distribution}}
%<install>  \file{dfg-icons-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-icons}}
%<install>  \file{dfg-bib-highlights-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-bib-highlights}}
%<install>  \file{dfg-thumbindex-options-example.tex}{\from{dfg-crc.dtx}{file,example-options-thumbindex}}
%<install>  \file{dfg-modules.md}{\from{dfg-crc.dtx}{modules-guide}}
%<install>  \file{dfg-module-options.json}{\from{dfg-crc.dtx}{module-option-catalog}}
%<install>  \file{dfg-module-examples.md}{\from{dfg-crc.dtx}{file,example-module-readme}}
%<install>  \file{dfg-build-module-examples.py}{\from{dfg-crc.dtx}{file,build-module-script}}
%<install>  \file{dfg-bib-highlights-example.tex}{\from{dfg-crc.dtx}{file,example-module-bibliography}}
%<install>  \file{dfg-collaboration-example.tex}{\from{dfg-crc.dtx}{file,example-module-collaboration}}
%<install>  \file{dfg-distribution-example.tex}{\from{dfg-crc.dtx}{file,example-module-distribution}}
%<install>  \file{dfg-gantt-example.tex}{\from{dfg-crc.dtx}{file,example-module-gantt}}
%<install>  \file{dfg-icons-example.tex}{\from{dfg-crc.dtx}{file,example-module-icons}}
%<install>  \file{dfg-thumbindex-example.tex}{\from{dfg-crc.dtx}{file,example-module-thumbindex}}
%<install>  \file{dfg-timeline-example.tex}{\from{dfg-crc.dtx}{file,example-module-timeline}}
%<install>  \file{dfg-plots-example.tex}{\from{dfg-crc.dtx}{file,example-module-plots}}
%<install>  \file{dfg-bib-highlights-example.bib}{\from{dfg-crc.dtx}{file,example-module-references}}
%<install>}
%<install|devinstall>\endbatchfile
%<*internal>
\fi
\input docstrip.tex
\keepsilent
\askforoverwritefalse
\nopreamble
\nopostamble
\catcode9=12
\generate{
  \file{\jobname.bib}{\from{\jobname.dtx}{internalbib}}
  \file{\jobname.mst}{\from{\jobname.dtx}{docindex}}
  \file{README.md}{\from{\jobname.dtx}{readme,dev}}
}
\usedir{source/latex/\jobname}
\generate{
  \file{\jobname.ins}{\from{\jobname.dtx}{install}}
  \file{\jobname-dev.ins}{\from{\jobname.dtx}{devinstall}}
}
\ifx\fmtname\nameofplainTeX
  \expandafter\endbatchfile
\else
  \generate{
    \file{\jobname-doc-data.tex}{\from{\jobname.dtx}{file,meta}}
    \file{\jobname-doc-table-a.tex}{\from{\jobname.dtx}{file,doc-table-a}}
    \file{\jobname-doc-table-b.tex}{\from{\jobname.dtx}{file,doc-table-b}}
    \file{\jobname-doc-table-q.tex}{\from{\jobname.dtx}{file,doc-table-q}}
    \file{\jobname-doc-table-pis.tex}{\from{\jobname.dtx}{file,doc-table-pis}}
    \file{\jobname-doc-examples.bib}{\from{\jobname.dtx}{file,bib,base}}
  }
  \expandafter\endgroup
\fi
%</internal>
%<*driver>
\providecommand*\InfoTeX{}
% The developer installer puts the class in local/; the public installer puts
% it beside the DTX. Both builds use the same class and embedded example data.
\makeatletter
\IfFileExists{./local/dfg-crc.cls}
  {\def\dfgDocClass{local/dfg-crc}
   \providecommand*\input@path{}
   \g@addto@macro\input@path{{local/}}}
  {\def\dfgDocClass{dfg-crc}}
\makeatother
\PassOptionsToPackage{hyperindex=false}{hyperref}
\documentclass[documentation=true,english,final=true,twoside=false]{\dfgDocClass}
\usepackage[reportchangedates]{doc}
\usepackage{pdfpages}
\usepackage[export]{adjustbox}
\usepackage{newunicodechar}
\newunicodechar{−}{\ensuremath{-}}
\providecommand{\pkg}[1]{\textsf{#1}}
\usepackage{imakeidx}
\makeindex[options=-s \jobname.mst]
\tcbuselibrary{documentation,listings,breakable,skins}
\setmonofont[
  Ligatures={NoCommon,NoDiscretionary,NoRequired,NoContextual}
]{TeX Gyre Cursor}
\definecolor{codeblue}{RGB}{0,84,159}
\definecolor{codegray}{RGB}{100,100,100}
\definecolor{Definition}{RGB}{0,84,159}
\tcbset{
  index actual={=},index quote={!},index level={>},
  docexample/.add style={}{
    colframe=codeblue,colback=white,breakable,enhanced jigsaw,
    documentation listing options={style=tcbdocumentation,escapeinside={(*}{*)}}
  },
  dfg wide/.style={sidebyside=false,breakable,enhanced jigsaw},
  dfg project/.store in=\dfgDocExampleProject,
}
\newtcblisting[auto counter,number within=chapter]{dfgExample}[2][]{
  enhanced,breakable,colback=white,colframe=codeblue,
  colbacktitle=codeblue,coltitle=white,fonttitle=\bfseries\sffamily,
  title={Example \thetcbcounter: #2},
  title after break={Example \thetcbcounter: #2 (continued)},
  dfg project={},
  listing and text,sidebyside,sidebyside align=top seam,
  lefthand ratio=.48,sidebyside gap=6mm,
  boxrule=.5pt,arc=1mm,left=2mm,right=2mm,top=2mm,bottom=2mm,
  before skip=8pt,after skip=10pt,
  listing options={language={[LaTeX]TeX},basicstyle=\ttfamily\footnotesize,
    breaklines=true,columns=fullflexible,keepspaces=true,showstringspaces=false},
  before lower={\normalfont\normalsize\raggedright\setlength{\textwidth}{\linewidth}\hvFloatSet{nonFloat=true}\dfgDocExampleContext},
  #1
}
\newtcbinputlisting[use counter from=dfgExample]{\dfgTableSetup}[2]{
  enhanced,breakable,colback=white,colframe=codeblue,
  colbacktitle=codeblue,coltitle=white,fonttitle=\bfseries\sffamily,
  title={Example \thetcbcounter: #2},
  title after break={Example \thetcbcounter: #2 (continued)},
  listing only,listing file={\jobname-doc-table-#1.tex},
  boxrule=.5pt,arc=1mm,left=2mm,right=2mm,top=2mm,bottom=2mm,
  before skip=8pt,after skip=10pt,
  listing options={language={[LaTeX]TeX},basicstyle=\ttfamily\footnotesize,
    breaklines=true,columns=fullflexible,keepspaces=true,showstringspaces=false}
}

\IfFileExists{dfg-plots-example.tex}
  {\def\dfgModuleExampleDir{.}}
  {\def\dfgModuleExampleDir{local/module-examples}}
\newtcbinputlisting[use counter from=dfgExample]{\dfgModuleListing}[3]{
  enhanced jigsaw,unbreakable,colback=white,colframe=codeblue,
  colbacktitle=codeblue,coltitle=white,fonttitle=\bfseries\sffamily,
  title={Example \thetcbcounter: #2},
  title after break={Example \thetcbcounter: #2 (continued)},
  label={ex:module-#3},listing only,
  listing file={\dfgModuleExampleDir/#1},
  boxrule=.5pt,arc=1mm,left=2mm,right=2mm,top=2mm,bottom=2mm,
  before skip=8pt,after skip=10pt,
  listing options={language={[LaTeX]TeX},basicstyle=\ttfamily\footnotesize,
    breaklines=true,columns=fullflexible,keepspaces=true,showstringspaces=false}
}
\newcommand*{\dfgModuleCheckPDF}[1]{%
  \IfFileExists{output/module-examples/dfg-#1-example-preview.pdf}{}{%
    \PackageError{dfg-crc documentation}{Package example PDF missing: #1}
      {Run make module-examples before compiling the manual.}%
  }%
}
\newcommand*{\dfgModuleResult}[2]{%
  \dfgModuleCheckPDF{#1}%
  \begin{tcolorbox}[enhanced jigsaw,breakable,colback=white,colframe=codeblue,
    title={Independently compiled result (page #2)},
    colbacktitle=codeblue,coltitle=white,fonttitle=\bfseries\sffamily,
    boxrule=.5pt,arc=1mm,before skip=8pt,after skip=10pt]
    \centering
    \includegraphics[page=#2,max width=\linewidth,max totalheight=.42\textheight]
      {output/module-examples/dfg-#1-example-preview.pdf}
  \end{tcolorbox}%
}
\newcommand*{\dfgModuleThumbResultsFor}[2]{%
  \dfgModuleCheckPDF{#1}%
  \begin{tcolorbox}[enhanced jigsaw,breakable,colback=white,colframe=codeblue,
    title={Independent article pages, left to right},
    colbacktitle=codeblue,coltitle=white,fonttitle=\bfseries\sffamily,
    boxrule=.5pt,arc=1mm,before skip=8pt,after skip=10pt]
    \centering
    \foreach \examplepage [count=\exampleindex] in {#2}{%
      \includegraphics[page=\examplepage,width=.44\linewidth,
        height=.22\textheight,keepaspectratio]
        {output/module-examples/dfg-#1-example-preview.pdf}%
      \ifodd\exampleindex\hfill\else\par\smallskip\fi
    }\par
  \end{tcolorbox}%
}
\newcommand*{\dfgModuleThumbResults}{\dfgModuleThumbResultsFor{thumbindex}{1,2,3,4}}
\makeatletter
\ExplSyntaxOn
\cs_new_protected:Npn \dfgDocExampleContext
  {
    % Example headings show the class typography without changing the manual's
    % section counters, contents, or hyperlink destinations.
    \cs_set_eq:NN \dfgDocSection \section
    \cs_set_eq:NN \dfgDocSubsection \subsection
    \cs_set_eq:NN \dfgDocSubsubsection \subsubsection
    \RenewDocumentCommand \section {s o m} {\dfgDocSection*{##3}}
    \RenewDocumentCommand \subsection {s o m} {\dfgDocSubsection*{##3}}
    \RenewDocumentCommand \subsubsection {s o m} {\dfgDocSubsubsection*{##3}}
    \tl_set:No \l__tmp_current_project_tl {\dfgDocExampleProject}
    \exp_args:NV \__dfg_project_results_prepare:n \l__tmp_current_project_tl
    % hvFloat stores its label before caption packages install their own
    % label command. Prefix that stored label locally for each live example.
    \cs_set_eq:NN \dfgDocOriginalFloatCaption \do@@hvFloat
    \cs_set_protected:Npn \do@@hvFloat [##1]##2##3
      {\dfgDocOriginalFloatCaption[##1]{##2}
        {doc-example-\thetcbcounter-##3}}
  }
\ExplSyntaxOff
\makeatother
% Resolve example-project preview pages by named PDF destinations. This keeps
% the excerpts correct when earlier proposal pages change length.
\directlua{
  local function register_pages(filename, pattern, prefix)
  local pdf = pdfe.open(filename)
  if pdf then
    local pages = {}
    for number, entry in ipairs(pdfe.pagestotable(pdf)) do
      pages[entry[3]] = number
    end
    local function value(entry)
      if entry[1] == 10 then
        local kind, result = pdfe.getfromreference(entry[2])
        return result
      end
      return entry[2]
    end
    local function visit(node)
      local names = pdfe.getarray(node, 'Names')
      if names then
        local entries = pdfe.arraytotable(names)
        for index, entry in ipairs(entries) do
          if math.fmod(index, 2) == 1 then
            local id = value(entry):match(pattern)
            if id then
              local destination = pdfe.getarray(value(entries[index+1]), 'D')
              local page = pages[pdfe.arraytotable(destination)[1][3]]
              if page then
                token.set_macro(prefix .. id, tostring(page), 'global')
              end
            end
          end
        end
      end
      local children = pdfe.getarray(node, 'Kids')
      if children then
        for _, entry in ipairs(pdfe.arraytotable(children)) do visit(value(entry)) end
      end
    end
    local names = pdfe.getdictionary(pdfe.getcatalog(pdf), 'Names')
    if names then
      local destinations = pdfe.getdictionary(names, 'Dests')
      if destinations then visit(destinations) end
    end
    pdfe.close(pdf)
  end
  end
  register_pages('dfg-crc-proposal-example.pdf', '^project:(.+)$', 'dfgDocProjectPage')
  register_pages('dfg-crc-cv-example.pdf', '^doc[-]cv:(.+)$', 'dfgDocCVPage')
}
% Live project references point to the corresponding page of the complete
% proposal imported below; included PDF graphics do not import named targets.
\NewCommandCopy{\dfgDocOriginalHyperlink}{\hyperlink}
\ExplSyntaxOn
\tl_new:N \l__dfg_doc_link_target_tl
\cs_new_protected:Npn \__dfg_doc_hyperlink:nn #1#2
  {
    \str_if_eq:eeTF {\str_range:nnn {#1}{1}{8}} {project:}
      {
        \cs_if_exist:cTF {dfgDocProjectPage\str_range:nnn {#1}{9}{-1}}
          {\use:e {\exp_not:N \dfgDocOriginalHyperlink
            {example-proposal.\use:c {dfgDocProjectPage\str_range:nnn {#1}{9}{-1}}}
            {\exp_not:n {#2}}}}
          {\dfgDocOriginalHyperlink{#1}{#2}}
      }
      {\dfgDocOriginalHyperlink{#1}{#2}}
  }
\RenewDocumentCommand \hyperlink {mm}
  {
    \group_begin:
    \tl_set:Ne \l__dfg_doc_link_target_tl {#1}
    \exp_args:NV \__dfg_doc_hyperlink:nn \l__dfg_doc_link_target_tl {#2}
    \group_end:
  }
\ExplSyntaxOff
\newcommand*{\dfgDocProjectExcerpt}[2]{%
  \ifcsname dfgDocProjectPage#1\endcsname
    \includegraphics[page=\csname dfgDocProjectPage#1\endcsname,
      trim=25mm #2 15mm 17mm,clip,width=\linewidth]{dfg-crc-proposal-example.pdf}%
  \else
    \PackageError{dfg-crc documentation}{Missing example project destination #1}
      {Rebuild the standalone example proposal with make proposal-doc-example.}%
  \fi
}

\newcommand*{\dfgDocCVExcerpt}[1]{%
  \ifcsname dfgDocCVPage#1\endcsname
    \centering
    \includegraphics[page=\csname dfgDocCVPage#1\endcsname,
      width=\linewidth,height=.65\textheight,keepaspectratio]{dfg-crc-cv-example.pdf}%
  \else
    \PackageError{dfg-crc documentation}{Missing example CV destination #1}
      {Run make cv-doc-example before compiling the manual.}%
  \fi
}
\newcommand*{\dfgExampleRef}[1]{\hyperref[#1]{Example~\ref*{#1}}}
% Keep the manual's labels outside each reduced, framed example page.
\newcommand*{\dfgDocImportedPage}[1]{%
  \thispagestyle{empty}%
  \begin{tikzpicture}[remember picture,overlay]
    \node[anchor=north,font=\small\sffamily\bfseries,text=codeblue]
      at ([yshift=-12mm]current page.north)
      {#1\enspace\textperiodcentered\enspace separate document};
    \node[anchor=south,font=\small\sffamily,text=codegray]
      at ([yshift=10mm]current page.south)
      {Manual page \thepage};
  \end{tikzpicture}%
}
\NewDocumentCommand{\dfgFile}{m}{\texttt{#1.tex}}
\changeSettings{thumbindex=false,doiAPIMail={}}
\input{\jobname-doc-data.tex}
\addbibresource{\jobname.bib}
\addbibresource{\jobname-doc-examples.bib}
\def\MacroFont{\ttfamily\scriptsize}
\let\AltMacroFont\MacroFont
\AtBeginDocument{
  \MakeShortVerb{\|}
  \def\theCodelineNo{\color{codegray}\scriptsize\arabic{CodelineNo}\space}
  \CodelineNumbered\DisableCrossrefs\RecordChanges
  \setlength{\hfuzz}{2pt}
  \setlength{\emergencystretch}{3em}
  \RedeclareSectionCommands[beforeskip=2ex,afterskip=1ex]{section,subsection,subsubsection}
  \ihead{\texttt{dfg-crc} \dfgVersion}\ohead{\headmark}
  \ifoot*{}\cfoot*{}\ofoot*{\pagemark}
}
\crefformat{lstlisting}{#2example\ #1#3}
\Crefformat{lstlisting}{#2Example #1#3}
\crefmultiformat{lstlisting}{#2examples #1#3}{; #2#1#3}{; #2#1#3}{; #2#1#3}
\Crefmultiformat{lstlisting}{#2Examples #1#3}{; #2#1#3}{; #2#1#3}{; #2#1#3}
\Crefrangeformat{lstlisting}{#3Examples #1#4--#5#2#6}
\crefrangeformat{lstlisting}{#3examples #1#4--#5#2#6}
\author{Lukas C. Bossert\\\href{mailto:bossert@itc.rwth-aachen.de}{bossert@itc.rwth-aachen.de}}
\title{\texttt{dfg-crc} and reusable LaTeX packages\\User guide and implementation}
\date{Version \dfgVersion\quad\dfgVersionDate}
\begin{document}
\hypersetup{pdftitle={dfg-crc and reusable LaTeX packages: user guide and implementation},
  pdfauthor={Lukas C. Bossert},pdfsubject={dfg-crc documentation}}
\frontmatter
\maketitle
\chapter*{About this manual}
Start with Part~\ref{part:proposal-class} for the proposal and CV user guide.
The implementation reference follows. Independent packages are documented
in the final part, Part~\ref{part:independent-packages}: each package has a
complete example file and output compiled independently of the proposal class.

The manual itself uses \texttt{dfg-crc}. Its class examples execute with the
fictional metadata embedded in the DTX: source is shown beside the result,
or above it for wide tables and plots. Independent package examples are
compiled as their own standard-class documents and then included as PDFs.

Setup fragments, shell commands, and companion data files are shown as code. Complete proposal and CV examples follow the user guide, before the
implementation reference; see Chapters~\ref{chap:complete-example-proposal}
and~\ref{chap:complete-example-cv}.

\blockcquote[195]{Hoare1973}{Documentation must be regarded as an integral part of the process of design and coding.}

Built with \InfoTeX.
\tableofcontents
\mainmatter
\part{The proposal and CV class}
\label{part:proposal-class}
\chapter{Shared commands and first steps}
The \texttt{dfg-crc} class is a starting point for a Collaborative Research
Centre proposal and the accompanying CV section.  Authors write the proposal
chapters and maintain structured records for people, institutions, projects,
work packages, and funding.  The class uses those records to create project
headings, references, tables, collaboration plots, Gantt charts, and totals
that stay consistent across the document.

The supplied files include a complete example proposal, example CV, and
customization file.  Start with the generated examples to see how the source
files fit together, then replace their content and metadata with those of your
own centre.  This chapter introduces the commands reused throughout the proposal.
Chapter~\ref{chap:proposal-walkthrough} then follows the proposal itself;
Chapter~\ref{chap:manual-reference} collects the complete key and settings reference.  Applicants should still compare the result
with the current DFG forms and programme rules.

For independent use of the package components, begin with
Part~\ref{part:independent-packages}. The class already loads them and
supplies the proposal metadata adapters described in this part.

\section{Compiling and generated files}

The maintained source of this bundle is
\texttt{dfg-crc.dtx}.  Files such as
\texttt{local/dfg-crc.cls}, \texttt{README.md}, and
the example files in \texttt{local/} are generated from that source.  For
template or documentation changes, edit the |.dtx| file and regenerate the
derived files.

For a first local compile, use LuaLaTeX through \texttt{latexmk}:
\begin{dispListing*}{title={First local compile}}
make files
cd local
latexmk -lualatex crc-proposal.tex
latexmk -lualatex crc-cv.tex
\end{dispListing*}

The class expects LuaLaTeX.  Calling \texttt{LaTeX} with a capital \texttt{L}
asks TeX for a format file named \texttt{LaTeX.fmt}; use \texttt{lualatex} or
\texttt{latexmk -lualatex} instead.

If a change has no visible effect, check which generated class file is being
loaded.  Regenerate the class and local examples with \texttt{make files}, then
compile the relevant example again.

To update a separately controlled proposal worktree, use
\texttt{make update-class TARGET\_DIR=/path/to/proposal-worktree} for the class
alone.  Use \texttt{make update-all TARGET\_DIR=/path/to/proposal-worktree} to
rebuild the manual and copy \texttt{dfg-crc.cls}, its module packages,
\texttt{dfg-crc.pdf}, \texttt{dfg-crc-proposal-example.pdf}, and
\texttt{dfg-crc-cv-example.pdf}.  Both targets require the
destination to be the root of another Git worktree and report the affected
files without committing or pushing them.  They leave the destination's
README, changelog, and licence unchanged.

\subsection{Automatic metadata caches}

Ordinary and final builds automatically reuse raw metadata rows for repeated
PI and project references and for generated tables. The project-leader table
prefetches the person, project, institution, and affiliation rows before its
repeated width measurements. Position and gender counts are retained for each
requested funding phase, and PI surnames and initials are indexed for name
disambiguation. These optimizations require no class option.

For predictable compile times, keep static metadata as plain text and
apply presentation settings at the output location. Do not insert formatting
macros such as \cs{mbox}, \cs{textbf} or \cs{emph} into IDs, person names or
roles merely to control their appearance in a table. Use
|firstname={Verena}| and configure alignment, emphasis and hyphenation in the
table or reference formatting instead. Presentation macros in these fields
can force the expensive original lookup on every use.

The caches check the stored database and column definitions before reuse;
additions, edits, sorting, and locally scoped data changes are detected
automatically. Field values remain unexpanded, so formatting, reference colors,
first-name preferences, hyperlinks, and provenance tags follow the settings at
the output location. Macro-valued names and roles use the original
name-disambiguation scan. This fallback applies to the whole person database:
even a formatting command such as |firstname={\mbox{Verena}}| disables the
surname/initial index for every PI reference. Keep static names as plain text
and control wrapping in the table layout instead. Nonliteral IDs, searches by other columns, and
unsupported Datatool map readers use the original row lookup. Normal LaTeX
reruns are still required when cross-references change.

\section{How to read the examples}
The examples use the same class commands as a proposal. In the template data,
\texttt{per1} is Kim Sample, \texttt{per2} is Alex Example, and \texttt{A01}
is their shared project. The manual has twelve PIs and fifteen active projects:
|A01|--|A06|, |B01|--|B06|, and |Q01|--|Q03|. Research projects include both
continuing and new projects; Q projects demonstrate service, research training,
and administration. |A00| is a former, reference-only project and is excluded
from active counts. Outputs are compiled from the displayed source.

Small examples place code beside its result; wide examples put the result below
and allow it to continue onto another page. Headings inside live examples are
unnumbered so they do not change the manual's outline. The complete shared metadata are
listed once in Section~\ref{sec:manual-fixtures}. Finance examples show their
additional input records at the point of use. Optional settings normally go
immediately after the command, before its required arguments.

\section{Declare records with \texorpdfstring{\cs{addEntry}}{addEntry}}
Keep static field values as plain data wherever possible. In particular,
IDs, person names and roles should contain no presentation macros; configure
their typography in the output commands or table settings. Macro-valued
identity fields can disable metadata indexes and substantially increase the
runtime of every compilation pass; see the automatic-cache guidance above.

\begin{docCommand}{addEntry}{\oarg{key-set}\marg{database}\marg{key=value}}
  Adds an entry to the database \meta{database} with the defined
  values from \meta{key=value}.  An |id| is unique within its database.  If a
  later call reuses the same |id|, the class issues a warning, removes all
  earlier rows with that |id|, and stores the later entry instead.  The same
  |id| may still be used in a different database.  Entries without an |id|,
  such as ordinary funding and staff rows, remain append-only.

  See \dfgExampleRef{ex:manual-declare-a-record-and-retrieve-its-fields}, \dfgExampleRef{ex:manual-requested-funding-for-a-project}.
\end{docCommand}

A keyset defines the accepted fields; a database stores the resulting rows.
Omit the optional keyset when it has the same name as the database, for
example |\addEntry{person}{...}|. Give it explicitly for a separate collection,
as below. Braces protect commas inside values. Use stable IDs rather than
repeating names in the prose.

\begin{dfgExample}[label={ex:manual-declare-a-record-and-retrieve-its-fields}]{Declare a record and retrieve its fields}
\addEntry[person]{ManualContacts}{
  id        = {example-contact},
  firstname = {Kim},
  lastname  = {Sample}
}
\getEntry[ManualContacts]{example-contact}{firstname}\space
\getEntry[ManualContacts]{example-contact}{lastname}
\end{dfgExample}

Store proposal records in |metadata/dfg-metadata.tex|, or in another metadata
file loaded by the proposal. Tables share those records. The standard databases
are |meta| (the CRC), |person|, |project|, |institution|, and |affiliation|;
funding and staff tables use the named collections introduced with each table.
Full field definitions are in Section~\ref{doc:metadata}.

\section{Read, store, and compare fields}
You can get any kind of information back from any database using \refCom{getEntry}:
\begin{docCommand}{getEntry}{\oarg{database}\marg{value of
      id}\marg{column}\oarg{alternative id-field}}
  Retrieve and typeset the value of \meta{column} from the row whose
  id-cell equals \meta{value of id}.

  The optional \meta{database} argument selects the \refPkg{datatool}
  database to query; it defaults to \cs{tmpLocalDB}, which is set by
  the surrounding context (typically by the table-generating command).
  The optional \meta{alternative id-field} argument names the column
  that holds the row identifier and defaults to \texttt{id}; supply a
  different name when the row is keyed on something other than the
  standard id column (for example \texttt{ref-project-id} or
  \texttt{number}).

  The retrieved value is wrapped in \cs{dfgShowTag} before being
  typeset, so when the \refKey{showtags} class option is active the
  output is annotated with a small overlay marker showing the
  originating database, id, and column.  When the option is inactive,
  the value is typeset plain.

  The command performs several checks and emits a warning to the log
  when something is wrong: a \texttt{database-name-not-given} warning
  if \meta{database} is empty, a \texttt{database-not-found} warning
  if no database with the given name exists, and a \texttt{missing-key}
  warning if the row exists but the requested cell is empty or
  undefined.  The last warning is suppressed during \refPkg{tabularray}'s
  measuring phase to avoid duplicate log entries.

  When the \texttt{fastcompile-project} class option is active, the lookup is
  skipped entirely.  Project identifiers are typeset in bold black; other
  row identifiers use a quiet grey placeholder.  Error diagnostics retain
  the configured \texttt{error} colour.  Starred multi-field lookups initialise their destination
  macros to empty values without touching a database.

  \medskip
  Examples:
  \begin{dfgExample}[label={ex:manual-field-lookup-and-alternative-identifier}]{Field lookup and alternative identifier}
\getEntry[person]{per9}{lastname}\par
\getEntry[project]{A06}{name}[number]\par
\def\tmpLocalDB{person}
\getEntry{per9}{firstname}
\end{dfgExample}


  When several columns from the same row are needed, prefer the starred
  form \refCom{getEntry*}, which performs only a single row lookup.

  See \dfgExampleRef{ex:manual-field-lookup-and-alternative-identifier}.
\end{docCommand}

\begin{docCommand}{getEntry*}{\oarg{database}\marg{value of
      id}\marg{assignments}\oarg{alternative id-field}}
  Starred variant of \cs{getEntry}.  Retrieves multiple columns from the
  same row in a single lookup and assigns each value to the macro named
  on the left-hand side of the assignment.

  The \meta{assignments} argument is a comma-separated list of
  \meta{\textbackslash macro}\,\texttt{=}\,\meta{column} pairs.  For each
  pair, the value of \meta{column} for the row whose id-cell equals
  \meta{value of id} is stored in \meta{\textbackslash macro}.  Unlike
  the unstarred form, this variant does not print anything and does not
  wrap results in \cs{dfgShowTag} -- the caller is responsible for
  formatting the retrieved values.

  Missing fields trigger the same \texttt{missing-key} warning as the
  unstarred form (suppressed during \pkg{tabularray}'s measuring phase).

  \medskip
  Example:
  \begin{dfgExample}[label={ex:manual-retrieve-several-fields-at-once}]{Retrieve several fields at once}
\getEntry*[person]{per8}{
  \exampleFirst = firstname,
  \exampleLast = lastname,
  \exampleDegree = academicdegree
}
\exampleDegree\space
\exampleFirst\space\exampleLast
\end{dfgExample}
  This is preferable over multiple \cs{getEntry} calls when several
  fields from the same row are needed: the row is located once instead
  of once per field.

  See \dfgExampleRef{ex:manual-retrieve-several-fields-at-once}.
\end{docCommand}

\begin{docCommand}{tmpLocalDB}{\marg{database}}
  Define the database locally (e.g. within a group) so you don't need to repeat it
  as \oarg{database} for e.g. \refCom{getEntry}.

  See \dfgExampleRef{ex:manual-field-lookup-and-alternative-identifier}.
\end{docCommand}


\begin{docCommand}{compareEntry}{\oarg{database}\marg{id}\marg{field}\marg{value}
    \marg{true}\marg{false}}
  Compare an entry with the \meta{id} of \meta{database} against \meta{value}
  and show either \meta{true} or \meta{false}.

  See \dfgExampleRef{ex:manual-compare-a-database-entry-against-something}, \dfgExampleRef{ex:manual-conditionally-print-an-affiliation}.
\end{docCommand}

For example, compare the surname of |per6| against an expected value.

\begin{dfgExample}[label={ex:manual-compare-a-database-entry-against-something}]{Compare a database entry against something.}
\compareEntry[person]{per6}{lastname}{Hartmann}
  {The surname matches.}{The surname differs.}
\end{dfgExample}

The next example prints an affiliation only when the institution refers to it.
\begin{dfgExample}[label={ex:manual-conditionally-print-an-affiliation}]{Conditionally print an affiliation}
\compareEntry[institution]{ins3}{ref-affiliation-id}{aff3}
  {\getEntry[affiliation]{aff3}{name}}
  {Another university}
\end{dfgExample}

\section{Follow references between records}
A |ref-institution-id| value links a person to institutions; each institution's
|ref-affiliation-id| links it to a university or other parent organisation.
Use one brace argument per step, ending with the field to print. Multiple IDs
are followed automatically, so prose stays correct when affiliations change.

\begin{docCommand}{get}{\oarg{database}\marg{id}\marg{field or reference}\ldots}
  Read a field directly, or follow metadata references before reading the
  final field. Each intermediate argument names a destination database and
  follows the current row's |ref-<database>-id| field. The source database
  defaults to \cs{tmpLocalDB}. No institution or affiliation ID needs to be
  repeated in the document text.

  \begin{dfgExample}[label={ex:manual-follow-metadata-references}]{Follow metadata references}
\get[person]{per7}{lastname}\par
\get[person]{per7}{institution}{name}\par
\get[person]{per7}{institution}{affiliation}{name}\par
\get[project]{B04}{person}{lastname}\par
\get[RequestedFundingStaff]{per6}{person}[ref-person-id]{institution}{name}
\end{dfgExample}

  The full reference-key spelling also works:
  |\get[person]{MM}{ref-institution-id}{ref-affiliation-id}{name}|.
  Traversal is generic: a |ref-other-unit-id| field points to rows of the
  |other-unit| database. The source may be any database populated by
  \refCom{addEntry}, including one using a separately named keyset. Each
  destination is matched by its |id| field. The lookup follows only the
  explicitly requested path; an affiliation reached through an institution
  therefore needs both steps.

  A reference value may contain multiple comma-separated IDs. All branches
  are followed in stored order, and the resulting values are separated by
  commas. Repeated destination rows are printed once, in first-occurrence
  order. For example, two institutions of one university yield two institution
  names but only one affiliation name when the path ends at that university.
  Different rows with the same name are still distinct results.

  Missing databases, rows, fields, and empty reference lists use the existing
  lookup warnings and contribute no value; valid branches still render without
  dangling separators. The final value retains its LaTeX formatting and the
  \refKey{showtags} annotation identifies the destination row and field.
  Focused fast compilation consumes the path but prints the source ID
  placeholder, just like \refCom{getEntry}.

  With no following step, a full reference key returns its raw ID list:
  |\get[person]{MM}{ref-institution-id}|. An existing scalar field takes
  precedence over a shorthand relation name, so a following prose group is
  not absorbed. Use the explicit |ref-<database>-id| spelling if the names
  conflict. For a custom source identifier column, append the existing
  |[id-field]| argument after the first field/reference argument; destination
  rows still use |id|. The starred |\get*| form delegates to
  \refCom{getEntry*} for assignments and does not traverse references.

  See \dfgExampleRef{ex:manual-follow-metadata-references}, \dfgExampleRef{ex:manual-raw-reference-ids-and-resolved-organisation-names}.
\end{docCommand}

Two institution IDs may lead to the same affiliation. The final destination
is printed once, so this also works when a person's metadata changes later.
\begin{dfgExample}[label={ex:manual-raw-reference-ids-and-resolved-organisation-names}]{Raw reference IDs and resolved organisation names}
IDs: \get[person]{per7}{ref-institution-id}\par
Institutions: \get[person]{per7}{institution}{name}\par
Affiliation:
\get[person]{per7}{institution}{affiliation}{name}
\end{dfgExample}

A lookup may branch at several steps: from a project to its PIs, then to their
institutions and affiliations. Shared affiliations are still deduplicated.
\begin{dfgExample}[label={ex:manual-find-the-affiliations-behind-a-project}]{Find the affiliations behind a project}
\getProject*{B04}\par
PIs: \get[project]{B04}{person}{lastname}\par
Affiliations:
\get[project]{B04}{person}{institution}{affiliation}{name}
\end{dfgExample}

\section{Names and references in prose}
To quickly get a name of a person there is a dedicated command:
\begin{docCommand}{getName}{\marg{<id>}}
  Get last name of person that has the \meta{id}.
  This sets the database to \texttt{person}.

  See \dfgExampleRef{ex:manual-names-with-and-without-academic-titles}.
\end{docCommand}

\begin{docCommands}[
    doc name = getFullName
  ]{
    {doc parameter = \sarg\marg{id}},
    {doc parameter = \marg{id}}
  }
  Get the full name of the person with the \meta{id}.
  The starred version adds the academic title in front.

  See \dfgExampleRef{ex:manual-names-with-and-without-academic-titles}.
\end{docCommands}

\begin{dfgExample}[label={ex:manual-names-with-and-without-academic-titles}]{Names with and without academic titles}
\getName{per9}\par
\getFullName{per9}\par
\getFullName*{per9}
\end{dfgExample}

PI and project commands also have all-lowercase aliases, with identical
arguments, starred forms, formatting, and links. For example,
|\getpiwithproject{per6}| is equivalent to |\getPIWithProject{per6}|, and
|\getpiofproject*{B05}| is equivalent to |\getPIofProject*{B05}|.
This also applies to |\getPI|, |\getPIsWithRole|, |\getProject|,
|\getProjectColor|, |\getProjectCount|, |\getProjectWithPI|,
|\getPIOfProjectWithProject|, and the legacy commands |\getPIProject| and
|\getProjectPI|. Legacy aliases share the same once-per-command, per-LaTeX-run deprecation
warning as their canonical spelling.
The mixed spellings |\getPIwithProject|, |\getProjectwithPI|, and
|\getPIOfProject| are accepted as well. Other capitalizations remain
case-sensitive in TeX.

\begin{docCommands}[
    doc name = getPI
  ]{
    {doc parameter = \sarg\marg{id-list}},
    {doc parameter = \marg{id-list}},
    {doc parameter = \marg{id-list}\oarg{text}}
  }
  Reference one or multiple PIs from the \texttt{person} database.  The
  \meta{id-list} is a comma-separated list of person ids.  By default the
  command prints the lastname; the starred version also prints the firstname.
  If multiple PI records share a lastname, unstarred references automatically
  add the first given-name initial. For example, PI records for Kai Markus
  Schneider and Carolin V. Schneider are printed as \textbf{K.~Schneider} and
  \textbf{C.~Schneider}. If the initial is also shared, the full firstname is
  used instead. The comparison includes all records with role \texttt{PI} or
  \texttt{Co-PI}, independently of funding period or project selection.
  Project-first references inherit this distinction, for example
  \textbf{A04 (K.~Schneider)} and \textbf{B09 (C.~Schneider)}.
  With the optional \meta{text} argument, \meta{text} is printed instead, but
  the hyperlink still points to the PI.
  Set \texttt{PIReferenceFirstName=true} with \refCom{changeSettings} to make
  the unstarred command include the firstname too. The starred form always
  includes it. This setting also applies to \refCom{getPIProject} and
  \refCom{getPIofProject}. \refCom{getProjectPI} keeps project PI names to
  lastnames with automatic disambiguation unless its starred form is used.
  Shared PI surnames use the initial rule even with
  \texttt{PIReferenceFirstName=true}; use the star to force full firstnames.
  Explicit display text bypasses automatic disambiguation. Fast project
  compilation retains the usual ID placeholder without reading the database.

  The printed name is typeset bold, coloured with \texttt{referencePI}, and
  linked to the corresponding person's row in
  \cs{printTable}|{ProjectLeaders}|.  Each row of that table provides the
  destination \texttt{pi:}\meta{id}.

  See \dfgExampleRef{ex:manual-reference-one-or-multiple-pis}.
\end{docCommands}

\hypertarget{pi:spokesperson}{}% Example-only person has no project-head anchor.
\begin{dfgExample}[label={ex:manual-reference-one-or-multiple-pis}]{Reference one or multiple PIs.}
\getPI{per6}\par
\getPI*{per6,per8}\par
\getPI{spokesperson}[the spokesperson]
\end{dfgExample}

\begin{docCommand}{getProject}{\sarg\marg{id-list}\oarg{text}}
  Reference one or multiple projects from the \texttt{project} database.  The
  \meta{id-list} is a comma-separated list of project ids.  By default the
  command prints the project number; with the optional \meta{text} argument,
  \meta{text} is printed instead, but the hyperlink still points to the
  project.  In CV mode the command prints the same text without a hyperlink.
  The starred form always uses this compact project-only representation,
  independently of \refKey{projectPIOncePerSection} and its first-reference
  state.
  Projects declared with \refKey{reference-only}|=true| are never hyperlinked;
  instead, \enquote{former project} is appended to make the missing project
  section explicit.

  The printed project reference is typeset bold and coloured according to the
  first letter of the project id. Multiple project references are joined as a
  natural-language list with commas and a final \enquote{and}. With
  \refKey{projectPIOncePerSection}|=true|, the command behaves like the
  unstarred \refCom{getProjectPI}: the first reference to each project in a
  section includes its PIs and later references use the compact project form.
  Generated tables and lists remain compact.

  See \dfgExampleRef{ex:manual-reference-one-or-multiple-projects}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-reference-one-or-multiple-projects}]{Reference one or multiple projects.}
\changeSettings{projectPIOncePerSection=false}
\getProject{A03,B04,Q01}\par
\getProject{A06}[the modelling project]\par
\getProject*{A00}
\end{dfgExample}

\begin{docCommand}{getProjectCount}{\oarg{area}}
  Print the number of active projects.  A project is active when its
  \refKey{project-status} is \texttt{C} or \texttt{N} and
  \refKey{consider-for-lists} is \texttt{true} and
  \refKey{reference-only} is \texttt{false}.  With no optional argument all
  active projects are counted.  Any explicit \refKey{project-area} value may
  be supplied to restrict the result; where that metadata is absent, the first
  character of the project ID is used.  All area totals are computed together
  on first use and cached for subsequent calls.

  See \dfgExampleRef{ex:manual-count-active-projects}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-count-active-projects}]{Count active projects.}
All: \getProjectCount\par
Area A: \getProjectCount[A]\par
Area B: \getProjectCount[B]\par
Area Q: \getProjectCount[Q]
\end{dfgExample}

\begin{docCommands}[
    doc name = CRC
  ]{
    {doc parameter = \marg{crc-number}},
    {doc parameter = \sarg\marg{crc-number}},
    {doc parameter = \sarg\oarg{crc-title}\marg{crc-number}}
  }
  Print a CRC reference.  For the current CRC, identified by the
  \refKey{number} field of the \texttt{meta} entry with id \texttt{crc},
  the unstarred command prints the short form stored in \cs{thisCRC}; the
  starred command prints the long form with the CRC title.

  For a different CRC number, the unstarred command prints only the short
  reference, while the starred form prints a long reference.  If
  \meta{crc-title} is given, it is used as the title of the external CRC;
  otherwise the command falls back to the CRC number.

  See \dfgExampleRef{ex:manual-reference-current-and-external-crcs}.
\end{docCommands}

\begin{docCommands}[
    doc name = TRR
  ]{
    {doc parameter = \marg{trr-number}},
    {doc parameter = \sarg\marg{trr-number}},
    {doc parameter = \sarg\oarg{trr-title}\marg{trr-number}}
  }
  Print a CRC/TRR reference.  The command follows the same rules as
  \refCom{CRC}, but uses \enquote{CRC/TRR} as the printed programme
  type.
  A line break is permitted after the slash; the TRR abbreviation and
  programme number remain together.

  See \dfgExampleRef{ex:manual-reference-current-and-external-crcs}.
\end{docCommands}

\begin{dfgExample}[label={ex:manual-reference-current-and-external-crcs}]{Reference current and external CRCs.}
\CRC{9999}\par
\CRC*{9999}\par
\CRC*[External CRC title]{999}\par
\TRR*[External CRC/TRR title]{999}
\end{dfgExample}

\begin{docCommands}[
    doc name = getPIProject
  ]{
    {doc parameter = \sarg\marg{person-id-list}},
    {doc parameter = \marg{person-id-list}}
  }
  Print one or multiple PIs together with their assigned projects.  The
  \meta{person-id-list} is a comma-separated list of ids from the
  \texttt{person} database.  For each PI, the command reads
  \refKey{ref-project-id} from the person entry and prints the referenced
  project identifiers in parentheses using \cs{getProject}|*|, without
  repeating the projects' PI names.

  The starred version prints firstnames in addition to lastnames.

  See \dfgExampleRef{ex:manual-print-pis-with-their-projects}.
\end{docCommands}

\begin{dfgExample}[label={ex:manual-print-pis-with-their-projects}]{Print PIs with their projects.}
\changeSettings{projectPIOncePerSection=false}
\getPIProject{per6,per11}\par\medskip
\getPIProject*{per6,per11}
\end{dfgExample}

Use \cs{getPIWithProject} for the same person-first output. It takes person
ids and prints each PI followed by their project list. The legacy
\cs{getPIProject} remains available but warns that it is deprecated.

\begin{docCommands}[
    doc name = getProjectPI
  ]{
    {doc parameter = \sarg\marg{project-id-list}},
    {doc parameter = \marg{project-id-list}}
  }
  Print one or multiple projects together with their assigned PIs.  The
  \meta{project-id-list} is a comma-separated list of ids from the
  \texttt{project} database.  For each project, the command reads
  \refKey{ref-person-id} from the project entry and prints the referenced PIs
  in parentheses using \refCom{getPI}.

  If a project id is identical to the current project established by
  \refCom{printProjectHead}, only the project itself is printed, just as with
  \refCom{getProject}; its PIs are omitted.  In a list containing several
  projects, this exception applies only to the matching project.

  By default, PI names are shown only for the first \refCom{getProject} or
  \refCom{getProjectPI} reference to each project within a section. Both
  commands share the same remembered state, and a new section resets it.
  Generated tables and lists remain compact. Set
  \refKey{projectPIOncePerSection}|=false| with \refCom{changeSettings} to make
  \refCom{getProject} always compact and \refCom{getProjectPI} always expanded.

  The starred version prints firstnames in addition to lastnames.

  See \dfgExampleRef{ex:manual-print-projects-with-their-pis}.
\end{docCommands}

\begin{dfgExample}[label={ex:manual-print-projects-with-their-pis}]{Print projects with their PIs.}
\changeSettings{projectPIOncePerSection=false}
\getProjectPI{A03,B04}\par\medskip
\getProjectPI*{A03,B04}
\end{dfgExample}

Use \cs{getProjectWithPI} for the same project-first output. It takes project
ids and prints each project followed by its PI list. The legacy
\cs{getProjectPI} remains available but warns that it is deprecated.

\begin{docCommand}{getPIOfProjectWithProject}{\sarg\marg{project-id-list}}
  Print the PIs of one or more projects, followed by each project's compact
  reference in parentheses. The argument is a comma-separated list of project
  ids, matching the project named after \enquote{OfProject} in the command.
  The starred form includes firstnames; the
  \texttt{PIReferenceFirstName=true} setting also enables firstnames in the
  unstarred form.
\end{docCommand}

\begin{docCommand}{getPIofProject}{\sarg\oarg{properties}\marg{project-id}\oarg{delimiter}}
  Print the PIs assigned to a project.  The command reads
  \refKey{ref-person-id} from the project entry and then prints selected
  person fields from the \texttt{person} database. Each name links to its row
  in the PI table and uses the same reference styling as \refCom{getPI}. The optional
  \meta{properties} argument is a comma-separated list of fields to print and
  defaults to \texttt{lastname}.  Typical values are
  \texttt{academicdegree}, \texttt{firstname}, and \texttt{lastname}.  The
  optional \meta{delimiter} separates multiple PIs and defaults to |\,/\,|.

  The starred form defaults to |firstname,lastname| and joins names as
  ``Alice Example, Bob Sample and Carol Demo''. With two PIs it uses only
  ``and''; with one PI it adds no separator. Explicit properties still override
  the default. In the starred form, an explicit trailing delimiter replaces
  only the final ``and'' separator; earlier names remain comma-separated.

  See \dfgExampleRef{ex:manual-print-the-pis-of-a-project}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-print-the-pis-of-a-project}]{Print the PIs of a project.}
\getPIofProject{B05}\par
\getPIofProject[firstname,lastname]{B05}[; ]\par
\getPIofProject*{Q02}\par
\getPIofProject*{Q03}\par
\getPIofProject*[lastname]{Q03}
\end{dfgExample}

\section{Change shared settings}
\begin{docCommand}{changeSettings}{\marg{key=value}}
  Customize fonts, logo paths, colors, \refKey{thumbindex}, and other class
  defaults.  The former \cs{changeSetting} spelling remains available as a
  compatibility alias.

  See \dfgExampleRef{ex:manual-set-proposal-text-in-the-customization-file}.
\end{docCommand}
Put proposal-wide settings in |preamble/dfg-customization.tex|. For example,
|\changeSettings{salary@PhD=83700}| sets the annual salary used in funding
calculations. Table, list, and plot options apply to a single call; shared
settings establish defaults. The full list is in Section~\ref{doc:customization}.

\begin{docCommand}{getValue}{\marg{customization key}}
  Read the current value of any key accepted by \refCom{changeSettings}.
  The command is expandable and follows local changes, so numeric values can
  also be used in \cs{num} and calculations. For example:
\begin{dispListing*}{title={Using customization values in text}}
Housing costs are \num{\getValue{animalHousing@mouse}}\,EUR per mouse per week.
The annual postdoctoral rate is \num{\getValue{salary@postDoc}}\,EUR.
The configured font is \getValue{font}.
Thumb index enabled: \getValue{thumbindex}.
The reference color is \getValue{color@reference@PI}.
\end{dispListing*}
  These examples read the configured values without changing them. With no
  override, \texttt{animalHousing@mouse} returns \texttt{0.75}; the getter
  uses the same stored rate as the animal-housing table. It returns a value
  without a currency or unit suffix; add those in the surrounding text.

  Booleans return \texttt{true} or \texttt{false}; dimensions return points.
  Automatic thumb-index margins return \texttt{auto}, and orientation returns
  \texttt{inwards} or \texttt{outwards}. Text and formatting values retain their
  LaTeX commands. The compatibility keys \texttt{biblatexstyle} and
  \texttt{biblatexstyleFeature} read the current document mode's CV or proposal
  setting. Leading and trailing spaces around a key are ignored; unknown keys
  raise an error. This interface covers customization keys, not arbitrary
  commands or packages defined in the customization file.
\end{docCommand}

\begin{docKeys}[doc parameter={=\meta{text}}]{
  {doc name=dfgLocation}, {doc name=dfgDate},
  {doc name=dfgTitle}, {doc name=InfoTeX}
}
  Override the matching public commands through \cs{changeSettings}, including
  from |preamble/dfg-customization.tex|. The defaults are |<Location>|,
  |<date>|, the quoted CRC name from metadata, and |LuaLaTeX (via Overleaf).|,
  respectively. The first three commands append \cs{xspace}; |InfoTeX| prints
  its value exactly. Values are stored without expansion, so references and
  formatting can be used in them. No fixed submission date is supplied.
  See \dfgExampleRef{ex:manual-set-proposal-text-in-the-customization-file}.
\end{docKeys}

\begin{dfgExample}[label={ex:manual-set-proposal-text-in-the-customization-file}]{Set proposal text in the customization file}
\changeSettings{
  dfgLocation = {Example City},
  dfgDate     = {30 September 2026},
  dfgTitle    = {Collaborative research programme},
  InfoTeX    = {LuaLaTeX, local build}
}
\dfgTitle\par
\dfgLocation, \dfgDate\par
\InfoTeX
\end{dfgExample}

These macros already exist when the customization file is read, so direct
overrides with \cs{renewcommand} work there too. For the three
space-aware commands, include |\xspace| yourself when using |\renewcommand|.
Definitions supplied before loading the class are preserved until explicitly
overridden. If both interfaces assign a value, the last assignment wins.

\section{Tables, lists, and plots: one calling convention}
The dispatcher selects a named output and passes its arguments to it. Put
settings in the leading square brackets. A simple target needs one pair of
braces; a target with arguments uses an outer pair around the entire sequence:
|\printTable{ProjectLeaders}|, |\printTable{{Projects}{A}{Area title}}|.
The following chapter introduces each built-in target beside its result.

\begin{docCommand}{printTable}{\oarg{options}\marg{name}}
  Print one of the predefined template tables.  The \meta{name} is the table
  base name without the suffix \texttt{Table}; for example
  \texttt{ProjectLeaders} calls \cs{ProjectLeadersTable}.  If \meta{name} is a
  braced list, the first item is used as the table base name and the remaining
  items are passed as arguments to that table command.  The gap above a table
  follows the normal subsection-to-text gap by default. The class derives
  \cs{dfgTablePreSep} from the final document fonts and paragraph spacing at
  the beginning of the document. A nonnegative value set in the customization
  file or preamble overrides this default; for example,
  |\setlength{\dfgTablePreSep}{12pt}| selects a fixed common gap. It applies
  after headings and paragraphs, including the requested-funding staff roster
  and the \refEnv{FundingDirectCostsTable} breakdowns. Long tables receive
  the length through their |presep| option.
  Put options before the table specification. For example,
  |\printTable[all-sexes]{GenderEqualityProjectLeaders}| selects the expanded
  gender overview for that call only.
  The shared |note={text}| option adds a footnote-sized \enquote{Note:} below
  the table. For example:\par\noindent
  |\printTable[note={Additional information.}]{{RequestedFunding}{A01}}|\par
  On a multi-page table the note appears once, below its last part. Existing
  table notes are retained; text is appended to an existing \enquote{Note}
  remark, or a new \enquote{Note:} is added after other remarks. The fixed
  \enquote{Figures in EUR.} notice always ends with a full stop. Empty or
  whitespace-only notes add no text or space. Formatting, citations, commas
  inside braces, paragraph breaks, and \cs{footnote} are supported.
  With |theme=main|, wrapped remarks, including these notes, have no hanging
  indent: second and later lines start at the left edge of the remark.
  Footnotes retain their text and hyperlinks in the normal page footer;
  no surrounding environment is required.
  Combine the note with target-specific options in the same brackets, for
  example |[all-sexes,note={Additional information.}]| or
  |[MyStaffDatabase,note={Additional information.}]|. The note applies only to
  this call. A skipped table or a no-data message receives no orphan note.
  For staff rosters it appears before the institution legend and job
  descriptions.
  The command inserts \cs{par} before and after its output, so surrounding
  text always starts in separate paragraphs, even without blank source lines.
  Directly after a heading, it also inserts a zero-size rule and a no-break
  penalty to prevent overlap at a page break. The rule adds no interline gap,
  so the spacing is controlled by \cs{dfgTablePreSep}. Do not insert a manual
  \cs{null} before \cs{printTable}: it would add another interline gap.

  See \dfgExampleRef{ex:manual-project-leaders-and-their-affiliations}, \dfgExampleRef{ex:manual-requested-funding-for-a-project}, \dfgExampleRef{ex:manual-laboratory-animals-purchase-housing-and-funding}.
\end{docCommand}

\begin{docCommand}{printList}{\oarg{options}\marg{name}}
  Print one of the predefined template lists.  The \meta{name} is the list base
  name without the suffix \texttt{List}; for example
  \texttt{ParticipatingInstitutions} calls
  \cs{ParticipatingInstitutionsList}.  The optional \meta{options} are passed
  to the generated list command.  Put sorting, formatting, database, and
  raster settings together in this leading option list, as with
  \cs{printPlot}.  Both |{ParticipatingInstitutions}| and
  |{{ParticipatingInstitutions}}| are accepted as the list specification.
  Older trailing options remain supported, with leading settings taking
  precedence.  A person's institutions use
  |\printList{{Institutions}{per1}}|; that form needs the person ID, while
  |\printList{ParticipatingInstitutions}| lists participating institutions
  across the proposal, with affiliation names in bold.


  See \dfgExampleRef{ex:manual-flowing-institution-columns}, \dfgExampleRef{ex:manual-alphabetical-institution-raster}, \dfgExampleRef{ex:manual-one-person-with-multiple-institutions}.
\end{docCommand}

\cs{printPlot} uses the same convention: |\printPlot[options]{{type}{project-id}}|.
Within a project, omit the ID to use that project. The complete option and
result examples follow the work-package declarations in
Section~\ref{sec:manual-plot-examples}.

\chapter{Build the proposal in order}
\label{chap:proposal-walkthrough}
\label{sec:manual-table-guide}
Follow the generated proposal from the title page through general information,
finances, individual projects, bylaws, declarations, and back matter. Each
output example pairs its source with its result. All sixteen built-in table
targets, all three lists, and both plot types appear at their point of use.
The shared metadata are documented once in Section~\ref{sec:manual-fixtures};
table-specific records are shown directly before their printing command.

\section{Title page and applicant universities}

\begin{docCommand}{dfgApplicantAffiliationsTF}{\marg{singular}\marg{plural}}
  Use \meta{singular} when |meta.ref-affiliation-id| contains one applicant
  affiliation and \meta{plural} when it contains several.  The title page,
  applicant-university section heading, bylaws, and declarations use this
  helper for their grammar.  \cs{theCRCaffiliation} and
  \cs{theCRCaffiliationLocation} contain the complete human-readable name and
  location lists.  The first id is the coordinating university and is exposed
  as \cs{theCRCCoordinatingAffiliation}; any remaining ids are exposed as
  \cs{theCRCOtherApplicantAffiliations}, matching the two separate fields on
  the DFG title page.

  See \dfgExampleRef{ex:manual-choose-applicant-wording-from-metadata}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-choose-applicant-wording-from-metadata}]{Choose applicant wording from metadata}
\dfgApplicantAffiliationsTF
  {Applicant university:}
  {Applicant universities:}
\theCRCaffiliation.
\end{dfgExample}

\begin{docCommand}{crcLogo}{\oarg{graphics-options}}
  Print the CRC logo.  The optional \meta{graphics-options} are passed to
  \cs{includegraphics}.  The actual file is configured with
  \refKey{crcLogoPath} through \cs{changeSettings} and remains available as
  \cs{crcLogoPath}.

  See \dfgExampleRef{ex:manual-configure-and-print-the-title-page-logos}.
\end{docCommand}

\begin{docCommand}{affiliationLogo}{\oarg{graphics-options}}
  Print the affiliation logo.  The optional \meta{graphics-options} are passed
  to \cs{includegraphics}.  The actual file is configured with
  \refKey{affiliationLogoPath} through \cs{changeSettings} and remains
  available as \cs{affiliationLogoPath}.

  See \dfgExampleRef{ex:manual-configure-and-print-the-title-page-logos}.
\end{docCommand}

\begin{docCommand}{Hrule}{\oarg{key=value}}
  Print a configurable horizontal rule.  The available keys are
  \texttt{color}, \texttt{above}, \texttt{below}, and \texttt{thickness}.

  See \dfgExampleRef{ex:manual-a-horizontal-rule-with-custom-spacing}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-a-horizontal-rule-with-custom-spacing}]{A horizontal rule with custom spacing}
Scientific objectives
\Hrule[color=blue,thickness=.6pt,above=4pt,below=6pt]
Experimental approach
\end{dfgExample}

Use your own logo files in a proposal. This example substitutes the bundled
placeholder image so the size options can be tried without external files.

\begin{dfgExample}[label={ex:manual-configure-and-print-the-title-page-logos}]{Configure and print the title-page logos}
\changeSettings{
  crcLogoPath=example-image,
  affiliationLogoPath=example-image
}
\crcLogo[width=.4\linewidth]\quad
\affiliationLogo[width=.4\linewidth]
\end{dfgExample}

\section{General information}
\subsection{Key data: governing bodies and contact details}
\begin{docCommand}{getPersonInformation}{\oarg{database}\marg{person-id-list}}
  Print full PI contact details, including institutions and contact fields.
  The database defaults to |person|. Use explicit person IDs for a selected
  pair; use \cs{getPIsWithRole} below to select people by their metadata role.
  In project heads, one PI occupies a full-width one-column raster and several
  PIs occupy a two-column raster. Both use the same raster alignment and spacing
  below the \enquote{Project leader(s)} heading; the number of PIs does not
  tighten that gap.

  See \dfgExampleRef{ex:manual-contact-details-for-two-selected-pis}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-contact-details-for-two-selected-pis},dfg wide]{Contact details for two selected PIs}
\getPersonInformation[person]{per1,per2}
\end{dfgExample}

\begin{docCommand}{getPIsWithRole}{\oarg{options}\marg{role}}
  Print persons with the given \meta{role} in PI boxes.  Put all options
  before the role, for example |database=person,raster columns=2|.
  The database defaults to \texttt{person}.  Only persons belonging to
  the current funding period are shown.  The default three-column raster
  has a 12\,pt column gap.  Rows of boxes and the content after the raster
  are separated by 20\,pt.  Raster settings in \meta{options} are passed to
  the underlying \refPkg{tcolorbox} raster and may override those defaults.
  Use |academicdegree-below| to place the academic degree on a separate
  line below the name, inside the same PI-box title.  This applies only to
  the current call; omitting the option or setting |academicdegree-below=false|
  keeps the degree inline after the name.  For example:
  |\getPIsWithRole[academicdegree-below]{steering-committee-member}|.
  The contact markers in each PI box are controlled globally with
  |\changeSettings{PIcontactStyle=icons}| (the default),
  |PIcontactStyle=text| for the labels ``Phone:'' and ``E-Mail:'', or
  |PIcontactStyle=none| to suppress both markers.
  Older calls with a bare database name or trailing raster options remain
  supported; leading settings take precedence over trailing settings.

  In both this raster and the two-column raster of \cs{getPersonInformation},
  titles are ragged right and top-aligned.  Each title reserves the height of
  the tallest title in its raster, keeping the contact information aligned
  when names or academic degrees wrap.  Equal-height groups settle over
  successive LaTeX runs; a clean build can require three passes.
  Phone and email each remain unbroken, but their one-em separating space
  permits a line break when both contacts do not fit on the same line.

  See \dfgExampleRef{ex:manual-print-all-pis-with-a-given-role}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-print-all-pis-with-a-given-role},dfg wide]{Print all PIs with a given role.}
\getPIsWithRole[raster columns=2]{steering-committee-member}
\end{dfgExample}

\subsection{Project leaders}
The table resolves each PI's institutions and affiliations from the shared
metadata (Section~\ref{sec:manual-fixtures}). Declare those records once;
changing a name or institution then updates every table and reference.

\begin{dfgExample}[label={ex:manual-project-leaders-and-their-affiliations},dfg wide,listing above* text]{Project leaders and their affiliations}
\printTable{ProjectLeaders}
\end{dfgExample}

\subsection{Participating institutions}
  Use |columns=2| or |columns=3| to flow affiliation groups down balanced
  columns, keeping each affiliation with its institutions. Short groups follow
  one another without equal-height row padding. Reading order is down each
  column. The gap defaults to 12\,pt; set |column sep=16pt| to change it.
  Flowing lists start a new paragraph with \cs{medskipamount} space above them.

  Without |columns|, participating institutions use one raster cell per
  affiliation, including its institutions. The default is one column,
  with a 12\,pt column gap and
  a 10\,pt row gap.  Pass |raster columns=2| or other \refPkg{tcolorbox}
  raster options through \meta{options}.  Sorting defaults to |order=count|;
  |order=alpha| sorts affiliations alphabetically.  The bare |count| and
  |alpha| options remain accepted.
  \begin{dfgExample}[label={ex:manual-flowing-institution-columns},dfg wide]{Flowing institution columns}
\printList[columns=2]{ParticipatingInstitutions}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-three-flowing-institution-columns},dfg wide]{Three flowing institution columns}
\printList[columns=3,column sep=16pt]{ParticipatingInstitutions}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-alphabetical-institution-raster},dfg wide]{Alphabetical institution raster}
\printList[order=alpha,raster columns=2]{ParticipatingInstitutions}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-institution-raster-ordered-by-pi-count},dfg wide]{Institution raster ordered by PI count}
\printList[order=count,raster columns=3]{ParticipatingInstitutions}
\end{dfgExample}




\subsection{Project groups and projects}
\label{sec:manual-consortium-tables}
Projects are grouped by their area. The same command serves each area; the
second argument supplies the heading. The shared dataset contains six A,
six B, and three Q projects, declared once in Section~\ref{sec:manual-fixtures}.

\begin{dfgExample}[label={ex:manual-project-overview-area-a},dfg wide,listing above* text]{Project overview: area A}
\printTable{{Projects}{A}{Microbiota and metabolic pathways}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-project-overview-area-b},dfg wide,listing above* text]{Project overview: area B}
\printTable{{Projects}{B}{Immune mechanisms and clinical translation}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-service-training-and-administration-projects},dfg wide,listing above* text]{Service, training, and administration projects}
\printTable{{Projects}{Q}{Shared services, training, and coordination}}
\end{dfgExample}

The status legend can follow the project overview. The funding-period wording
and research-area list are taken from metadata, so they stay consistent with
the tables. The footnote remains in the normal page flow.

\begin{dfgExample}[label={ex:manual-project-status-legend-and-research-areas},dfg wide,listing above* text]{Project-status legend and research areas}
{\footnotesize
N: New projects started in the \theFundingPeriodText\space funding period;\space
E: Ending projects not continued in the \theFundingPeriodText\space funding period;\space
Research areas according to the German Research Foundation (2024--2028)%
\footnote{\raggedright
  \url{https://www.dfg.de/resource/blob/331950/fachsystematik-2024-2028-en.pdf}}:
\printList{ResearchAreasFromProjects}\par}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-research-areas-excluding-selected-projects},dfg wide,listing above* text]{Research areas excluding selected projects}
\printList[A01,B01]{ResearchAreasFromProjects}
\end{dfgExample}

The optional argument of |ResearchAreasFromProjects| excludes the listed
project IDs from the collection of research areas. Like the project tables,
the legend includes research and service projects whose status is not |E|.
Projects with |consider-for-lists=false|, training projects, and administrative
projects do not contribute codes.
The sorted, deduplicated list is rebuilt for every call, including calls with
different exclusions.

The project tables use a 15\,mm research-area column, wide enough for the
unbroken heading at the default table size. Codes are centered as text,
including cells containing several codes. Left alignment of the title and
project-leader columns is handled separately.

\begin{dfgExample}[label={ex:manual-look-up-research-area-descriptions}]{Look up research-area descriptions}
\dfgResearchAreasList{2.21-02}\par
\dfgResearchAreasList{2.21-05}
\end{dfgExample}

\paragraph{Person-specific institution lists}
\label{sec:manual-person-lists}
Use |\printList{{Institutions}{per7}}| to print the institutions assigned to
person \texttt{per7}.  The person ID is required.  For a non-default database,
use |\printList[database=other]{{Institutions}{per7}}|; the database defaults to
\texttt{person}.  Put formatting options in the same leading list, as in
|\printList[database=person,abbreviation,narrow]{{Institutions}{per7}}|.
The older bare-database and trailing-formatting forms remain supported.
The list reads
\refKey{ref-institution-id} from the person entry and then resolves the
referenced entries in the \texttt{institution} and \texttt{affiliation}
databases. Options are \texttt{abbreviation}, \texttt{narrow},
\texttt{noaddress}, \texttt{nozip}, and \texttt{nolocation}.

  In the standard layout, every institution prints the institution name,
  affiliation name, street, ZIP code, location, and country when these values
  are available.  If a person references more than one institution, the entries
  are separated by a paragraph break with a small vertical gap.  If an
  institution row has an empty \refKey{name}, the output starts directly with
  the affiliation name.

  \begin{description}
    \item[\texttt{abbreviation}] Use the institution's
      \refKey{abbreviation} instead of its full \refKey{name}.  If the
      abbreviation is absent, the full name is used for compatibility.
    \item[\texttt{narrow}] Print a compact inline form.  Fields inside one
      institution are separated by commas and multiple institutions by
      semicolons.  This is useful in narrow CV/table cells.
    \item[\texttt{noaddress}] Omit the street address.
    \item[\texttt{nozip}] Omit the ZIP code.
    \item[\texttt{nolocation}] Omit the location and country.
  \end{description}
The former \cs{dfgInstitutionList} spelling remains as a compatibility alias.

\begin{dfgExample}[label={ex:manual-one-person-with-multiple-institutions}]{One person with multiple institutions}
\get[person]{per7}{ref-institution-id}\par
\printList{{Institutions}{per7}}
\medskip
\printList[abbreviation,narrow,noaddress,nozip,nolocation]
  {{Institutions}{per7}}
\end{dfgExample}

\subsection{Frame-text references}
\begin{docCommand}{printFrameBibliography}{\oarg{biblatex options}}
  Print the frame-text bibliography, forwarding the optional arguments to
  \cs{printbibliography} and preserving its normal font size. With
  \refKey{emphasizeEntries} enabled, a complete entry is bold when its
  \texttt{keywords} field contains \texttt{frametext-highlight}. Project
  highlight keywords do not affect this list; the frame keyword does not
  affect project lists or inline citations. Like project bibliographies,
  output is suppressed when \refKey{fastcompile-project-show-publications}
  is disabled.
\end{docCommand}

Add the keyword to the publication's existing keywords, for example
|keywords = {pabst-A,B06-highlight,frametext-highlight}|. The keyword controls
formatting, not inclusion: cite the entry or add it with \cs{nocite} as usual.
Enable \refKey{emphasizeEntries} in \cs{changeSettings}, then use:
\begin{dispListing}
\defbibnote{frame-references}{%
  \usekomafont{subsection}%
  \bfseries\sffamily References
}
\printFrameBibliography[
  prenote={frame-references},
  heading=none
]
\end{dispListing}
Replace the plain \cs{printbibliography} call in existing chapter 1 files;
template updates preserve those edited files.

\subsection{Research profile: summaries and highlighted statements}
\begin{docEnvironment}{dfgBoxEnv}{\oarg{further specifications}}
  Box environment to be used for highlighting things
  To be used in \dfgFile{content}.
  See \dfgExampleRef{ex:manual-highlight-text-with-a-box-environment}.
\end{docEnvironment}

\begin{dfgExample}[label={ex:manual-highlight-text-with-a-box-environment}]{Highlight text with a box environment}
\begin{dfgBoxEnv}[title={Research question}]
How do host and microbiome communicate?
\end{dfgBoxEnv}
\end{dfgExample}

% \begin{docEnvironment}{dfgTitleBox}{\oarg{further specifications}}
% Box environment to be used for e.g. a title page
% To be used in \dfgFile{content}
% \end{docEnvironment}

\begin{docEnvironment}{dfgSummaryBox}{\oarg{further specifications, e.g. `title=NN`}}
  Box environment to be used for e.g. summaries that are lists.
  Use \cs{item} for bulletpoints. To be used in \dfgFile{content}

  See \dfgExampleRef{ex:manual-example-use-of-a-summary-box}.
\end{docEnvironment}

\begin{dfgExample}[label={ex:manual-example-use-of-a-summary-box}]{Example use of a summary box}
\begin{dfgSummaryBox}[title={Next steps}]
  \item Validate biomarkers.
  \item Share the results.
\end{dfgSummaryBox}
\end{dfgExample}

\begin{docCommand}{dfgBox}{\oarg{further specifications}\marg{content}}
  Box environment to be used for anything.
  To be used anywhere in the text. The mandatory content argument accepts
  paragraph breaks.

  See \dfgExampleRef{ex:manual-example-of-a-minimal-box}.
\end{docCommand}
\begin{dfgExample}[label={ex:manual-example-of-a-minimal-box}]{Example of a minimal box }
\dfgBox[title={Research finding}]
  {Microbial signals shape immunity.}
\end{dfgExample}

\subsection{Tables and figures in the scientific narrative}
Use the following environments when the prose needs a table or a figure that
is not one of the predefined metadata tables.

\begin{docEnvironment}{TableEnv}{\oarg{outer options}\marg{column specification}
    \oarg{table options}\marg{caption}\marg{label}}
  Typeset a generic long table using the template's main table theme. The
  leading optional \meta{outer options} extend the tabularray outer
  specification. For explanations applying to the whole table, use
  |remark{Abbreviations}={Definitions.}| or |remark{Note}={Additional information.}|.
  For marked footnotes referenced from cells, use |note{a}={Footnote text.}|
  and |\TblrNote{a}|. In |theme=main|, remark continuation lines start flush
  with the left edge of the remark, without a hanging indent. Lettered notes
  keep tabularray's standard formatting.
  The optional \meta{table options} after the column specification are inserted into the inner
  \refPkg{tabularray} specification and default to an empty option list, so
  the square brackets may be omitted when no additional options are needed.
  Body cells default to left alignment; explicit column and row alignments
  take precedence. Use |halign=l|, |halign=c|, or |halign=r| for alignment,
  and reserve |font| for font settings.
  Left alignment is configured once in the shared theme setup with standard
  \cs{raggedright}; individual cells need no paragraph-alignment prefix.
  In |theme=main|, header text uses |valign=m| for vertical centring,
  including cells spanning several header rows. Use the same setting for
  additional header rows in a multirow heading.
  Column specifications can override theme defaults. \refEnv{TableEnv}
  reapplies its header alignment after the column specification, before
  caller options. For a custom |tblr|, put |row{1-2}={valign=m}| after
  its column specification when the header spans two rows, and use |m|
  in spanning header cells. Explicit row and cell options can override
  the default alignment.
  Table text defaults to \cs{footnotesize} at theme scope.  Consequently,
  cell-local declarations such as |font=\bfseries| or |font=\itshape| retain
  the default size; include an explicit size such as |font=\normalsize\bfseries|
  only when a table or cell should override it.

  See \dfgExampleRef{ex:manual-tableenv-with-column-and-row-options}, \dfgExampleRef{ex:manual-new-continuing-and-ending-project-structures}.
\end{docEnvironment}

\begin{dfgExample}[label={ex:manual-tableenv-with-column-and-row-options}]{TableEnv with column and row options}
\begin{TableEnv}[remark{Note}={Illustrative project counts.}]{X[2,l] X[1,r]}[
  row{1}={font=\bfseries},
  rowsep=3pt,
  column{2}={halign=r}
]{Projects by area}{tab:manual-area-counts}
Area & Projects \\
A & \getProjectCount[A] \\
B & \getProjectCount[B] \\
Q & \getProjectCount[Q]
\end{TableEnv}
\end{dfgExample}


\subsection{Figures}
For inserting figures we highly recommend to use the command from the package |hvfloat|.
\begin{docCommand}{hvFloat}{\sarg\oarg{options}+\marg{floattype}\marg{floatingobject}%
    \oarg{shortcaption}\marg{longcaption}\marg{label}}

  See \dfgExampleRef{ex:manual-a-figure-with-a-caption}.
\end{docCommand}


\begin{dfgExample}[label={ex:manual-a-figure-with-a-caption}]{A figure with a caption}
\hvFloat[capPos=bottom]{figure}
  {\includegraphics[width=\linewidth]{example-image}}
  {Example artwork and its caption.}
  {fig:manual-hvfloat}
\end{dfgExample}

\subsection{Early-career researchers and equality objectives}
\label{sec:manual-researcher-tables}
\begin{docCommand}{EarlyCareerResearchersTable}{\oarg{database}}
  List doctoral candidates from |EarlyCareerResearcher|, using the |person|
  keyset. This is a named training roster, separate from the monetary staff
  request. |PhD| and |MD| select the row colours. An empty |periodEnd| prints
  an ongoing appointment as \enquote{since}. A nonempty |dateDefense|
  automatically makes the surname and first name bold. Other cells retain
  their configured styles, including the row colour and topic italics.
  Missing, empty, or whitespace-only dates leave the ordinary name style. Former-project markers and their explanatory legend are omitted
  in this training roster, including direct calls with a custom database.

  See \dfgExampleRef{ex:manual-doctoral-candidates-completed-ongoing-and-medical-projects}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-doctoral-candidates-completed-ongoing-and-medical-projects},dfg wide,listing above* text]{Doctoral candidates: completed, ongoing, and medical projects}
\addEntry[person]{EarlyCareerResearcher}{
  id             = {doc-phd-completed},
  ref-project-id = {A01},
  firstname      = {Robin},
  lastname       = {Meyer},
  dateDefense    = {2025-09-15},
  financed-by    = {DFG},
  category       = {PhD},
  topic          = {Microbial metabolites and epithelial signalling},
  periodStart    = {2021-10},
  periodEnd      = {2025-09}
}
\addEntry[person]{EarlyCareerResearcher}{
  id             = {doc-phd-ongoing},
  ref-project-id = {B03},
  firstname      = {Alex},
  lastname       = {Reed},
  financed-by    = {University},
  category       = {PhD},
  topic          = {Tissue-resident immune-cell programming},
  periodStart    = {2025-04},
  periodEnd      = {}
}
\addEntry[person]{EarlyCareerResearcher}{
  id             = {doc-md},
  ref-project-id = {B04},
  firstname      = {Sam},
  lastname       = {Taylor},
  financed-by    = {DFG},
  category       = {MD},
  topic          = {Clinical markers of cross-organ inflammation},
  periodStart    = {2026-04},
  periodEnd      = {2026-09}
}
\printTable{EarlyCareerResearchers}
\end{dfgExample}

\subsubsection*{A. Objectives for the participation of female researchers}
This example supplies the previous objective, observed number and percentage,
and future objective for doctoral and postdoctoral researchers. All figures are
fictitious. Use the |GenderEquality| keyset for both equality tables.

\begin{dfgExample}[label={ex:manual-a-objectives-for-the-participation-of-female-researchers},dfg wide,listing above* text]{A. Objectives for the participation of female researchers}
\addEntry[GenderEquality]{GenderEqualityStaff}{
  position                                = {PhD},
  previous-objective-percentage-female    = {40},
  status-quo-number-female                = {12},
  status-quo-percentage-female            = {50},
  future-objective-percentage-female      = {50}
}
\addEntry[GenderEquality]{GenderEqualityStaff}{
  position                                = {postDoc},
  previous-objective-percentage-female    = {40},
  status-quo-number-female                = {4},
  status-quo-percentage-female            = {40},
  future-objective-percentage-female      = {50}
}
\printTable{GenderEqualityStaff}
\end{dfgExample}

\subsubsection*{B. Project leaders}
Here the records specify objectives for each career category. Status-quo counts
and percentages are calculated from the |gender|, |position|, and funding-period
membership of the |person| records shown in
Section~\ref{sec:manual-consortium-tables}. Only proposals with
|fundingPeriodNumeral = {3}| show the additional first-funding-period columns,
using membership in period~1. By default, the table shows only female
numbers and percentages. For a third-period proposal, it follows DFG
form~60.200: periods~1 and~2 each have Number/Percentage columns; period~3
has its original objective and current Number/Percentage columns. The
existing |future-objective-percentage-female| field supplies that period~3
objective. Include period~3 membership in the person records to calculate
the proposed leadership composition.

Pass |[all-sexes]| before the table name in \refCom{printTable} to select
the expanded f/m/d comparison. For a third-period proposal, every period includes Number and
Percentage columns for f/m/d, alongside the previous period's objective and
the proposed period's future objective. All percentages use the complete f/m/d population in the
same career category (or across the four categories in the total row).
Do not enter these calculated values again in the objectives database;
include historical PIs with the appropriate |period| membership.

\begin{dispListing}
\printTable{GenderEqualityProjectLeaders}            % default: female-only
\printTable[all-sexes]{GenderEqualityProjectLeaders} % f/m/d for all periods
\end{dispListing}

\begin{docKey}{all-sexes}{\docKeyChoices{true,false}}{initially \texttt{false}}
  A per-table option for \cs{GenderEqualityProjectLeadersTable}. The bare flag
  |[all-sexes]| selects f/m/d counts and percentages, including period~3 in a
  third-period proposal, alongside the previous/future objectives.
  Omit the option (or use |[all-sexes=false]|) for the female-only DFG layout.
  Percentages always use all genders as their denominator. The option affects
  only the current table and does not change subsequent tables or prose commands.
  Use |[database=MyObjectives,all-sexes]| for a custom objectives database;
  the older bare database argument also remains supported.
\end{docKey}

\begin{dfgExample}[label={ex:manual-b-project-leaders-objectives-and-calculated-participation},dfg wide,listing above* text]{B. Project leaders: objectives and calculated participation}
\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                                = {postDoc},
  previous-objective-percentage-female    = {40},
  future-objective-percentage-female      = {50}
}
\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                                = {groupLeader},
  previous-objective-percentage-female    = {40},
  future-objective-percentage-female      = {50}
}
\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                                = {prof-W2},
  previous-objective-percentage-female    = {40},
  future-objective-percentage-female      = {50}
}
\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                                = {prof-W3},
  previous-objective-percentage-female    = {40},
  future-objective-percentage-female      = {50}
}
\printTable{GenderEqualityProjectLeaders}
\end{dfgExample}

\subsubsection{Use the same statistics in prose}
\begin{description}
  \item[\cs{getPositionGenderPhaseAmount}]
    \oarg{database}\marg{position}\marg{gender}\marg{period} prints the count
    for one position/gender/period tuple.
    See \dfgExampleRef{ex:manual-person-counts-and-percentages-for-a-funding-period}.

  \item[\cs{getPositionPhaseTotal}]
    \oarg{database}\marg{position}\marg{period} prints the all-gender total.
    See \dfgExampleRef{ex:manual-person-counts-and-percentages-for-a-funding-period}.

  \item[\cs{getGenderPhaseTotal}]
    \oarg{database}\marg{gender}\marg{period} prints the all-position total.
    See \dfgExampleRef{ex:manual-person-counts-and-percentages-for-a-funding-period}.

  \item[\cs{getPositionGenderPhasePercentage}]
    \oarg{database}\marg{position}\marg{gender}\marg{period} prints the
    rounded integer percentage value within a position.
    See \dfgExampleRef{ex:manual-person-counts-and-percentages-for-a-funding-period}.

  \item[\cs{getGenderPhasePercentage}]
    \oarg{database}\marg{gender}\marg{period} prints the rounded integer
    percentage value across all counted positions.
    See \dfgExampleRef{ex:manual-person-counts-and-percentages-for-a-funding-period}.

\end{description}

The period argument is the funding-period number, not a calendar year.
Percentage commands return a number; append |\%| when using it in prose.
The commands below retrieve the numbers printed in section~1.4.2~B for any
funding period, independently of which proposal period is currently selected.
Use |f|, |m|, or |d| for the gender. The supported table positions are
|postDoc|, |groupLeader|, |prof-W2|, and |prof-W3|. The total-row commands
sum these four positions and count each person with |role=PI| once per period;
a person belonging to several periods is counted in each matching period.
The optional database defaults to |person|. Percentages are rounded to the
nearest integer and return zero if their denominator is zero. These are
person statistics; calculating the share of projects with female leadership
requires a separate calculation that counts each project once.

\begin{dispListing}
% First funding period: female W3 professors, number and percentage.
\getPositionGenderPhaseAmount{prof-W3}{f}{1}
\getPositionGenderPhasePercentage{prof-W3}{f}{1}\%
% All genders within the same career category.
\getPositionPhaseTotal{prof-W3}{1}
% First-period total row: female project leaders, number and percentage.
\getGenderPhaseTotal{f}{1}
\getGenderPhasePercentage{f}{1}\%
% Second-period total row: change only the final argument.
\getGenderPhaseTotal{f}{2}
\getGenderPhasePercentage{f}{2}\%
\end{dispListing}
\begin{dfgExample}[label={ex:manual-person-counts-and-percentages-for-a-funding-period}]{Person counts and percentages for a funding period}
W3 professors in period 3:
\getPositionPhaseTotal{prof-W3}{3}.\par
Women among them:
\getPositionGenderPhaseAmount{prof-W3}{f}{3}
(\getPositionGenderPhasePercentage{prof-W3}{f}{3}\%).\par
Women across counted positions:
\getGenderPhaseTotal{f}{3}
(\getGenderPhasePercentage{f}{3}\%).
\end{dfgExample}

\section{Existing and requested funds}
The proposal-wide tables combine institutional resources and project requests.
The class transfers project declarations through the auxiliary files, so
compile with |latexmk| until the totals settle. The project-level declarations
and their local tables follow in Section~\ref{sec:manual-project-funding}.

\subsection{Finances: existing funds and resources}
\label{sec:manual-existing-finances}
The following overviews precede the project chapters in a proposal. By default,
current-period figures are restored from project declarations through the
auxiliary file; compile again after changing those declarations. Custom databases
in the next two examples isolate their inputs from the other demonstrations.

\subsubsection*{Existing funds for direct costs}
The five historical rows use full EUR amounts. Current-period rows group funds
by |ref-affiliation-id|: the applicant affiliation |aff1|, another participant
|aff2|, and the special value |other-funds|. Funding-source text does not choose
the column. In a proposal, declare the current rows in
|RequestedAndExistingFundingDirectCosts| and use
|\printTable{ExistingFundsDirectCosts}| to collect them automatically.

\begin{dfgExample}[label={ex:manual-existing-direct-costs-previous-and-new-funding-periods},dfg wide,listing above* text]{Existing direct costs: previous and new funding periods}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year                 = {1},
  applicant            = {2000},
  participant          = {1000},
  other-funds          = {500}
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year                 = {2},
  applicant            = {2000},
  participant          = {1000},
  other-funds          = {500}
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year                 = {3},
  applicant            = {2000},
  participant          = {1000},
  other-funds          = {500}
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year                 = {4},
  applicant            = {2000},
  participant          = {1000},
  other-funds          = {500}
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year                 = {5},
  applicant            = {2000},
  participant          = {1000},
  other-funds          = {500}
}
\addEntry[funding]{ManualExistingCosts}{
  ref-project-id       = {A01},
  ref-affiliation-id   = {aff1},
  financed-by          = {Example core or third-party funds},
  sum                  = {year1 = {4000}, year2 = {4000}, year3 = {4000}, year4 = {4000}, year5 = {4000}}
}
\addEntry[funding]{ManualExistingCosts}{
  ref-project-id       = {A01},
  ref-affiliation-id   = {aff2},
  financed-by          = {Example core or third-party funds},
  sum                  = {year1 = {2000}, year2 = {2000}, year3 = {2000}, year4 = {2000}, year5 = {2000}}
}
\addEntry[funding]{ManualExistingCosts}{
  ref-project-id       = {A01},
  ref-affiliation-id   = {other-funds},
  financed-by          = {Example core or third-party funds},
  sum                  = {year1 = {1000}, year2 = {1000}, year3 = {1000}, year4 = {1000}, year5 = {1000}}
}
\printTable[ManualExistingCosts]{ExistingFundsDirectCosts}
\end{dfgExample}

\subsubsection*{Existing staff}
These records inherit institutions from the PI metadata already shown.
The custom database supplies all columns read by the overview; empty organisation
fields allow the person's institution references to be used. The overview counts existing staff at applicant and participating
affiliations. In a proposal, add them to |RequestedFundingStaff| and use
|\printTable{OverviewExistingStaff}| without a database override.

\begin{dfgExample}[label={ex:manual-existing-staff-by-affiliation-and-career-category},dfg wide,listing above* text]{Existing staff by affiliation and career category}
\addEntry[staff]{ManualExistingStaff}{
  ref-project-id       = {A01},
  funding-status       = {existing},
  staff-type           = {research},
  ref-person-id        = {per1},
  lastname             = {Sample},
  category             = {prof-W3},
  ref-institution-id   = {},
  ref-affiliation-id   = {},
  field-of-research    = {Life sciences},
  commitment           = {8},
  funding-source       = {State funds}
}
\addEntry[staff]{ManualExistingStaff}{
  ref-project-id       = {A02},
  funding-status       = {existing},
  staff-type           = {research},
  ref-person-id        = {per6},
  lastname             = {Hartmann},
  category             = {prof-W2},
  ref-institution-id   = {},
  ref-affiliation-id   = {},
  field-of-research    = {Life sciences},
  commitment           = {8},
  funding-source       = {State funds}
}
\addEntry[staff]{ManualExistingStaff}{
  ref-project-id       = {B03},
  funding-status       = {existing},
  staff-type           = {research},
  ref-person-id        = {per11},
  lastname             = {Sato},
  category             = {prof-W2},
  ref-institution-id   = {},
  ref-affiliation-id   = {},
  field-of-research    = {Life sciences},
  commitment           = {8},
  funding-source       = {State funds}
}
\printTable[ManualExistingStaff]{OverviewExistingStaff}
\end{dfgExample}

\begin{docCommand}{ExistingInstrumentationTable}{\oarg{database}}
  List equipment already available to the projects. The database defaults to
  |existingInstrumentation| and uses the |instrumentation| keyset. The |cost|
  field is in thousands of euros: |250| means EUR\,250,000. Set |cost={n.a.}|
  when the purchase cost is unavailable, for example for donated equipment;
  it is printed as text rather than interpreted as a number or as zero.
  Numeric costs retain the usual formatting and precision. A supplied
  |quantity| prefixes the description with a text multiplication sign.
  A comma-separated |ref-project-id| lists shared equipment once for several projects.
  Rows are sorted in ascending order by |ref-project-id|; shared equipment
  is ordered by its listed project IDs and remains a single row.
  Description cells use standard \cs{raggedright} with natural word spacing;
  the column heading remains centred.

  See \dfgExampleRef{ex:manual-existing-instrumentation-including-shared-equipment}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-existing-instrumentation-including-shared-equipment},dfg wide,listing above* text]{Existing instrumentation, including shared equipment}
\addEntry[instrumentation]{existingInstrumentation}{
  ref-project-id = {A01},
  quantity       = {1},
  instrument     = {Confocal laser-scanning microscope},
  company        = {Example Instruments},
  year           = {2025},
  cost           = {250},
  financed-by    = {DFG}
}
\addEntry[instrumentation]{existingInstrumentation}{
  ref-project-id = {A01,B03},
  quantity       = {2},
  instrument     = {Anaerobic workstation},
  company        = {Example Laboratory Systems},
  year           = {2024},
  cost           = {80},
  financed-by    = {University funds}
}
\addEntry[instrumentation]{existingInstrumentation}{
  ref-project-id = {B03},
  quantity       = {1},
  instrument     = {Donated incubator},
  company        = {Example Laboratory Systems},
  year           = {2024},
  cost           = {n.a.},
  financed-by    = {Donation}
}
\printTable{ExistingInstrumentation}
\end{dfgExample}

\subsection{Finances: previous funding and new requests}
\label{sec:manual-requested-finances}
The next table combines five historical rows with the current requests declared
in the funding examples. Its new-period amounts include the earlier |A02|
requests, the equipment records below, and the complete |A06| request in
Section~\ref{sec:manual-project-funding}. These records are collected from the
auxiliary file even when their declarations follow the overview. All input
amounts are full EUR; do not duplicate a project declaration to populate this
overview.

\begin{dfgExample}[label={ex:manual-previous-funding-and-current-requests-across-all-five-groups},dfg wide,listing above* text]{Previous funding and current requests across all five groups}
\addEntry[funding]{PreviousRequestedFunding}{
  year                 = {1},
  staff                = {100000},
  costs                = {20000},
  instrumentation      = {30000},
  fellowships          = {5000},
  globalfunds          = {10000}
}
\addEntry[funding]{PreviousRequestedFunding}{
  year                 = {2},
  staff                = {100000},
  costs                = {20000},
  instrumentation      = {0},
  fellowships          = {5000},
  globalfunds          = {10000}
}
\addEntry[funding]{PreviousRequestedFunding}{
  year                 = {3},
  staff                = {100000},
  costs                = {20000},
  instrumentation      = {0},
  fellowships          = {5000},
  globalfunds          = {10000}
}
\addEntry[funding]{PreviousRequestedFunding}{
  year                 = {4},
  staff                = {100000},
  costs                = {20000},
  instrumentation      = {0},
  fellowships          = {5000},
  globalfunds          = {10000}
}
\addEntry[funding]{PreviousRequestedFunding}{
  year                 = {5},
  staff                = {100000},
  costs                = {20000},
  instrumentation      = {0},
  fellowships          = {5000},
  globalfunds          = {10000}
}
\printTable{PreviousAndCurrentRequestedFunding}
\end{dfgExample}

The staff overview counts requested positions by category and year; salary
percentages affect monetary costs, not the number of positions. This example
uses a separate database, |ManualStaffRequest|, to show precisely these two
records. Pass that database as the leading optional argument. In a proposal,
use |RequestedFunding| for the records and omit the table's optional argument
to collect requests across all projects. Projects without requested positions
remain visible with empty-value markers.

\begin{dfgExample}[label={ex:manual-requested-staff-positions-by-category-and-year},dfg wide,listing above* text]{Requested staff positions by category and year}
\addEntry[funding]{ManualStaffRequest}{
  ref-project-id = {B03},
  funding-type   = {staff},
  category       = {PhD},
  percentage     = {65},
  quantity       = {
    year1 = {1}, year2 = {1}, year3 = {2}, year4 = {2}, year5 = {1}
  }
}
\addEntry[funding]{ManualStaffRequest}{
  ref-project-id = {Q01},
  funding-type   = {staff},
  category       = {postDoc},
  percentage     = {100},
  quantity       = {
    year1 = {0}, year2 = {1}, year3 = {1}, year4 = {1}, year5 = {0}
  }
}
\printTable[ManualStaffRequest]{OverviewOfFundsRequestedForStaff}
\end{dfgExample}

Requested equipment belongs in |RequestedFunding| with
|funding-type={instrumentation}|. Unlike existing-equipment purchase costs,
the yearly |sum| values are full EUR amounts. The overview collects these
project declarations through the auxiliary file; two compilations may be
needed after adding or changing them. Its result also includes the |A06|
imaging workstation declared in the complete project-funding example in Section~\ref{sec:manual-project-funding}.

\begin{dfgExample}[label={ex:manual-requested-instrumentation-by-project-and-year},dfg wide,listing above* text]{Requested instrumentation by project and year}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q01},
  funding-type   = {instrumentation},
  category       = {Live-cell imaging system},
  sum            = {
    year1 = {150000},
    year2 = {0},
    year3 = {0},
    year4 = {0},
    year5 = {0}
  }
}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {B03},
  funding-type   = {instrumentation},
  category       = {Automated sample preparation},
  sum            = {
    year1 = {0},
    year2 = {0},
    year3 = {45000},
    year4 = {0},
    year5 = {0}
  }
}
\printTable{OverviewFundsRequestedInstrumentation}
\end{dfgExample}

\subsubsection*{Upkeep of laboratory animals}
Each row specifies the animal count, average weeks kept, purchase cost per
animal, and requested and existing funds in EUR. Housing rates come from the
animal-type registry. The built-in IDs |mouse|, |rat|, and
|mouse-gnotobiotic| retain their existing class settings and rates.
Subtotals include only groups represented by table rows. Gnotobiotic mice
have their own rate and row label, but contribute to the |mouse| subtotal.
The last row counts all animals and sums the explicitly supplied funding.

\begin{docCommand}{DeclareAnimalType}{\marg{id}\marg{key-value list}}
  Register or update an animal/housing type, normally in
  |preamble/dfg-customization.tex|. This command is available while that file
  is read. IDs start with a lowercase letter and contain only lowercase
  letters, digits, and hyphens. New types require |label| and |housing-rate|.
  |label-plural| defaults to |label| and supplies subtotal text.
  |total-group| defaults to the type's own ID. It can name the type itself or
  an already registered type, whose plural label is used for the grouped subtotal.
  It is a direct grouping ID; it does not inherit the target's housing rate
  or follow chains of groups. Redeclarations retain omitted fields and
  invalid declarations retain the previous definition. All assignments
  follow ordinary TeX grouping.
\end{docCommand}

\begin{dispListing}
\DeclareAnimalType{zebrafish}{
  label={Zebrafish}, label-plural={Zebrafish},
  housing-rate=0.12 % Example EUR per animal per week
}
\DeclareAnimalType{mouse-gnotobiotic}{total-group=mouse}
\end{dispListing}

The existing \refKey{animalHousing@mouse},
\refKey{animalHousing@mouseGnotobiotic}, and \refKey{animalHousing@rat}
settings remain live. Updating a built-in type's |housing-rate| also updates
its corresponding setting and compatibility accessor.
This table accepts |totals-by=group| (default) or |totals-by=type| through
the optional argument of \cs{printTable}. The latter separates housing types:
\begin{dispListing}
\printTable[totals-by=type]{UpkeepLaboratoryAnimals}
\printTable[database=MyAnimals,totals-by=group]{UpkeepLaboratoryAnimals}
% The former bare database argument is also supported:
\printTable[MyAnimals]{UpkeepLaboratoryAnimals}
\end{dispListing}

Subtotals follow registry declaration order; data rows are sorted by project.
Quantities must be
non-negative integers; weeks and costs accept non-negative decimal numbers.
Blank or invalid values print a dash. An asterisk marks totals that exclude
missing or invalid values; if no valid value is available, the total is a dash.
Explicit zero remains zero. Rows with a missing/unregistered type are shown
under |Unclassified| rather than silently disappearing.
Purchasing unit prices and average weeks retain decimals. Funding totals
continue to use the declared funding columns and whole-EUR display: no
purchase/housing cost formula replaces those amounts.
Every table call prepares its own rows and totals before tabularray measures
cells, preventing repeated rendering or another database from double-counting.

\begin{docCommand}{getAnimalCount}{\oarg{options}}
  Print the count from the animal data read so far. The default selects the
  entire |UpkeepLaboratoryAnimals| database. Use |group=mouse| to include all
  rows whose |total-group| is |mouse|, or |type=mouse| to match only that
  exact type. Both selectors require a registered type ID and cannot be
  combined. |database=MyAnimals| selects another database.
\end{docCommand}
\begin{docCommand}{getAnimalCosts}{\oarg{options}}
  Accept the same selectors and a |cost| option:
  \begin{description}
    \item[requested (default), existing] Sum the supplied requested or
      existing funding amounts.
    \item[purchase] Sum quantity times purchase price per animal.
    \item[housing] Sum quantity times average weeks kept times the row's
      own housing rate. Grouping never substitutes a shared rate.
    \item[total] Sum the calculated purchase and housing components.
  \end{description}
  Funding amounts print as whole EUR, matching the table. Calculated costs
  retain up to two decimal places; neither command adds a currency/unit suffix.
  These are formatted printing commands, not expandable numeric expressions.
\end{docCommand}
Both commands work before or after a table, after the relevant
|\addEntry| declarations. They read current data and grouping/rates, independently
of the last table's |totals-by| option. A registered selection with no rows
returns zero; unknown IDs, conflicting selectors, unknown options, and missing
databases produce a warning and a dash. Missing/invalid numeric inputs produce
an asterisk and a diagnostic. A partial calculated total includes all known
purchase/housing components; if none is known it prints a dash with an asterisk.
All required factors must be supplied, including for zero-quantity rows.
\begin{dispListing}
Mice: \getAnimalCount[group=mouse].
Only gnotobiotic mice: \getAnimalCount[type=mouse-gnotobiotic].
Requested: \getAnimalCosts[group=mouse,cost=requested]\,EUR.
Housing: \getAnimalCosts[group=mouse,cost=housing]\,EUR.
\end{dispListing}

\begin{dfgExample}[label={ex:manual-laboratory-animals-purchase-housing-and-funding},dfg wide,listing above* text]{Laboratory animals: purchase, housing, and funding}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id       = {A01},
  species              = {mouse},
  quantity             = {100},
  weeks-kept           = {12},
  purchasing-costs     = {25},
  requested-funds      = {9000},
  existing-funds       = {3000}
}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id       = {B03},
  species              = {rat},
  quantity             = {20},
  weeks-kept           = {8},
  purchasing-costs     = {40},
  requested-funds      = {1600},
  existing-funds       = {800}
}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id       = {A02},
  species              = {mouse-gnotobiotic},
  quantity             = {30},
  weeks-kept           = {10},
  purchasing-costs     = {50},
  requested-funds      = {6000},
  existing-funds       = {2500}
}
\DeclareAnimalType{zebrafish}{
  label={Zebrafish}, label-plural={Zebrafish}, housing-rate=0.12
}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id       = {A03},
  species              = {zebrafish},
  quantity             = {200},
  weeks-kept           = {12},
  purchasing-costs     = {2},
  requested-funds      = {688},
  existing-funds       = {0}
}
\printTable{UpkeepLaboratoryAnimals}
Mice: \getAnimalCount[group=mouse].\par
Requested for mice: \getAnimalCosts[group=mouse,cost=requested]\,EUR.\par
Housing for mice: \getAnimalCosts[group=mouse,cost=housing]\,EUR.
\end{dfgExample}

\subsection{Refer to financial totals in prose}

The near-identical funding names encode two different scopes.  Commands using
the singular name |RequestedFunding| use the proposal-wide
|RequestedFundingOverview| database by default.  Commands using the plural
name |RequestedFunds| use the project-level |RequestedFunding| database and
therefore require a project id.  In the signatures below,
\meta{sum-fields} means one or more fields such as |sum-year1| through
|sum-year5|.

\begin{description}
  \item[\cs{getCountRequestedStaff}]
    \oarg{project}\marg{year}\marg{category} prints the requested staff
    quantity, optionally restricted to one project.
    See \dfgExampleRef{ex:manual-requested-positions-and-multi-year-direct-costs}.

  \item[\cs{getSumRequestedFunding}]
    \oarg{database}\marg{year}\marg{type} prints the proposal-wide total for
    one funding type; use |year=all| for all five years.
    See \dfgExampleRef{ex:manual-project-counts-and-funding-totals}.

  \item[\cs{getTotalSumRequestedFunding}]
    \oarg{database}\marg{year}\marg{type} has the same proposal-wide scope and
    additionally accepts |type=all| for the grand total.
    See \dfgExampleRef{ex:manual-project-counts-and-funding-totals}.

  \item[\cs{getSumPreviousRequestedFunding}]
    \oarg{database}\marg{year}\marg{fields} totals the selected columns in
    the previous-period database; |year=all| includes every row.
  \item[\cs{getSumRequestedFunds}]
    \oarg{database}\marg{project}\marg{type}\marg{sum-fields} prints a
    project total for one funding type.
    See \dfgExampleRef{ex:manual-project-counts-and-funding-totals}.

  \item[\cs{getTotalSumRequestedFunds}]
    \oarg{database}\marg{project}\marg{sum-fields} prints a project total
    across all funding types.
    See \dfgExampleRef{ex:manual-project-counts-and-funding-totals}.

  \item[\cs{getSumRequestedFundsInstrumentation}]
    \oarg{project}\marg{sum-fields} prints the proposal-wide instrumentation
    total or restricts it to the optional project.
  \item[\cs{getSumRequestedFundingDirectCosts}]
    \oarg{database}\marg{year}\marg{group} totals direct costs for
    |applicant|, |participant|, |other-funds|, or |all|.
  \item[\cs{getSumExistingFunds}]
    \oarg{database}\marg{project}\marg{sum-fields} prints existing direct-cost
    funding for one project.
\end{description}

For example:
\begin{dfgExample}[label={ex:manual-project-counts-and-funding-totals}]{Project counts and funding totals}
Area A projects: \getProjectCount[A]\par
Staff: \getSumRequestedFunding{all}{staff}\par
Total: \getTotalSumRequestedFunding{all}{all}\par
A02 staff, year 1:
\getSumRequestedFunds{A02}{staff}{sum-year1}\par
A02 total, year 1:
\getTotalSumRequestedFunds{A02}{sum-year1}
\end{dfgExample}

Use the optional project argument to compare a project with the full request.
Here |1| is the first funding-year column; |PhD| is the staff category.
\begin{dfgExample}[label={ex:manual-requested-positions-and-multi-year-direct-costs}]{Requested positions and multi-year direct costs}
A02 doctoral positions, year 1:
\getCountRequestedStaff[A02]{1}{PhD}.\par
All doctoral positions, year 1:
\getCountRequestedStaff{1}{PhD}.\par
A02 direct costs, years 1 and 2:
\getSumRequestedFunds{A02}{costs}{sum-year1,sum-year2}\,EUR.
\end{dfgExample}

\section{Individual projects}
\label{sec:manual-project-status}
\subsection{Choose the structure from project status and type}
Set |project-status| in the project's metadata: |N| for new, |C| for continuing,
and |E| for ending. This is independent of |project-type|: |research|,
|service|, |mgk| (integrated research training), or |admin| (central coordination).
Changing metadata adjusts the generated heading and some tables; it does not
rewrite the authored sections. Start from the matching generated content file.

\begin{dfgExample}[label={ex:manual-new-continuing-and-ending-project-structures},dfg wide]{New, continuing, and ending project structures}
\begin{TableEnv}{X[1,l] X[2,l] X[3,l]}[row{1}={font=\bfseries}]
  {Choose a project structure}{tab:manual-project-status}
Status & Background & Forward-looking content \\
N: new & Research rationale and preliminary work
  & Project plan, collaborations, and requested funding \\
C: continuing & Progress to date and current state of research
  & Project plan, collaborations, and requested funding \\
E: ending & Project history, report, and published results
  & Closing funding and staff from the ending period
\end{TableEnv}
\end{dfgExample}

The starter files |03_project_A02.tex| and |03_project_A01.tex| demonstrate
new and continuing research projects, respectively. Both have a summary,
aims, work packages, a timeline, the relevance of sex/gender/diversity,
the project's CRC role, differentiation from other grants, and project funding.
The ending example |03_project_A00.tex| instead contains a report, three result
categories, and closing funding information; it does not request a new period
or present a new work programme.

For service projects, |03_project_Q01.tex| uses the continuing structure but
focuses on services, access, capacity, and quality assurance. The training
example |03_project_Q02.tex| and coordination example |03_project_Q03.tex|
have dedicated content structures. Their headings, like ending-project
headings, omit the research-area line. A |reference-only=true| project is a
separate concept: it records a former project for references and is excluded
from active counts. The manual's |A00| demonstrates this case.

\subsection{Start and finish a project}
\begin{docCommand}{printProject}{\oarg{setup code}\marg{specification}}
  Use the unified project-boundary interface.  Start a project with its id and
  finish the active project without repeating that id:
  \begin{dispListing}
    \printProject{{Head}{A01}}
    \ldots
    \printProject{{Tail}}
  \end{dispListing}
  The \texttt{Head} form delegates to \refCom{printProjectHead}; the
  \texttt{Tail} form delegates to \refCom{printProjectTail}.  The original
  commands remain available as compatibility fallbacks.

  An optional argument on \texttt{Head} runs setup code before the project
  header. Its local assignments remain active for the complete project and
  are restored by the matching \texttt{Tail}:
  \begin{dispListing}
    \printProject[
      \changeSettings{journalTitle=shortjournal,emphasizeEntries=false}
    ]{{Head}{B02}}
    % Project text, bibliographies, figures, and funding tables.
    \printProject{{Tail}}
  \end{dispListing}
  The argument contains executable LaTeX code, rather than a bare settings
  list. Both the unified tail and the legacy \cs{printProjectTail} close this
  scope. An explicitly empty argument |[]| also creates a project scope;
  omitting the argument retains the existing unscoped behaviour for projects
  without automatic ending-project defaults. Optional
  setup code is accepted only on \texttt{Head}; projects must not be nested.

  Scoped projects start on a new page and flush their last page before the
  settings are restored, including in \refKey{fastcompile-project} mode.
  This keeps page headers and deferred output within the project's scope.
  Always supply the matching tail. Only ordinary local assignments are
  restored; explicit global definitions remain global.

  When the loaded project metadata has \refKey{project-status} |E|, the head
  automatically selects |emphasizeAuthors=true,emphasizeEntries=false| in a
  project scope, even without an optional argument. Explicit setup code runs
  afterwards and takes precedence, for example:
  \begin{dispListing}
    \printProject[
      \changeSettings{emphasizeAuthors=false,emphasizeEntries=true}
    ]{{Head}{B02}}
    % This project overrides the ending-project emphasis defaults.
    \printProject{{Tail}}
  \end{dispListing}
  The default is selected from metadata, rather than from a project's ID.
  Metadata-free fast project builds cannot infer a status; explicit setup
  code remains available in that mode.

  This mechanism applies to settings read while the project is rendered,
  such as \refKey{journalTitle}, \refKey{emphasizeEntries}, and funding rates.
  It does not reload packages or rerun class initialization: bibliography
  styles and the initial font-family setup still belong in the customization
  file before the class loads their packages.

  See \dfgExampleRef{ex:manual-new-project-heading-excerpt-from-the-starter-proposal}, \dfgExampleRef{ex:manual-ending-project-heading-excerpt-from-the-starter-proposal}.
\end{docCommand}

\begin{docCommand}{printProjectHead}{\oarg{setup code}\marg{project-id}}
  Start the section for one project.  The command sets the current project,
  creates the project heading, resets project-local counters, starts a
  bibliography refsection, prints the project leaders, and prepares the
  project-specific thumbindex and headers.  Active research and service
  projects also receive the DFG research-areas heading from their
  \refKey{research-area} metadata; ending, MGK, and administrative projects do
  not.  For every person id in the
  project's comma-separated \refKey{ref-person-id} value, all names stored in
  \refKey{name-alias} are registered as emphasized bibliography names.  An
  empty alias value is ignored.
  The optional setup argument and automatic ending-project emphasis defaults
  are the same as for the unified \cs{printProject} interface. The
  |projectTitle| customization independently selects full or short titles
  in the TOC, running head and \enquote{Project title:} heading; all three
  initially use the full \refKey{name}. See the |projectTitle| examples.

  With \refKey{fastcompile-project}, the current-project state, counters,
  labels, a compact running header containing the project ID, and the optional
  bibliography refsection are prepared.  A light hook-based draft watermark is
  added to every shipped page. The calculated heading, project-leader cards,
  contract information and legal-issues table are replaced by a labeled
  \texttt{<project-id-header>} placeholder. Its space and the following section
  counters come from the last normal build's ordinary \texttt{.aux} file,
  including any complete header pages. Header metadata are not read for this.
  The thumb index and table-of-contents entry are omitted.

  Keep auxiliary files when switching modes. After changes to header metadata,
  fonts or layout, compile normally until the header settles, then return to
  focused mode. The snapshot is checked against the current text width and
  height; other changes require that explicit normal refresh. Without a
  matching record, a warning and an \texttt{approximate half text height} label identify
  the fallback, which reserves half of the current \cs{textheight}.
  Its spacing is an estimate, and the first authored section
  still follows General information as section 2.

  See \dfgExampleRef{ex:manual-continuing-project-heading-excerpt-from-the-starter-proposal}.
\end{docCommand}

\begin{docCommand}{printProjectTail}{}
  Finish the current project section.  The command closes the bibliography
  refsection, resets bold bibliography names, restores the table-of-contents
  depth, and starts a new page.  In \refKey{fastcompile-project}, it only closes
  the optional publication refsection and does not force a page break.
  When the project was opened with optional setup code or automatic
  ending-project defaults, the tail also closes that setup scope and restores the
  preceding settings; in this case it flushes the final project page even in
  fast project mode.

  See \dfgExampleRef{ex:manual-continuing-project-heading-excerpt-from-the-starter-proposal}.
\end{docCommand}

These commands manage complete pages and bibliography sections. The following
code/result examples therefore show the beginning of the actual example
proposal pages, rather than running a project wrapper inside the manual's
own section. The complete proposal and inline examples share the same
metadata. The omitted project body belongs between the two commands.
Former project |A00| illustrates the ending-project structure; it remains
excluded from active project counts and funding requests.

\begin{dfgExample}[label={ex:manual-new-project-heading-excerpt-from-the-starter-proposal},dfg wide,listing and comment,
  comment={\dfgDocProjectExcerpt{A02}{200mm}}]{New project: heading excerpt from the example proposal}
% In project metadata: project-status = {N}
\printProject{{Head}{A02}}
% Summary, research rationale, plan, and funding.
\printProject{{Tail}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-continuing-project-heading-excerpt-from-the-starter-proposal},dfg wide,listing and comment,
  comment={\dfgDocProjectExcerpt{A01}{200mm}}]{Continuing project: heading excerpt from the example proposal}
% In project metadata: project-status = {C}
\printProjectHead{A01}
% Summary, progress to date, plan, and funding.
\printProjectTail
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-ending-project-heading-excerpt-from-the-starter-proposal},dfg wide,listing and comment,
  comment={\dfgDocProjectExcerpt{A00}{218mm}}]{Ending project: heading excerpt from the example proposal}
% In project metadata: project-status = {E}
\printProject{{Head}{A00}}
% Project history, published results, closing funding.
\printProject{{Tail}}
\end{dfgExample}

\subsection{Publications for new and continuing projects}
\begin{docCommand}{projectPublicationsHeading}{}
  Print the standard project-publications subsection heading only when
  \refKey{fastcompile-project-show-publications} is enabled.

  See \dfgExampleRef{ex:manual-project-publications-with-the-standard-heading}.
\end{docCommand}

\begin{docCommand}{projectNocite}{\marg{entry keys}}
  Add project publication entries with \cs{nocite} only when
  \refKey{fastcompile-project-show-publications} is enabled.

  See \dfgExampleRef{ex:manual-project-publications-with-the-standard-heading}.
\end{docCommand}

\begin{docCommand}{printProjectBibliography}{\oarg{biblatex options}}
  Print a project bibliography only when \refKey{fastcompile-project-show-publications} is
  enabled.  Use these three project-specific commands together so disabling
  publication output also removes its heading and explicit bibliography work.
  Project bibliography entries are typeset in \cs{footnotesize}.  With
  \refKey{emphasizeEntries} enabled, an entry carrying the current project's
  \texttt{<project-id>-highlight} keyword is printed in bold.  A direct
  \cs{printbibliography} call bypasses this formatting, the font setting,
  and the publication-output switch.

  See \dfgExampleRef{ex:manual-project-publications-with-the-standard-heading}.
\end{docCommand}

A local |refsection| keeps this example's bibliography independent of the
manual. In an ordinary project, use the reference section established by the
project wrapper. The leading options are passed to |biblatex|.
\begin{dfgExample}[label={ex:manual-project-publications-with-the-standard-heading},dfg wide,dfg project=A02]{Project publications with the standard heading}
\begin{refsection}
\projectPublicationsHeading
\projectNocite{FAIR2016}
\printProjectBibliography[heading=none]
\end{refsection}
\end{dfgExample}

\subsection{Project plan: aims and work packages}

For writing aims and workpackages we provide some special commands and features, including a gantt-chart.

\begin{docEnvironment}{aims}{\oarg{options}}
  Environment to be used in a project section to summarize in a condensed way the aims of the project.
  Use |label={RDM Aims}| to replace the default |Aim| prefix, keeping the
  item number and colon. The same text is used verbatim for singular and
  plural references through \cs{cref}, \cs{Cref}, and \refCom{getAim},
  including references outside the list or before it. Compile twice after
  changing labels. Without this option, the defaults remain |Aim| and |Aims|.
  Other list options, such as |start=3| and |itemsep=2pt|, are passed to
  \pkg{enumitem}.

  Use |resume| to continue numbering from the previous |aims| list.
  Repeat the custom prefix, as in |[label={RDM Aims},resume]|, to keep it
  in the numbered items and their cross-references. With |[resume]| alone,
  numbering continues but the prefix returns to the default |Aim|/|Aims|.
  Resuming uses the previous |aims| list regardless of its label text;
  custom labels do not create separate counters.

  See \dfgExampleRef{ex:manual-aims-and-their-references}.
\end{docEnvironment}

\begin{docCommand}{addAim}{\marg{label}}
  Add an aim within the \refEnv{aims} environment. You can refer to this aim by using \refCom{getAim}\marg{label}.

  See \dfgExampleRef{ex:manual-aims-and-their-references}.
\end{docCommand}

These aim and work-package examples use project |A03| as their current
project, as normally established by \cs{printProjectHead}.

\begin{dfgExample}[label={ex:manual-aims-and-their-references},dfg project=A03]{Aims and their references}
\begin{aims}
  \addAim{manual-a} Identify pathways.
  \addAim{manual-b} Validate biomarkers.
  \addAim{manual-c} Test interventions.
\end{aims}
See \getAim{manual-a,manual-b,manual-c}.
\begin{aims}[label={RDM Aims}]
  \addAim{manual-rdm-a} Document research data.
  \addAim{manual-rdm-b} Publish reusable datasets.
\end{aims}
See \getAim{manual-rdm-a,manual-rdm-b}.
\begin{aims}[label={RDM Aims},resume]
  \addAim{manual-rdm-c} Archive the datasets.
\end{aims}
Continued as \getAim{manual-rdm-c}.
\end{dfgExample}

\begin{docCommand}{getAim}{\marg{label}}
  Refer to an aim with the \marg{label} in the \refEnv{aims} environment.
  You can refer to multiple aims, too: |\getAim{A,B,C}|.

  The default is referencing the aims of the same project.
  You can also refer to an aim of a different project:
  \cs{getAim}\oarg{project-id}\marg{label}.

  See \dfgExampleRef{ex:manual-aims-and-their-references}, \dfgExampleRef{ex:manual-references-to-another-project-s-work-packages}.
\end{docCommand}


\begin{docEnvironment}{workpackages}{}
  Environment to be used in a project section when workpackages are written.
  This environment contains all descriptions of the workpackages that are introduced by
  \refCom{addWP}.

  See \dfgExampleRef{ex:manual-work-packages-and-their-references}, \dfgExampleRef{ex:manual-nested-work-packages-and-mixed-references}.
\end{docEnvironment}

\begin{docCommand}{addWP}{\marg{label}\marg{key=values}}
  Add a work package with the stable identifier \meta{label}. Use |title| for
  its narrative heading and group chart-specific settings under |gantt|.
  At the top level, the title is printed as a bold work-package heading.
  Sub-workpackages start directly with the authored prose after their list
  label; their title is not printed as a heading. Immediate source whitespace,
  including a blank line after \cs{addWP}, is consumed for sub-workpackages.

  The existing flat keys remain supported without deprecation warnings.
  Both syntaxes work in normal and focused project compilation, including
  focused mode with images disabled. The new syntax requires a class extracted
  from this updated source; older released classes accept the flat syntax only.

  See \dfgExampleRef{ex:manual-work-packages-and-their-references},
  \dfgExampleRef{ex:manual-gantt-label-fallbacks}, and
  \dfgExampleRef{ex:manual-nested-work-packages-and-mixed-references}.
\end{docCommand}

\begin{docKey}{title}{=\meta{text}}{}
  Narrative heading for a first-level work package. This value also supplies
  the default chart label when neither |gantt/label| nor the legacy
  |description| key has been supplied in a declaration using the new syntax.
  An explicitly empty |title={}| overrides |name|; focused mode then retains
  its existing WP-ID heading fallback.
\end{docKey}

\noindent\begin{minipage}{\linewidth}
\begin{docKey}{gantt}{=\meta{key-value list}}{}
  Group of chart-specific options: |label|, |start|, |end|, and |style|.
  The notation |gantt/label| below means |label| inside this group.
\end{docKey}
\end{minipage}\par

\noindent|gantt/label| is the text printed after the work-package reference in
    the chart. Omission uses the resolved title, unless a legacy |description|
    is present. An explicitly empty |label={}| suppresses this text while
    retaining the work-package reference and its link.

\noindent|gantt/start| and |gantt/end| specify positions on the existing
    1--16 chart axis. Supply both when plotting a scheduled work package.
    Equal endpoints suppress its bar, as with the legacy period keys.
    These values do not change the chart's existing calendar or units.

\noindent|gantt/style| selects the bar style: |default|, |alternative|, |crosshatch|,
    |important|, or |striped|. Omission selects |default|. An invalid value
    warns and falls back to |default|; an empty style selects the default
    without a warning. See also \refKey{style} for the colour settings.

\paragraph{Compatibility and precedence}
The following flat keys continue to work in \cs{addWP}. They also remain the
stored database field names, so existing \cs{getEntry} queries and direct
|\addEntry[gantt]| declarations keep working.
\begin{center}
\begin{tabular}{ll}
\textbf{Existing key} & \textbf{New key} \\
\hline
|name|        & |title| \\
|description| & |gantt/label| \\
|periodStart| & |gantt/start| \\
|periodEnd|   & |gantt/end| \\
|style|       & |gantt/style|
\end{tabular}
\end{center}

You can migrate one field at a time. For each field, an explicitly supplied
new key takes precedence over its flat counterpart, regardless of their order
in the declaration. If the new key is absent, the flat value is used. Explicit
empty values count as supplied: |gantt={label={}}| overrides a nonempty
|description|. In declarations using the new syntax, repeated assignments
within one spelling use the last value. Legacy-only declarations retain the
original parser and its validation.
Values are stored without expansion, preserving formatting commands and
references for their output context.

The title-to-label fallback applies only when |title| or |gantt| occurs.
A declaration using only the old keys retains its previous output: a missing
or empty |description| does not suddenly produce a label from |name|.
For example, |title={New heading}| overrides |name={Old heading}|, while
|description={Short label}| still supplies the chart label.
The new keys belong to \cs{addWP}; direct |\addEntry[gantt]| calls continue to
use the existing flat database keys.

\begin{dfgExample}[label={ex:manual-work-packages-and-their-references},dfg wide,dfg project=A03,leftlower=12mm,unbreakable]{Work packages and their references}
\begin{workpackages}
  \addWP{manual-wp1}{
    title={Identify pathways},
    gantt={label={Pathway discovery},
      start=1, end=6, style=alternative}
  }
  Collect and analyse samples.
  \addWP{manual-wp2}{
    title={Validate biomarkers},
    gantt={label={Validation},
      start=7, end=12, style=important}
  }
  Test independent cohorts.
\end{workpackages}
See \getWP{manual-wp1,manual-wp2}.
\end{dfgExample}

The next example uses project |A04|. The first chart row inherits its text
from |title|. The second keeps only its WP reference because its chart label
is explicitly empty. The narrative headings are independent of this choice.
\begin{dfgExample}[label={ex:manual-gantt-label-fallbacks},dfg wide,dfg project=A04,leftlower=12mm,unbreakable]{Grouped Gantt options: omitted and empty labels}
\begin{workpackages}
  \addWP{manual-label-title}{
    title={Analyse imaging data},
    gantt={start=1, end=8}
  }
  Develop and validate the analysis tools.
  \addWP{manual-label-empty}{
    title={Coordinate imaging services},
    gantt={label={}, start=4, end=16,
      style=alternative}
  }
  Support the collaborating projects.
\end{workpackages}
\printPlot{{gantt}}
\end{dfgExample}


Furthermore, PI, work-package, and aim references each have an independent
color setting. They default to |black| and are independent of
\refKey{color@reference@boldAuthor}. Configure them with \cs{changeSettings}:
\begin{dispListing}
  \changeSettings{
    color@reference@PI  = my-blue,
    color@reference@WP  = my-blue,
    color@reference@Aim = my-blue
  }
\end{dispListing}

\begin{docCommand}{getWP}{\marg{label}}
  Refer to a workpackage with the \marg{label} in the \refEnv{workpackages} environment.
  You can refer to multiple workpackages, too: |\getWP{wp2,wp3,wp4}|.
  Consecutive references under the same parent work package are compacted into
  a range.  Its |to| connector uses the surrounding font weight while the
  |WPs| prefix and endpoint labels stay bold. A narrow, unbreakable space
  separates |WP| or |WPs| from its number. References under later parent
  work packages remain separate and are not discarded during compaction.

  The default is referencing the workpackage of the same project.
  You can also refer to a workpackage of a different project:
  \cs{getWP}\oarg{project-id}\marg{label}.
  Parent and nested work packages can be combined in one call, for example
  |\getWP{wp1a,wp1b,wp2,wp3a,wp3b}|. The parent |wp2| is retained alongside
  the nested items; sorting follows the hierarchy and ranges do not cross
  parent boundaries.

  See \dfgExampleRef{ex:manual-work-packages-and-their-references}, \dfgExampleRef{ex:manual-nested-work-packages-and-mixed-references}.
\end{docCommand}

For this example the current project is |B04|. Parent and nested work packages
can be referenced together; nested ranges stay within their parent.
\begin{dfgExample}[label={ex:manual-nested-work-packages-and-mixed-references},dfg wide,dfg project=B04,leftlower=12mm]{Nested work packages and mixed references}
\begin{workpackages}
  \addWP{manual-nested-1}{title={Discovery}}
  \begin{workpackages}
    \addWP{manual-nested-1a}{} Recruit participants.
    \addWP{manual-nested-1b}{} Profile samples.
    \addWP{manual-nested-1c}{} Validate signals.
  \end{workpackages}
  \addWP{manual-nested-2}{title={Translation}}
  Test the selected intervention.
\end{workpackages}
See \getWP{manual-nested-1a,manual-nested-1b,manual-nested-1c,manual-nested-2}.
\end{dfgExample}

The next example is in |A03|. Its explicit |[B04]| argument points back to
the work packages above, while |[A03]| selects the earlier aim example.
\begin{dfgExample}[label={ex:manual-references-to-another-project-s-work-packages},dfg project=A03]{References to another project's work packages}
Exchange samples with
\getWP[B04]{manual-nested-1a,manual-nested-2}.\par
This supports \getAim[A03]{manual-a,manual-c}.
\end{dfgExample}






While some keys have been described already, here is what is missing so far:
\begin{docKey}{style}{\docKeyChoices{default,alternative,crosshatch,important,striped}}{initially: \texttt{default}}

  Define the style of the bar of this workpackage in the gantt-chart.

  For customizing the colors of the various styles have a look at:
  \refKey{color@gantt@default},
  \refKey{color@gantt@alternative},
  \refKey{color@gantt@crosshatch},
  \refKey{color@gantt@important},
  \refKey{color@gantt@stripe-one} and
  \refKey{color@gantt@stripe-two}.

  See \dfgExampleRef{ex:manual-gantt-five-bar-styles},
  \dfgExampleRef{ex:manual-gantt-custom-colours}, and
  \dfgExampleRef{ex:manual-gantt-grayscale}.
\end{docKey}

\subsection{Timeline and collaboration plots}
\begin{docCommand}{printPlot}{\oarg{options}\marg{plot specification}}
  Print a Gantt or collaboration plot.  Use the lowercase type names
  |gantt| and |collaboration| in the braced specification.  The second
  braced item selects a project, as in |\printPlot{{gantt}{B06}}| or
  |\printPlot{{collaboration}{B06}}|.  Omit the project ID inside a project
  to use its current ID: |\printPlot{{gantt}}| or
  |\printPlot{{collaboration}}|.  Without a current project, give the ID.
  Place plot options before the specification, for example
  |\printPlot[arcs=true]{{collaboration}{B06}}| or
  |\printPlot[caption={Additional details}]{{gantt}}|.  Use the same leading
  caption option with an explicit ID, as in
  |\printPlot[caption={Additional details}]{{gantt}{B06}}|.
  Captions default to below the plots; older trailing captions remain supported.
  Both plot types forward all other options to \refCom{hvFloat}, for example
  |\printPlot[floatPos=!t,caption={}]{{gantt}{Q01}}| or
  |\printPlot[floatPos=!t,capPos=top,arcs=true]{{collaboration}{B06}}|.
  Plot-specific keys such as |caption|, |layout|, and |arcs| are handled by the
  class; the remaining keys are interpreted and validated by |hvfloat|.
  Defaults are |floatPos=!hb| and |capPos=bottom|. Explicit options override
  these defaults for that call only, including through compatibility aliases.
  Use \refKey{plotOptions} in \refCom{changeSettings} for shared defaults, and
  \refKey{ganttPlotOptions} or \refKey{collaborationPlotOptions} for one type.
  These settings also accept native |style=| names. The class supplies
  |proposalPlots|; see the customization examples below.
  Gantt figures always have the label |fig:gantt-<project-id>|, independently
  of additional caption text. For project A02, use |\cref{fig:gantt-A02}|.
  The same label applies to the compatibility command |\printGantt|.
  Update older caption-free references such as |fig:ganttA02| to the dashed form.
  By default, both plot types prefer their source position and may otherwise
  move to the bottom of the current or a later page. Selecting a different
  |floatPos| explicitly changes this placement policy.
  For either plot type, an empty |caption={}| leaves the default caption intact
  and serves as a placeholder for additional project-specific text.
  The former type names |Gantt|, |ProjectCollaboration|, and the plural
  lowercase |collaborations| remain accepted as compatibility aliases.

  The collaboration arc diagram is the default.  Select the heatmap with
  |layout=heatmap|.  Heatmap
  columns use a shared dynamic box width based on the project area with the
  most projects, and inactive no-collaboration projects have white backgrounds.
  Project areas are read from the optional |project-area| field of each
  |project| entry; if it is absent, the first character of the project ID is
  used.  Rows are created for every distinct area, ordered by area and project
  ID.  The familiar A, B, and Q colors are retained; other areas use a rotating
  palette.  Override individual colors with
  |area-colors={C=orange,D=violet}| or replace the fallback palette with
  |area-palette={teal,brown,magenta}| in the plot options.  Use
  \refKey{collaborationAreaColors} and
  \refKey{collaborationAreaPalette} in \refCom{changeSettings} to apply the
  same customization to every collaboration plot.

  See \dfgExampleRef{ex:manual-gantt-chart-of-the-current-project}, \dfgExampleRef{ex:manual-current-project-connections-as-arcs}, \dfgExampleRef{ex:manual-explicit-project-heatmap-and-caption}.
  For bar colours and patterns, see
  \dfgExampleRef{ex:manual-gantt-five-bar-styles} and
  \dfgExampleRef{ex:manual-gantt-custom-colours}.
\end{docCommand}

\paragraph{Live plot variants}
\label{sec:manual-plot-examples}
For examples without an explicit ID, the current project is |A03|, as it
would be after |\printProjectHead{A03}|. Specifying |B04| overrides that
context for that call. Each example starts with the default plot options.

\begin{dfgExample}[label={ex:manual-collaborations-of-the-current-project},dfg wide,dfg project=A03]{Collaborations of the current project}
\printPlot{{collaboration}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-explicit-id-overrides-the-current-project},dfg wide,dfg project=A03]{Explicit ID overrides the current project}
\printPlot{{collaboration}{B04}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-current-project-connections-as-arcs},dfg wide,dfg project=A03]{Current-project connections as arcs}
\printPlot[arcs=true]{{collaboration}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-current-project-heatmap},dfg wide,dfg project=A03]{Current-project heatmap}
\printPlot[layout=heatmap]{{collaboration}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-explicit-project-heatmap-and-caption},dfg wide,dfg project=A03]{Explicit-project heatmap and caption}
\printPlot[layout=heatmap,caption={Shared experimental platforms.}]
  {{collaboration}{B04}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-custom-project-area-colours},dfg wide,dfg project=A03]{Custom project-area colours}
\printPlot[layout=heatmap,area-colors={A=teal,B=orange,Q=violet}]
  {{collaboration}{A03}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-layout-aliases-and-additional-caption},dfg wide,dfg project=A03]{Layout aliases and additional caption}
\printPlot[arc-diagram,caption={Partners of the imaging service.}]
  {{collaboration}{Q01}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-gantt-chart-of-the-current-project},dfg wide,dfg project=A03]{Gantt chart of the current project}
\printPlot[caption={Discovery followed by validation.}]{{gantt}}
\end{dfgExample}

\begin{dfgExample}[label={ex:manual-gantt-chart-with-explicit-project-id},dfg wide,dfg project=A03]{Gantt chart with explicit project ID}
\printPlot{{gantt}{A03}}
\end{dfgExample}

For older sources, |Gantt| means |gantt|; |ProjectCollaboration| and
|collaborations| mean |collaboration|. These aliases render the same results
and accept the same leading options.

\paragraph{Gantt bar styles and colours}
\label{sec:manual-gantt-colours}
Choose a bar's appearance with |gantt={style=...}| in \refCom{addWP}.
The flat \refKey{style} key remains supported.
The three solid fills are |default|, |alternative|, and |important|;
|crosshatch| adds a hatch pattern, and |striped| alternates two colours.
The following example defines one work package of each style in |B06|.
Its five rows are reused in the palette examples below, so the colours can
be compared without changing the work plan.

\begin{dfgExample}[label={ex:manual-gantt-five-bar-styles},dfg wide,dfg project=B06,leftlower=12mm]{Five Gantt bar styles}
\begin{workpackages}
  \addWP{manual-colour-default}{
    title={Baseline},
    gantt={label={Default}, start=1, end=6, style=default}
  }
  \addWP{manual-colour-alternative}{
    title={Parallel analysis},
    gantt={label={Alternative}, start=3, end=9, style=alternative}
  }
  \addWP{manual-colour-important}{
    title={Validation},
    gantt={label={Important}, start=7, end=12, style=important}
  }
  \addWP{manual-colour-crosshatch}{
    title={Integration},
    gantt={label={Crosshatch}, start=9, end=14, style=crosshatch}
  }
  \addWP{manual-colour-striped}{
    title={Joint experiments},
    gantt={label={Striped}, start=11, end=16, style=striped}
  }
\end{workpackages}
\printPlot[caption={One row for each built-in bar style.}]{{gantt}{B06}}
\end{dfgExample}

For a document-wide palette, put \cs{changeSettings} in
|preamble/dfg-customization.tex|. These colour settings are applied at
|\begin{document}|. They accept colour names and xcolor mixes such as
|teal!45|. The |frame| colour controls the outline of the bars, while
|crosshatch| controls the hatch strokes and |stripe-one|/|stripe-two|
control the two alternating stripe colours.
\begin{dispListing*}{title={Document-wide Gantt palette: place in the customization file}}
\changeSettings{
  color@gantt@default     = {teal!45},
  color@gantt@alternative = {orange!50},
  color@gantt@important   = {violet!70},
  color@gantt@crosshatch  = {black!25},
  color@gantt@stripe-one  = {teal!20},
  color@gantt@stripe-two  = {teal!80},
  color@gantt@frame       = {black!50}
}
\end{dispListing*}

To recolour just one chart after the document has started, use
\cs{colorlet} on the live colour names inside a group. The next example
also defines an RGB colour; the surrounding group restores the previous
palette afterwards. The colour names are set before \refCom{printPlot};
they are not plot options.

\begin{dfgExample}[label={ex:manual-gantt-custom-colours},dfg wide,dfg project=B06]{Custom colours for one Gantt chart}
\begingroup
\definecolor{ganttOcean}{RGB}{0,114,178}
\colorlet{color@gantt@default}{ganttOcean!45}
\colorlet{color@gantt@alternative}{teal!50}
\colorlet{color@gantt@important}{orange!90}
\colorlet{color@gantt@crosshatch}{violet!35}
\colorlet{color@gantt@stripe-one}{ganttOcean!25}
\colorlet{color@gantt@stripe-two}{ganttOcean!55}
\colorlet{color@gantt@frame}{black!50}
\printPlot[caption={Custom fills, coloured hatching, and two-tone stripes.}]
  {{gantt}{B06}}
\endgroup
\end{dfgExample}

For grayscale output, use different gray levels and retain the hatch and
stripe patterns. The following chart uses the same work packages and dates;
its black outlines make the bar boundaries explicit.

\begin{dfgExample}[label={ex:manual-gantt-grayscale},dfg wide,dfg project=B06]{Grayscale Gantt bars with patterns}
\begingroup
\colorlet{color@gantt@default}{black!20}
\colorlet{color@gantt@alternative}{black!35}
\colorlet{color@gantt@important}{black!50}
\colorlet{color@gantt@crosshatch}{black!25}
\colorlet{color@gantt@stripe-one}{white}
\colorlet{color@gantt@stripe-two}{black!35}
\colorlet{color@gantt@frame}{black}
\printPlot[caption={Grayscale fills with hatching and stripes.}]{{gantt}{B06}}
\endgroup
\end{dfgExample}

\subsection{Individual project funding}
\label{sec:manual-project-funding}
The example below adds a funding request for |A06|, whose project metadata
are already loaded. It covers all five funding groups: |staff|, |costs|,
|fellowships|, |globalfunds|, and |instrumentation|. The doctoral position at
65\% uses the configured annual salary; the other groups specify full EUR
amounts directly, including a one-off equipment purchase. The year headings
and partial-year factors come from |meta.fundingYears|. The earlier |A02|
funding examples use separate records.

\begin{dfgExample}[label={ex:manual-requested-funding-for-a-project},dfg wide,listing above* text,after={\par\clearpage}]{Requested funding for a project}
\changeSettings{salary@PhD=83700}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A06},
  funding-type   = {staff},
  category       = {PhD},
  percentage     = {65},
  quantity       = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  }
}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A06},
  funding-type   = {costs},
  category       = {consumables},
  sum            = {
    year1 = {1000},
    year2 = {2000},
    year3 = {2000},
    year4 = {2000},
    year5 = {1000}
  }
}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A06},
  funding-type   = {fellowships},
  category       = {Short-term research fellowships},
  sum            = {
    year1 = {3000},
    year2 = {6000},
    year3 = {6000},
    year4 = {6000},
    year5 = {3000}
  }
}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A06},
  funding-type   = {globalfunds},
  category       = {Training and networking},
  sum            = {
    year1 = {1500},
    year2 = {3000},
    year3 = {3000},
    year4 = {3000},
    year5 = {1500}
  }
}
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A06},
  funding-type   = {instrumentation},
  category       = {Imaging workstation},
  sum            = {
    year1 = {20000},
    year2 = {0},
    year3 = {0},
    year4 = {0},
    year5 = {0}
  }
}
\printTable[note={Illustrative amounts for this example.}]{{RequestedFunding}{A06}}
\end{dfgExample}

The project staff roster describes who does the work. It uses |staff| records
in |RequestedFundingStaff|; monetary requests remain separate |funding|
records. Existing staff may inherit their name and institution through
|ref-person-id|. Use |lastname={TBA}| for an unnamed requested position.
The |description| text is printed as a numbered job description below the table.

\begin{dfgExample}[label={ex:manual-project-staff-an-existing-investigator-and-a-doctoral-vacancy},dfg wide,listing above* text]{Project staff: an existing investigator and a doctoral vacancy}
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id    = {B03},
  funding-status    = {existing},
  staff-type        = {research},
  ref-person-id     = {per11},
  field-of-research = {Immunology},
  commitment        = {8},
  funding-source    = {State funds},
  description       = {Supervises the experiments and data analysis.}
}
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {B03},
  funding-status     = {requested},
  staff-type         = {research},
  lastname           = {TBA},
  positionText       = {Doctoral researcher (65\%)},
  field-of-research  = {Immunology},
  ref-institution-id = {ins1},
  category           = {PhD},
  description        = {Performs longitudinal experiments and prepares the thesis.}
}
\printTable{{RequestedFundingStaff}{B03}}
\end{dfgExample}

Existing direct-cost funding is declared separately from new requests. The
following records identify the participating affiliations and funding sources;
the |sum| values are full EUR amounts for each funding-year column.

\begin{dfgExample}[label={ex:manual-existing-direct-cost-funding-from-two-sources},dfg wide,listing above* text]{Existing direct-cost funding from two sources}
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {B03},
  ref-affiliation-id = {aff1},
  financed-by        = {University core funds},
  sum                = {
    year1 = {1000}, year2 = {2000}, year3 = {2000}, year4 = {2000}, year5 = {1000}
  }
}
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {B03},
  ref-affiliation-id = {aff2},
  financed-by        = {Partner university},
  sum                = {
    year1 = {500}, year2 = {1000}, year3 = {1000}, year4 = {1000}, year5 = {500}
  }
}
\printTable{{RequestedAndExistingFundingDirectCosts}{B03}}
\end{dfgExample}

\begin{docEnvironment}{FundingDirectCostsTable}{\oarg{heading}}
  Typeset a three-column breakdown of direct costs that can continue across
  pages. Page breaks occur between rows; an individual row stays together.
  The optional heading stays with the first row and is printed once, without
  a table number or a list-of-tables entry. Continuation notices identify
  subsequent parts of the table.
  The gap above the heading (or above the table if no heading is supplied)
  uses \cs{dfgTablePreSep}, like the long tables. A fixed 4\,pt gap separates
  an optional heading from the table itself.
  The currency column uses its natural width so that codes such as EUR fit
  in the selected font; the description column fills the remaining width.

  See \dfgExampleRef{ex:manual-explain-individual-direct-cost-items}.
\end{docEnvironment}

\begin{dfgExample}[label={ex:manual-explain-individual-direct-cost-items}]{Explain individual direct-cost items}
\begin{FundingDirectCostsTable}[Consumables]
  Assay reagents & EUR & 1200 \\
  Culture media & EUR & 800 \\
\end{FundingDirectCostsTable}
\end{dfgExample}

\subsection{Report and results of an ending project}
\begin{docCommand}{printProjectResults}{\marg{key-value list}}
  Print the three result categories required for an ending project.  The keys
  \texttt{quality-assured}, \texttt{other}, and \texttt{patents} each accept a
  comma-separated list of bibliography entry keys.  Use the literal value
  \texttt{none} when a category produced no results.  An omitted or empty key
  retains a drafting instruction instead, so an unfinished list is not
  accidentally reported as empty.

  Every non-empty category is placed in a separate \pkg{biblatex}
  reference segment within the reference section opened by
  \cs{printProjectHead}.  Consequently, category membership is local to the
  current project.  The command also places any pending floats before the
  result lists.

  The combined result-key list is written to the project's auxiliary file.
  On the next normal \LaTeX{} pass, a \texttt{projectReport} bibliography uses
  this list to omit report citations that are printed later as project
  results.  This follows the usual \pkg{biblatex} compilation cycle and does
  not require the entry keys to be duplicated in the report.

  See \dfgExampleRef{ex:manual-published-results-of-an-ending-project}.
\end{docCommand}

\begin{docEnvironment}{projectReport}{}
  Isolate all citations in the project report in their own reference segment
  and print that segment's bibliography at the end of the environment.  Any
  entries assigned to \cs{printProjectResults} for the same project are
  omitted, because they are printed in the later result lists.  Place the
  environment immediately after the report subsection heading and label.

  See \dfgExampleRef{ex:manual-published-results-of-an-ending-project}.
\end{docEnvironment}

\begin{dfgExample}[label={ex:manual-published-results-of-an-ending-project},dfg wide,dfg project=A00]{Published results of an ending project}
\begin{refsection}
\begin{projectReport}
  Follow the FAIR principles \cite{FAIR2016}
  and document software design \cite{Hoare1973}.
\end{projectReport}
\printProjectResults{
  quality-assured={FAIR2016},
  other=none,
  patents=none
}
\end{refsection}
\end{dfgExample}

For |project-status=E|, the staff table reuses
|\printTable{{RequestedFundingStaff}{project-id}}|. Rows with
|funding-status=requested| describe staff funded with approved grant money
in the ending period, rather than a request for a new period. The complete
B02 example shows this closing table together with its input records.

\section{Bylaws and declarations}
The bylaws are authored prose in |content/04_bylaws-of-the-crc.tex|. Use the
applicant-wording helper introduced with the title page for singular or plural
university names. The declaration file |content/05_declarations.tex| then
prints the required signatures from the same person metadata.

\begin{docCommand}{printSignature}{\oarg{database}\marg{id-description-pairs}}
  Print one signature block for each \marg{id}\marg{description} pair.  The
  \meta{database} defaults to \texttt{person}.  Inside \meta{description},
  \cs{theAffiliationOfRoleID} contains the person's affiliation id and can be
  used for further database lookups.

  See \dfgExampleRef{ex:manual-signature-blocks}.
\end{docCommand}

\begin{docCommand}{printSignaturesWithRole}{\oarg{database}\marg{role}\marg{description}}
  Print a signature block for every current-period person with \meta{role}.
  This is used for the rector, chancellor, or president of every applicant
  university, so a proposal with several applicants does not require a
  hard-coded list of person ids.  Inside \meta{description},
  \cs{theAffiliationOfRoleID} refers to the affiliation of the current
  signatory.

  See \dfgExampleRef{ex:manual-select-signatories-by-role}.
\end{docCommand}

\begin{dfgExample}[label={ex:manual-signature-blocks},dfg wide]{Signature blocks}
\printSignature{
  {spokesperson}{(Spokesperson of \thisCRC)}
  {rector}{(Rector of Example University)}
}
\end{dfgExample}

The role-based form resolves the affiliation for each signatory; it avoids
repeating names or maintaining a separate list of rectors in the content.
\begin{dfgExample}[label={ex:manual-select-signatories-by-role},dfg wide]{Select signatories by role}
\printSignaturesWithRole{rector}{%
  Rector of
  \get[affiliation]{\theAffiliationOfRoleID}{name}}
\end{dfgExample}

\section{Back matter: compact project overview}
The closing overview reuses the project and PI records already used in general
information. No separate database is needed.

On the dedicated closing page, the table uses a minimum row height of
2.4\,\cs{baselineskip}. If the project records need more vertical space than
is available below the CRC logo, the complete table is scaled down
proportionally to fit on that page. A shorter table retains its natural type
size. The logo keeps its configured size. No manual row-height adjustment is
needed when projects are added or their titles or project-leader names grow.

\begin{dfgExample}[label={ex:manual-compact-project-overview-for-the-closing-pages},dfg wide,listing above* text]{Compact project overview for the closing pages}
\printTable{projectOverview}
\end{dfgExample}

\chapter{Metadata and configuration reference}
\label{chap:manual-reference}
This chapter collects the detailed field definitions, class settings, CV and
bibliography conventions, and maintenance notes. Read it as a reference while
working through the preceding proposal examples.

\section{Metadata, databases and keysets}
\label{doc:metadata}
This reference lists the accepted fields for each keyset. The walkthrough
introduces the records at their point of use; consult this section when adding
fields or choosing a non-default value. The class stores records with
\refPkg{datatool}.

\paragraph{Databases}

We have these databases that are used and picked up by several commands by
default:
\begin{description}
  \item[meta] All the metainformation about the proposal
  \item[person] Everything that is related to a person
  \item[project] Anything that is related to a project
  \item[institution] Info about an institution, that is linked to:
  \item[affiliation] storing info about the affiliation
\end{description}
There are also more databases created on the fly but mainly used for project
specific purposes.
The examples below use one coherent sample dataset: \texttt{MM} and
\texttt{KM} are persons, \texttt{A01} is a project, \texttt{IAIS} is an
institution, and \texttt{RWTH} is the related affiliation.
\subsection{Keyset \textbf{person}}
\begin{dispListing*}{title={Example keyset to describe a person-entity.}}
(*\refCom{addEntry}*){person}{
  (*\refKey{id}*)                 = {MM},
  (*\refKey{firstname}*)          = {Max S.},
  (*\refKey{lastname}*)           = {Doe},
  (*\refKey{academicdegree}*)     = {Prof. Dr. rer. nat.},
  (*\refKey{gender}*)             = {m},
  (*\refKey{ref-institution-id}*) = {IAIS},
  (*\refKey{ref-project-id}*)     = {A01},
  (*\refKey{role}*)               = {PI,spokesperson},
  (*\refKey{position}*)           = {prof-W3},
  (*\refKey{positionText}*)       = {Professor of Microbial Systems},
  (*\refKey{period}*)             = {1},
  (*\refKey{name-alias}*)         = {{Max Doe},{M. S. Doe}},
  (*\refKey{orcid}*)              = {0000-0002-3555-7218},
  (*\refKey{email}*)              = {max.doe@example.edu},
  (*\refKey{phone}*)              = {+49 241 80 12345},
  (*\refKey{url}*)                = {https://example.edu/mm},
  (*\refKey{doctorateYear}*)      = {1995},
  (*\refKey{doctorate}*)          = {Dr. rer. nat.},
  (*\refKey{financed-by}*)        = {RWTH},
  (*\refKey{topic}*)              = {Host--microbiome interactions},
  (*\refKey{category}*)           = {prof},
  (*\refKey{dateDefense}*)        = {1995},
  (*\refKey{periodStart}*)        = {2025},
  (*\refKey{periodEnd}*)          = {2029},
  (*\refKey{contract-information}*) = {
    (*\refKey{C1}*)  = {yes},
    (*\refKey{C2}*)  = {no},
    (*\refKey{C3}*)  = {no},
    (*\refKey{C4}*)  = {yes},
  }
}
\end{dispListing*}
There are several keys you can and should use regarding a person.
They are described further done as an example on how to use \refCom{addEntry}
etc.
\begin{docKey}{email}{=\meta{string}}{}
Provide the email-address of the person.
\end{docKey}
\begin{docKey}{url}{=\meta{url}}{ }
URL of the persons academic/professional homepage (e.g. institute).
\end{docKey}

\begin{docKey}{phone}{=\meta{string}}{ }
Provide the phone number of the person.
\end{docKey}

\begin{docKey}{financed-by}{=\meta{string}}{ }
Describe the source of funding for the person’s e.g. position etc.
\end{docKey}

\begin{docKey}{topic}{=\meta{string}}{ }
Especially for the early career researchers describe their topic of research.
\end{docKey}

\begin{docKey}{category}{\docKeyChoices{groupLeader, prof , postDoc,medDoc,%
    PhD,research,nonResearch,student,assistant}}{ }
\refKey{category} is used in various databases.
Mostly it is used to state the category of the person, but it is also used
then for the early career researchers.
\end{docKey}

\begin{docKey}{contract-information}{=\meta{key-values}}{}
Provide information about the person's contractual situation.
The \meta{key-value} is further specified with
\refKey{C1},
\refKey{C2},
\refKey{C2a},
\refKey{C2b},
\refKey{C3},
\refKey{C3a},
\refKey{C4},
\refKey{C4a}.
The generated wording for the yes/no keys \refKey{C1}--\refKey{C4} is
singular/plural sensitive.  It is adjusted automatically to match the number
of project leaders and institutions represented in the proposal.
\end{docKey}

\begin{docKey}{C1}{\docKeyChoices{yes,no}}{}
This key collects the answer to \emph{Is the employment of the project leader(s) at the institution(s) indicated contractually secured for the duration of the proposed funding period?}
\end{docKey}
\begin{docKey}{C2}{\docKeyChoices{yes,no}}{}
This key collects the answer to \emph{Do any of the above mentioned persons hold fixed-term positions?}
\end{docKey}

\begin{docKey}{C2a}{=\meta{YYYY-MM-DD}}{}
If key \refKey{C2} has been answered with \meta{yes}, this question \emph{End
date of fixed-term contract:\meta{YYYY-MM-DD} } requires \meta{YYYY-MM-DD} as
answer, too.
\end{docKey}
\begin{docKey}{C2b}{\meta{YYYY-MM-DD}}{}
If key \refKey{C2} has been answered with \meta{yes}, this question
\emph{Further employment is planned until \meta{YYYY-MM-DD}} requires
\meta{YYYY-MM-DD} as answer, too.
\end{docKey}
\begin{docKey}{C3}{\docKeyChoices{yes,no}}{}
This key collects the answer to \emph{Will one or more of the above-mentioned persons retire during the proposed funding period?}.
\end{docKey}
\begin{docKey}{C3a}{=\meta{YYYY-MM-DD}}{}
If key \refKey{C3} has been answered with \meta{yes}, this question
\emph{anticipated retirement date: \meta{YYYY-MM-DD} } requires \meta{YYYY-MM-DD} as
answer, too.
\end{docKey}

\begin{docKey}{C4}{\docKeyChoices{yes,no}}{}
This key collects the answer to \emph{Funding for the position(s) of the project leader(s) at the institution(s) indicated is covered by core support (state funds or similar):}
\end{docKey}
\begin{docKey}{C4a}{=\meta{string}}{}
If key \refKey{C4} has been answered with \meta{no},
this key provides type and source of funding.
\end{docKey}

Following keys are mainly used for the CV-section but are closely tight to the person:
\begin{docKey}{orcid}{=\meta{0000-0000-0000-0000}}{}
  The individual string with the ORCiD.
  This value is also required for \refCom{getORCiD}.
\end{docKey}
\begin{docKey}{name-alias}{=\meta{string}}{ }
  More versions of the person's name.
  The various aliases for \refKey{name-alias} are also described under
  \refCom{addboldnames}.
\end{docKey}
\begin{docKeys}
{
  {doc name = doctorateYear,
    doc parameter = {=\meta{YYYY}}},
  {doc name = doctorate,
    doc parameter = {=\meta{string}}},
  {doc name = degree-programme,
    doc parameter = {=\meta{string}}},
}
Providing information about the doctorate.
\end{docKeys}



\subsection{Database entries for a \textbf{cv}}
CV box titles, body text, publication lists, and consent text use
|\normalsize|. They follow the selected document base size, normally the
class's nominal 11\,pt setting, instead of imposing a smaller CV font.
Personal-data labels and career stages occupy one quarter of the row width.
Multiline labels align with the first line of the details without enlarging
the gap before its next paragraph. Short entries reserve the full label height,
and long details remain breakable across pages.

\label{sec:doc:cv-basic}
The header of the CV section is (partly) based on the information you parse to
the document using the \refCom{addEntry} command with the keyset \textbf{person}:
Keys like \refKey{name-alias}, \refKey{orcid},
\refKey{doctorate}, \refKey{degree-programme},
\refKey{url} are used especially for the CV-section.

Let’s assume we have a person with the following information:

\begin{dispListing*}{title={Partly person-entity dataset focussing on its CV-entry.}}
  (*\refCom{addEntry}*){person}{
    (*\refKey{id}*)             ={MM},
    (*\refKey{firstname}*)      ={Max S.},
    (*\refKey{lastname}*)       ={Doe},
    (*\refKey{academicdegree}*) ={Prof. Dr. rer. nat.},
    (*\refKey{role}*)           ={PI},
    \ldots
    (*\refKey{name-alias}*)       ={{Maxi Doe},{Maximilian Doe}},
    (*\refKey{orcid}*)            ={0000-0002-3555-7218},
    (*\refKey{doctorateYear}*)    ={1995},
    (*\refKey{doctorate}*)        ={Dr. rer. nat.},
    (*\refKey{degree-programme}*) ={Biology},
    (*\refKey{url}*)              ={https://example.edu/mm},
  }
\end{dispListing*}


This set of information is unique to a person and therefore only needs to be
parsed once.

In the cv we need more dedicated information about the person. This is done
with a separate keyset so it will not clutter the person-entry too much.
You can have multiple of the following entries below for a person.
Most important stages should be indicated with |cv-type=mandatory|.
If you state |cv-type=supplement| you only need to
use the key |description|, same goes for |cv-type=activities| which will then be
in a different section, and last |cv-type=supervision|.
There are more sections with further information about the PI.
All the information go to the database \meta{cv}.

\begin{docKey}{ref-person-id}{=\meta{id}}{}
  Use the \meta{id} of the person to whom this entry belongs to.
\end{docKey}

\begin{docKey}{description}{=\meta{string}}{}
  Further description of the current entry.
\end{docKey}


\begin{docKey}{cv-type}{\docKeyChoices{mandatory,supplement,
      activities,supervision,
      distinction,other}}{}
  Specifying the type of one CV entry with additional information.
  Each CV of a person needs to have a \meta{mandatory} entry
  (as part of \emph{Qualification and Career}).
\end{docKey}

\begin{docKeys}[doc parameter = {=\marg{date}}]
  {
    {
      doc name = periodStart,
      doc description = starting date
    },
    {
      doc name = periodEnd,
      doc description = ending date
    },
    {
      doc name = dateDefense,
      doc description = date of the defense of the thesis
    },
  }
  Specifying the time span of an event. The \meta{date} should be given in an IS8601-form.
\end{docKeys}

Some information comes from the block described above, but for the \emph{Stages} you
need to describe them separately using the keys
\refKey{ref-person-id},
\refKey{cv-type},
\refKey{periodStart},
\refKey{periodEnd},
\refKey{name},
\refKey{position},
\refKey{positionText},
\refKey{description},
\refKey{ref-institution-id}.


\begin{dispListing*}{title={Example dataset-entry for a mandatory person-cv-entity.}}
  (*\refCom{addEntry}*){cv}{
    (*\refKey{ref-person-id}*)      ={MM},
    (*\refKey{cv-type}*)        ={mandatory},
    (*\refKey{periodStart}*)        ={1995},
    (*\refKey{periodEnd}*)          ={1998},
    (*\refKey{position}*)            ={prof-W3},
    (*\refKey{positionText}*)           ={Professor of Microbial Systems},
    (*\refKey{description}*)        ={Established an independent research group on host--microbiome interactions.},
    (*\refKey{ref-institution-id}*) ={IAIS},
  }
\end{dispListing*}

For each stage on the career path repeat the
\cs{addEntry}\marg{cv}\marg{ \ldots, type={mandatory}, \ldots}-block.


There are five more blocks to which a researcher can provide information. For
each block and for each entry within one block you need to create an entry.

\begin{description}
  \item[supplement:]   Supplementary Career Information
  \item[activities:]   Activities in the Research System
  \item[supervision:]  Supervision of Researchers in Early Career Phases
  \item[distinction:]  Academic Distinctions
  \item[other:]        Other Information
\end{description}
Here is a more concrete example
\begin{dispListing*}{title={Example dataset-entry for a common CV-entity}}
  (*\refCom{addEntry}*){cv}{
    (*\refKey{ref-person-id}*)      ={MM},
    (*\refKey{cv-type}*)            ={supplement},
    (*\refKey{description}*)        ={Member of the university research council since 2024.},
  }
\end{dispListing*}

\begin{docCommand}{dfgCV}{\marg{person-id}}
  Print the complete CV for one person.  The command expects a dedicated
  \texttt{cv-}\meta{person-id} database and combines the header, mandatory
  career stages, optional CV sections, selected publications, and the data
  privacy statement.

  See \dfgExampleRef{ex:manual-generate-the-cv-appendix-or-select-one-person}.
\end{docCommand}

\begin{docCommand}{dfgCVsection}{\oarg{database}}
  Print the CVs for all PIs in the current funding period.  The
  \meta{database} defaults to \texttt{person}; persons are sorted by lastname
  and firstname before their CVs are printed with \refCom{dfgCV}.

  See \dfgExampleRef{ex:manual-generate-the-cv-appendix-or-select-one-person}.
\end{docCommand}

The starter CV loads person and career records from
|metadata/dfg-metadata.tex| and |metadata/dfg-metadata-cv.tex|. The following
example shows the first CV page produced by the complete appendix. Its first
PI is |per2| (Alex Example); selecting just that person produces the same CV.
The local proposal, CV appendix, and manual use the same twelve-PI consortium.
All pages, including the privacy statement, follow in
Chapter~\ref{chap:complete-example-cv}.

\begin{dfgExample}[label={ex:manual-generate-the-cv-appendix-or-select-one-person},dfg wide,listing and comment,
  comment={\dfgDocCVExcerpt{per2}}]{Generate the CV appendix or select one person}
\documentclass[english,cv,final=true]{dfg-crc}
\begin{document}
\dfgCVsection
% For one person, replace the line above with:
% \dfgCV{per2}
\end{document}
\end{dfgExample}

\subsection{Keyset \textbf{project}}
The following keys describe a project. Optional fields are identified below.
\begin{dispListing*}{title=Example dataset-entry to describe a project-entity.}
  (*\refCom{addEntry}*){project}{
    (*\refKey{id}*) = {A01},
    (*\refKey{number}*) = {A01},
    (*\refKey{name}*)   = {Microbial metabolism in barrier tissues},
    (*\refKey{short-title}*) = {Barrier metabolism},
    (*\refKey{project-type}*)   = {research},
    (*\refKey{project-status}*) = {N},
    (*\refKey{project-area}*)   = {A},
    (*\refKey{consider-for-lists}*) = {true},
    (*\refKey{reference-only}*) = {false},
    (*\refKey{research-area}*) = {1.11-01,1.11-03},
    (*\refKey{ref-person-id}*) = {MM,KM},
    (*\refKey{collaboration}*) = {A02,B01,Q01},
    (*\refKey{legal-issues}*)  = {
      (*\refKey{L1}*)  = {yes},
      (*\refKey{L1a}*) = {yes},
      (*\refKey{L2}*)  = {no},
      (*\refKey{L2a}*) = {},
      (*\refKey{L3}*)  = {yes},
      (*\refKey{L4}*)  = {no},
      (*\refKey{L5}*)  = {no},
      (*\refKey{L5a}*) = {},
      (*\refKey{L6}*)  = {no},
      (*\refKey{L7}*)  = {no},
      (*\refKey{L7a}*) = {},
    }
  }
\end{dispListing*}

Other required keys are \refKey{id}, \refKey{name},
\refKey{number}, \refKey{ref-person-id}.

\begin{docKey}{short-title}{=\meta{string}}{optional, initially absent}
  Store a concise alternative to the full project title in \refKey{name}.
  This field alone does not change any output. Select its use independently
  for the table of contents, running head and project-start title with
  |\changeSettings{projectTitle={...}}|, documented below. If the field is
  absent, empty or whitespace-only, each selected short title falls back to
  \refKey{name}. Existing metadata therefore need no changes. Generic metadata
  getters and project overview tables continue to use the full \refKey{name}.
\end{docKey}

Within an \refCom{addEntry}|{project}{...}| entry, the
\refKey{ref-person-id} field is reserved exclusively for the person or persons
who are PIs of that project. Every person listed in this field is interpreted
as a project PI; no other person roles are inspected or considered. Persons
associated with the project only in another role must therefore not be included
in this field.

\begin{docKey}{project-type}{\docKeyChoices{research,service,mgk,admin}}{}
  Hereby you specify the type of the project.
  \meta{research} stands for a classical research project,
  \meta{service} is service project,
  \meta{mgk} is an integrated graduate college,
  \meta{admin} is an administrative project.
\end{docKey}

\begin{docKey}{project-status}{\docKeyChoices{N,E,C}}{}
  Define the status of the project, where \meta{N} means a \emph{new} project,
  \meta{E} stands for \emph{ending} and \meta{C} for \emph{continuing} project.
  The generated local proposal contains complete, separate source examples for
  all three statuses.  Continuing projects use \enquote{Project progress to
  date}, new projects use \enquote{Research rationale}, and ending projects use
  the shorter \enquote{Project history}, \enquote{Published project results},
  and \enquote{Funding} structure.  In every case \refCom{printProjectHead}
  supplies the preceding general-information section from metadata.
\end{docKey}

\begin{docKey}{project-area}{=\meta{area-id}}{}
  Assign the project to a collaboration-plot area such as \texttt{A},
  \texttt{B}, or \texttt{Q}.  Any number of area identifiers is supported.
  If the key is omitted or empty, the first character of the project ID is
  used for compatibility with existing metadata (for example, \texttt{A01}
  belongs to area \texttt{A}).
\end{docKey}

\begin{docKey}{consider-for-lists}{\docKeyChoices{true,false}}{}
  Control whether the project participates in automatically generated project
  lists, project overview tables, research-area aggregates, and project counts.
  The default is \texttt{true}.  Setting this key to \texttt{false} does not
  remove the database row, so the project remains available to explicit
  reference commands such as \refCom{getProject}.
\end{docKey}

\begin{docKey}{reference-only}{\docKeyChoices{true,false}}{}
  Declare that the project exists only so historical or external project ids
  can be referenced.  The default is \texttt{false}.  A reference-only project
  is printed without a hyperlink because it has no project section that could
  provide a link target.  In prose it receives the explicit
  \enquote{former project} indicator.  Generated tables and lists instead append
  a compact superscript asterisk and add a local \enquote{Former project} legend
  when at least one such project occurs.  This key is independent of
  \refKey{consider-for-lists}: an ending project with a real project section can
  be excluded from lists without becoming reference-only.
\end{docKey}

\begin{docKey}{research-area}{=\meta{ticklist}}{}
  Collect all research areas (according to the DFG list) in a comma-separated structure.
  Spaces around individual codes are ignored, e.g.\ |2.21-02, 2.22-31|.
\end{docKey}

\begin{docKey}{collaboration}{=\meta{project-id-list}}{}
  List the other CRC projects collaborating with this project.  Collaborations
  are treated as undirected and duplicate declarations are collapsed, so the
  reverse relation does not need to be repeated.  The project collaboration
  plot reads its edges from this field and its nodes from the same
  \texttt{project} database.  Its default arc layout shows all active projects
  on one axis and highlights the focus project and its direct collaborators.
  Set |arcs=true| to draw the connecting arcs, or select the optional
  heatmap layout.  Ending, reference-only,
  and |consider-for-lists=false| projects are omitted, as are edges to those
  intentionally excluded nodes.
  All arcs reach one common peak height, so their horizontal span does not imply
  collaboration strength or weight.  Project identifiers are printed inside
  the nodes, and in the arc layout each project-area rule spans its complete
  contiguous group of nodes.
\end{docKey}

\begin{docKey}{collaborations}{=\meta{project-id-list}}{}
  Compatibility alias for \refKey{collaboration}. New sources should use the
  singular spelling, consistently with the plot type and local plot option.
\end{docKey}

\begin{docKey}{legal-issues}{=\meta{further key-values}}{}
  Provide information about the project's legal issues.
  The \meta{key-value} is further specified with
  \refKey{L1},
  \refKey{L1a},
  \refKey{L2},
  \refKey{L2a},
  \refKey{L3},
  \refKey{L4},
  \refKey{L5},
  \refKey{L5a}.
  \refKey{L6}.
  \refKey{L7}.
  \refKey{L7a}.
\end{docKey}

\begin{docKey}{L1}{\docKeyChoices{yes,no}}{}
  This key records whether the project requires compliance with
  discipline-specific research ethics guidelines.
\end{docKey}
\begin{docKey}{L1a}{\docKeyChoices{yes,no}}{}
  If key \refKey{L1} has been answered with \meta{yes}, this statement
  records whether a statement from the responsible ethics committee is
  required and will be obtained before funding starts.
\end{docKey}

\begin{docKey}{L2}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{clinical trials}
\end{docKey}
\begin{docKey}{L2a}{\docKeyChoices{yes,no}}{}
  If key \refKey{L2} has been answered with \meta{yes}, this statement
  \emph{A copy of the studies’ registration is included with the proposal} requires an answer, too.
\end{docKey}

\begin{docKey}{L3}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{experiments involving vertebrates}
\end{docKey}

\begin{docKey}{L4}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{experiments involving recombinant DNA}
\end{docKey}


\begin{docKey}{L5}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{research involving human embryonic stem cells}
\end{docKey}
\begin{docKey}{L5a}{\docKeyChoices{yes,no}}{}
  If key \refKey{L5} has been answered with \meta{yes}, this statement
  \emph{Legal authorization has been obtained} requires an answer, too.
\end{docKey}

\begin{docKey}{L6}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{research concerning the Convention on Biological Diversity}
\end{docKey}

\begin{docKey}{L7}{\docKeyChoices{yes,no}}{}
  This key collects the answer to \emph{investigations involving dual use research of concern}
\end{docKey}
\begin{docKey}{L7a}{\docKeyChoices{yes,no}}{}
  If key \refKey{L7} has been answered with \meta{yes}, this statement
  \emph{A copy of the statement by the institution’s research ethics committee is included with the proposal} requires an answer, too.
\end{docKey}

\subsection{Keyset \textbf{institution}}
An institution describes the organisational unit a person belongs to, for
example an institute, department, centre, or clinic.  It is linked to its parent
affiliation through \refKey{ref-affiliation-id}.  The \refKey{abbreviation}
is the compact, reader-facing label used in generated table cells; the internal
\refKey{id} is never intended as display text.  Full institution lists and
legends continue to use \refKey{name}.  For compatibility, a missing
\refKey{abbreviation} falls back to \refKey{name}.  The \refKey{name} key may
be left empty when the affiliation itself is the relevant institution-level
text; in that case institution-list commands start with the affiliation name.

\begin{dispListing*}{title=Example dataset-entry to describe an institution-entity.}
  (*\refCom{addEntry}*){institution}{
    (*\refKey{id}*) = {IAIS},
    (*\refKey{name}*) = {Institute for Applied Immunology and Systems Biology},
    (*\refKey{abbreviation}*) = {IAIS},
    (*\refKey{ref-affiliation-id}*) = {RWTH},
  }
\end{dispListing*}

\begin{dispListing*}{title={Institution without a separate institution name.}}
  (*\refCom{addEntry}*){institution}{
    (*\refKey{id}*) = {RWTH-main},
    (*\refKey{name}*) = {},
    (*\refKey{abbreviation}*) = {RWTH},
    (*\refKey{ref-affiliation-id}*) = {RWTH},
  }
\end{dispListing*}

\begin{dispListing*}{title={Person with multiple institutions.}}
  (*\refCom{addEntry}*){person}{
    (*\refKey{id}*) = {MM},
    (*\refKey{firstname}*) = {Maria},
    (*\refKey{lastname}*) = {Sample},
    (*\refKey{ref-institution-id}*) = {IAIS,RWTH-main},
  }
\end{dispListing*}

In standard institution lists, multiple institutions are printed as separate
paragraphs with a small vertical gap.  In \texttt{narrow} mode, they are joined
inline with semicolons.  The \texttt{abbreviation} option selects institution
abbreviations (with a full-name fallback); generated compact tables enable this
option automatically.

\subsection{Keyset \textbf{affiliation}}
Following keys are required to describe an affiliation.

\begin{dispListing*}{title=Example dataset-entry to describe an affiliation-entity.}
  (*\refCom{addEntry}*){affiliation}{
    (*\refKey{id}*)             = {RWTH},
    (*\refKey{name}*)           = {Rheinisch-Westfälische Technische Hochschule Aachen},
    (*\refKey{abbreviation}*)   = {RWTH Aachen University},
    (*\refKey{addressStreet}*)  = {Templergraben 55},
    (*\refKey{addressZIP}*)     = {52062},
    (*\refKey{location}*)       = {Aachen},
    (*\refKey{country}*)        = {Germany}
  }
\end{dispListing*}

\begin{docKey}{abbreviation}{=\meta{string}}{}
  In addition to \refKey{name} provide an abbreviated version of this affiliation.
\end{docKey}

\begin{docKey}{addressStreet}{=\meta{string}}{}
  Specify the street of the affiliation.
\end{docKey}

\begin{docKey}{addressZIP}{=\meta{string}}{}
  Specify the ZIP code of the affiliation.
\end{docKey}

\begin{docKey}{location}{=\meta{string}}{}
  Specify the location (city) of the affiliation.
\end{docKey}

\begin{docKey}{country}{=\meta{string}}{}
  Specify the country the affiliation is located at.
\end{docKey}

\subsection{Keyset \textbf{funding}}

Each row represents one funding line.  For a staff row, the class can derive
the annual amount from the declared personnel category, percentage, and yearly
quantity.  For other funding types, annual values continue to be supplied
with \refKey{sum}.

\begin{dispListing*}{title={Complete dataset for a funding entity. Not all keys
        are always required.}}
  (*\refCom{addEntry}*)[funding]{RequestedFunding}{
    (*\refKey{id}*)                 = {A01-staff-prof},
    (*\refKey{ref-project-id}*)     = {A01},
    (*\refKey{ref-affiliation-id}*) = {RWTH},
    (*\refKey{financed-by}*)        = {DFG},
    (*\refKey{funding-type}*)       = {staff},
    (*\refKey{percentage}*)         = {100},
    (*\refKey{funding-category}*)           = {prof},
    (*\refKey{quantity}*)           = {
      { year1 = {1} },
      { year2 = {1} },
      { year3 = {1} },
      { year4 = {1} },
      { year5 = {1} },
    },
    (*\refKey{sum}*) = {
      { year1 = {1000} },
      { year2 = {1000} },
      { year3 = {1000} },
      { year4 = {1000} },
      { year5 = {1000} },
    },
    (*\refKey{year}*)               = {2026},
    (*\refKey{applicant}*)          = {5000},
    (*\refKey{participant}*)        = {2000},
    (*\refKey{other-funds}*)        = {0},
    (*\refKey{staff}*)              = {5000},
    (*\refKey{costs}*)              = {1200},
    (*\refKey{instrumentation}*)    = {0},
    (*\refKey{fellowships}*)        = {0},
    (*\refKey{globalfunds}*)        = {0}
  }
\end{dispListing*}

Not all of the above mentioned keys are necessary for each funding table.
We will provide examples for the various funding databases and their required
keysets.

\begin{docKey}{funding-type}{\docKeyChoices{staff, costs, fellowships,
      globalfunds, instrumentation}}{}
  Define the type of this funding according to the predefined set. This is
  important since different features are activated depending on the value of this key.
\end{docKey}

\begin{docKey}{percentage}{=\meta{number}}{}
  This is only relevant when \refKey{funding-type} is set to |staff|.
  State the percentage of a full position, for example |100| for a full
  position or |65| for a 65\% position.  Integer and decimal values are
  accepted by the automatic calculation.
\end{docKey}

\begin{docKey}[][doc label={funding-positionText}]{positionText}{=\meta{text}}{}
  Optional replacement for the staff description in the requested-funding
  table. When supplied, it is printed instead of the translated
  \refKey{funding-category} name. If omitted or empty, the category name is printed.
  The category still determines the salary calculation.
\end{docKey}

\begin{docKey}[][doc label={funding-category}]{category}{\docKeyChoices{groupLeader, prof, prof-W2, prof-W3,%
    postDoc,medDoc,PhD,research,nonResearch,student,assistant}}{}
  This is only relevant when \refKey{funding-type} is set to |staff|.
  Describe the kind of the required person. Depending on this \meta{category}
  the matching |salary@...| setting is used.  The categories |prof|,
  |prof-W2|, and |prof-W3| all use \refKey{salary@prof}; the other category
  names correspond directly to their setting names below.
\end{docKey}

\begin{docKey}{quantity}{=\meta{key=value}}{}
  This is a key that enables further \meta{key-values} with a predefined subset
  |year1| through |year5|. State how many positions of the
  \refKey{funding-category} are required in each year. Decimal quantities are
  supported, for example |year1={0.5}| for half a position.
\end{docKey}

\begin{docKey}{sum}{=\meta{key=value}}{}
  This is a key that enables further \meta{key-values} with a predefined subset
  for the individual years. State the sum for a person for a certain
  \refKey{funding-category}.  For |funding-type=staff| this key is optional: every
  omitted yearly sum is calculated from the salary setting for
  \refKey{funding-category}, \refKey{percentage}, and that year's
  \refKey{quantity}.  Because the five-year CRC period starts and ends with a
  half-year, automatically calculated amounts for |year1| and |year5| receive
  an additional factor of |0.5|; |year2| through |year4| use the complete
  annual rate.  The result is rounded to the nearest euro.  An explicit yearly
  sum remains an override, so existing declarations and exceptional personnel
  costs keep their stated value.
\end{docKey}

For every omitted staff sum, the class applies
\[
  \operatorname{round}\left(
    \text{salary(category)} \times
    \frac{\text{percentage}}{100} \times
    \text{quantity(year)} \times
    \text{period-factor(year)}, 0
  \right).
\]
Here, \(\text{period-factor}=0.5\) for |year1| and |year5| and \(1\) for
|year2|--|year4|.  Thus the two half-years together count as one complete
salary year.
The calculation is performed when the row is added and the result is stored in
the normal |sum-year1| through |sum-year5| fields.  Funding tables therefore
use calculated and explicitly supplied amounts in exactly the same way.  A
missing salary setting, percentage, or valid quantity produces a warning
instead of silently inventing an amount.

\begin{dispListing*}{title={Staff funding with automatically calculated sums.}}
(*\refCom{addEntry}*)[funding]{RequestedFunding}{
  (*\refKey{ref-project-id}*) = {A01},
  (*\refKey{funding-type}*)   = {staff},
  (*\refKey{funding-category}*)       = {PhD},
  (*\refKey{percentage}*)     = {65},
  (*\refKey{quantity}*)       = {
    year1 = {1}, year2 = {1}, year3 = {1},
    year4 = {1}, year5 = {1}
  }
}
\end{dispListing*}

\begin{docKey}{year}{=\meta{integer}}{}
  State the year as integer. Actually only relevant in combination with
  \refKey{applicant}, \refKey{participant}, \refKey{other-funds}, \refKey{staff}, \refKey{costs}, \refKey{instrumentation}, \refKey{fellowships}, \refKey{globalfunds}.
\end{docKey}


\begin{docKey}{applicant}{=\meta{integer}}{}
  State the sum of direct costs for the applicant institution.
\end{docKey}

\begin{docKey}{participant}{=\meta{integer}}{}
  State the sum of direct costs for any other participating (i.e. not-applicant) institution.
\end{docKey}


\begin{docKey}{other-funds}{=\meta{integer}}{}
  State the sum of direct costs when neither the applicant nor a participating
  institution is covering the costs.
\end{docKey}

\begin{docKey}{staff}{=\meta{integer}}{}
  State the \meta{sum} of staff for the previous funding phase.
  This is a fixed sum and therefore not necessary to calculate the sum like we do
  with \refKey{funding-category} etc.
\end{docKey}

\begin{docKey}{costs}{=\meta{integer}}{}
  State the \meta{sum} of direct costs for the previous funding phase.
  This is a fixed sum and therefore not necessary to calculate the sum like we do
  with \refKey{funding-category} etc.
\end{docKey}


\begin{docKey}{instrumentation}{=\meta{integer}}{}
  State the \meta{sum} of instrumentation for the previous funding phase.
  This is a fixed sum and therefore not necessary to calculate the sum like we do
  with \refKey{funding-category} etc.
\end{docKey}


\begin{docKey}{fellowships}{=\meta{integer}}{}
  State the \meta{sum} of staff for the previous funding phase.
  This is a fixed sum and therefore not necessary to calculate the sum like we do
  with \refKey{funding-category} etc.
\end{docKey}


\begin{docKey}{globalfunds}{=\meta{integer}}{}
  State the \meta{sum} of globalfunds for the previous funding phase.
  This is a fixed sum and therefore not necessary to calculate the sum like we do
  with \refKey{funding-category} etc.
\end{docKey}

\subsection{Keyset \textbf{staff}: requested-funding roster}

The |staff| key family also supplies the project-level roster required by the
DFG section \enquote{Requested funding for staff}.  These records use the fixed
database |RequestedFundingStaff| and are independent of the monetary
|RequestedFunding| rows above.  The public output call is
\refCom{printTable}|{{RequestedFundingStaff}{A01}}|.

\begin{dispListing*}{title={Complete staff-roster declaration.}}
(*\refCom{addEntry}*)[staff]{RequestedFundingStaff}{
  (*\refKey{staff-ref-project-id}*)     = {A01},
  (*\refKey{funding-status}*)     = {existing},
  (*\refKey{staff-type}*)         = {research},
  (*\refKey{staff-ref-person-id}*)      = {MM},
  (*\refKey{field-of-research}*)  = {Microbiology},
  (*\refKey{commitment}*)         = {8},
  (*\refKey{funding-source}*)     = {State funds},
  (*\refKey{staff-description}*)        = {
    Leads the experimental work and supervises the research staff.
  }
}
\end{dispListing*}

\begin{docKey}[][doc label={staff-ref-project-id}]{ref-project-id}{=\meta{project-id}}{}
  Required. Selects the project for which the roster row is printed.  The
  value must match the project argument in the table call.  For example, a
  row with |ref-project-id={A01}| is selected when |A01| is passed as the
  project argument to \refCom{printTable}.
\end{docKey}

\begin{docKeys}[
  doc parameter={=\meta{choice}}
]{
  {doc name=funding-status,
   doc parameter={\docKeyChoices{existing,requested}}},
  {doc name=staff-type,
   doc parameter={\docKeyChoices{research,nonResearch}}}
}
  These two required keys select one of the four official DFG groups.  Empty
  subgroups are omitted and declaration order is retained within each group.
  In a project with |project-status=E|, |funding-status=requested| denotes
  staff funded with approved grant money in the ending funding period; the
  table changes that group label and its job-description heading
  automatically.
\end{docKeys}

\begin{docKeys}[doc parameter={=\meta{string}}]{
  {doc name=ref-person-id,doc label={staff-ref-person-id}},
  {doc name=firstname,doc label={staff-firstname}},
  {doc name=lastname,doc label={staff-lastname}},
  {doc name=academic-degree},
  {doc name=positionText,doc label={staff-positionText}}
}
  A resolvable \refKey{staff-ref-person-id} obtains the name, academic degree,
  position, category, and organisation from the central |person| fields
  |firstname|, |lastname|, |academicdegree|, |positionText|, |position|,
  |ref-institution-id|, and the compatibility fallback |ref-affiliation-id|.
  Any explicitly supplied roster field overrides the central value. An empty
  or omitted \refKey{academic-degree} is silently left out of the roster.
  Job-description lead-ins print only the first and last name, without an
  academic degree. For an unnamed vacancy, use
  |lastname={TBA}|; |firstname| may then also be omitted, and both the roster
  and the job-description lead-in print a clean ``TBA'' marker. Multiple
  unnamed vacancies are distinguished by their category, position, field of
  research, and institution when duplicate records are checked. Either a
  person reference or at least a last name is required. For existing staff
  resolved through \refKey{staff-ref-person-id}, the lastname is printed in bold in
  the roster.
  Omitting |positionText| inherits the central person's position text.
  If no position text is available, the category supplies the position line
  and follows \refKey{categoryAbbreviations}, for example \enquote{Postdoc}.
  Explicit or inherited position text is printed as supplied, even if it
  matches a full category name. An explicit |positionText={}| suppresses the
  line. If neither a position text nor a category is available, its line and
  parentheses are omitted without a missing-field warning.
  The former roster key |position| remains accepted as a compatibility alias
  for |positionText|.
\end{docKeys}

\begin{docKeys}[doc parameter={=\meta{string}}]{
  {doc name=field-of-research},
  {doc name=funding-source},
  {doc name=description,doc label={staff-description}}
}
  \refKey{field-of-research} supplies its table cell for every roster row.
  It may be empty or omitted for existing and requested non-research staff;
  in that case the
  empty cell receives the |tableNoValue| background and no missing-field
  warning is issued.  It remains an
  applicable, warning-checked value for both research-staff groups.
  \refKey{funding-source} applies only to existing staff; the corresponding
  cell for requested staff is marked as not applicable.  \refKey{staff-description}
  supplies the numbered text below the table and accepts ordinary paragraph
  material, citations, and other LaTeX commands.  Each description is an item
  in the applicable existing- or requested-staff list. Its number is the
  flush-left item label; first name, last name, and all
  continuation lines share a consistent hanging indent. The bold name and
  description are separated by a normal interword space.
  Missing applicable values are highlighted and reported in the log.
\end{docKeys}

\begin{docKey}[][doc label={staff-ref-institution-id}]{ref-institution-id}{=\meta{id-list}}{}
  Resolve one or more comma-separated institution ids through the central
  |institution| database.  Each institution's \refKey{abbreviation} is printed
  in the department/institution column; the full \refKey{name} is retained in
  the automatically generated legend, followed by the parent-affiliation
  abbreviation in parentheses. Entries have the form
  \enquote{abbreviation: full institution name (affiliation abbreviation)}
  and are separated by commas. After a semicolon, each used affiliation is
  expanded as \enquote{abbreviation: full affiliation name}. Institutions and
  affiliations are each explained once, in first-use order. The complete
  legend uses normal font weight, without bold labels or section headings. This key may be omitted when a resolvable
  \refKey{staff-ref-person-id}
  already supplies |person.ref-institution-id|; a value on the staff row acts
  as an explicit override.  When \refKey{staff-ref-person-id} is empty or omitted,
  \refKey{staff-ref-institution-id} must be supplied explicitly.  The class warns at
  declaration time if both keys are empty, because the institution cannot be
  inherited and an existing staff member could not be assigned to an
  affiliation in \refCom{OverviewExistingStaffTable}.
\end{docKey}

\begin{docKey}{department}{=\meta{string}}{}
  Compatibility override for unstructured declarations.  When present, this
  text is printed directly and takes precedence over institution lookup.  New
  declarations should normally use \refKey{staff-ref-institution-id}.
\end{docKey}

\begin{docKey}[][doc label={staff-ref-affiliation-id}]{ref-affiliation-id}{=\meta{affiliation-id}}{}
  Compatibility fallback used only when neither \refKey{department} nor
  \refKey{staff-ref-institution-id} is supplied.  It prints the affiliation
  abbreviation and adds a direct \enquote{abbreviation: full affiliation name.}
  entry to the affiliation list, also when no institution is used. New declarations should use \refKey{staff-ref-institution-id}
  so the organisational unit and its
  parent affiliation remain separate structured data.  In particular, this
  compatibility key does not replace the required \refKey{staff-ref-institution-id}
  on a row that has no \refKey{staff-ref-person-id}.
\end{docKey}

\begin{docKey}{commitment}{=\meta{number}}{}
  Project commitment in hours per week for existing staff.  The value may be
  a non-negative integer or decimal; no artificial upper limit is imposed.
  For requested staff the table cell is marked as not applicable and no
  commitment value is required.  Missing-field warnings identify the row's
  |funding-status| and its displayed staff number.  A missing commitment on
  an existing-staff row prompts for hours per week and explains that
  |funding-status=requested| does not require commitment; correct the status
  only if the row actually represents requested staff.
\end{docKey}

\begin{docKey}[][doc label={staff-category}]{category}{\docKeyChoices{prof,groupLeader,postDoc,medDoc,
    PhD,research,nonResearch,student,assistant,prof-W2,prof-W3}}{}
  Required for requested staff unless it can be inherited from
  |person.position| through \refKey{staff-ref-person-id}.  Only keys registered in
  \cs{g\_\_dfg\_dfg\_category\_names\_prop} are accepted, and the table
  expands each key to the label stored in that property; for example,
  |postDoc| prints \enquote{Postdoctoral researcher}, or \enquote{Postdoc}
  with \refKey{categoryAbbreviations}.  Existing staff inherit
  the category for the chapter-2 overview when possible, but may still supply
  an explicit override; their Category cell in the project-level roster is
  marked as not applicable.
\end{docKey}

The table traverses |RequestedFundingStaff| only once for the selected project,
then assigns continuous sequence numbers in display order.  The same numbers
are reused below the table for the two job-description blocks.  Missing values,
unresolved references, and exact duplicate identities produce warnings and
visible placeholders without stopping compilation.

\paragraph{Reuse in chapter 2: overview of existing staff}

The same declarations also populate the proposal-wide table in section 2.1.2;
no separate totals database is needed.  The call is
\refCom{printTable}|{OverviewExistingStaff}|.  It selects only rows with
|funding-status={existing}|, counts one person per distinct parent affiliation,
and groups the values into the seven categories prescribed by the DFG form.
An unnamed or otherwise unreferenced person therefore needs an explicit
|ref-institution-id|; omitting both it and |ref-person-id| produces a warning
when the roster row is declared.
The mappings are |prof|, |prof-W2|, and |prof-W3| to Professors,
|groupLeader| to Junior research group leaders, |postDoc| to Postdoctoral
researchers, |PhD| to Doctoral researchers,
|research| and |medDoc| to Other research staff, |nonResearch| to Non-research
staff, and |student| and |assistant| to Student and graduate assistants.

The category column uses the available flexible width with |X[l]|;
centred affiliation columns use |Q[c]| so their headings and abbreviations
determine their natural widths instead of being clipped in equal-width cells.
The existing- and requested-staff tables share one abbreviation-note renderer:
regular footnote-size text, a plain \enquote{Abbreviations:} label, semicolon-
separated entries and normal spacing after the table.
All three header rows and the body values are vertically centred,
including spanning header cells. The category label reads \enquote{Junior research group}
on its first line and \enquote{leaders} on its second line. This layout is
maintained in the class source, so a proposal customization override is not
needed after updating the generated class.

The proposal workspace contains a standalone layout test at
\path{proposal-overleaf-com/__admin/scripts/test-overview-staff.tex}.
It declares 85 complete fictional staff records across all seven categories
and nine real affiliations in an isolated database, independently of project
auxiliary files. The source lists the expected counts and build commands.
Run LuaLaTeX twice from the proposal workspace; the PDF is written to
\path{output/pdf/test-overview-staff.pdf}. The test PDF labels the counts as
illustrative rather than proposal totals.

The applicant affiliation or affiliations are read as a comma-separated list
from |meta.ref-affiliation-id| and printed first; other affiliations are
obtained from each row's |ref-institution-id|.  The group heading says
enquote{applicant university} for one id and enquote{applicant universities}
for several ids, spanning all corresponding columns.  Multiple institutions
belonging to the same affiliation count that person only once in that
affiliation column.  Since the project declarations normally occur after
chapter 2, the class transfers the rows through the |.aux| file.  The normal
multi-pass |latexmk| build therefore fills the table automatically on the next
pass.


\subsection{Shared identifiers and CRC metadata}
Following keys are available for the \meta{person}-keyset.

\begin{docKey}{id}{=\meta{unique string}}{}
  Any kind of a unique string that serves as an id, especially for commands
  like \refCom{getEntry}. Almost all databases require this key.
\end{docKey}

\begin{docKeys}[
    doc parameter = {=\meta{string}}
  ]{
    { doc name = firstname },
    { doc name = lastname },
    { doc name = academicdegree },
    { doc name = gender,
      doc parameter = {\docKeyChoices{f,m,d}}},
    { doc name = period,
      doc parameter = {\docKeyChoices{1,2,3}},
      doc description = multi choice!!},
    { doc name = role,
      doc parameter = {\docKeyChoices{PI, spokesperson, manager,
            steering-committee-member, rector}}},
    { doc name = position,
      doc parameter = {\docKeyChoices{PhD, postDoc, groupLeader, research,
            nonResearch, student, prof, prof-W2, prof-W3}}},
    { doc name = positionText,
      doc parameter = {=\meta{string}},
      doc description = {Specifying the position of the person, current or in the CV-section for the respective period.}},
  }
  Personal and individual \emph{required} information about a person.
\end{docKeys}

\begin{docKeys}[
    doc parameter = {=\meta{string}}
  ]{
    { doc name = ref-institution-id },
    { doc name = ref-affiliation-id },
    { doc name = ref-project-id     },
  }
  Referencing to an external database with its dedicated \meta{id}.
  \textbf{Note:} When you reference using \refKey{ref-institution-id}, there
  is no need to explicitly reference the affiliation with \refKey{ref-affiliation-id}.
\end{docKeys}

The institution data is resolved through a two-step relationship.  A person
stores one or more institution ids in \refKey{ref-institution-id}; each
institution stores the id of its parent affiliation in
\refKey{ref-affiliation-id}.  Commands such as \refCom{printList}
therefore follow this chain:
\[
  \texttt{person.ref-institution-id}
  \longrightarrow
  \texttt{institution.id}
  \longrightarrow
  \texttt{institution.ref-affiliation-id}
  \longrightarrow
  \texttt{affiliation.id}.
\]
The affiliation id usually does not need to be duplicated in the person entry.

For the database |meta| there are also dedicated keys.
The database |meta| contains specific information on the metalevel about the
CRC.
For the |meta| row with |id=crc|, \refKey{ref-affiliation-id} accepts one or
more comma-separated affiliation ids, for example |{aff1,aff2}|.  These are the
applicant or coordinating universities.  Their names and locations are
resolved in declaration order for the title page and related prose; applicant
funding totals include every listed id.
Besides \refKey{id}, \refKey{ref-affiliation-id} there are these dedicated keys:
\begin{docKeys}{
    {doc name = name,
      doc parameter = {=\meta{string}},
      doc description = {applicable to other keysets, too.}},
    {doc name = nameAddon,
      doc parameter = {=\meta{string}}},
    {doc name = number,
      doc parameter = {=\meta{integer}}},
    {doc name = fundingPeriodNumeral,
      doc parameter = {\docKeyChoices{1,2,3}},
    },
    {doc name = fundedSince,
      doc parameter = {=\meta{YYYY}}},
    {doc name = fundingYears,
      doc parameter = {=\meta{YYYY1,YYYY2,YYYY3,YYYY4,YYYY5}}},
    {doc name = fundingYearsPrevious,
      doc description = {applicable to 2nd and 3rd phases},
      doc parameter = {=\meta{YYYY1,YYYY2,YYYY3,YYYY4,YYYY5}}},
  }
  Specify the core information of a CRC.
  The key \refKey{fundingPeriodNumeral} corresponds to \refKey{period}.
\end{docKeys}
\section{Adjustments and Customizations}
\label{doc:customization}

\subsection{Page layout and paragraph spacing}
\label{doc:page-layout}
The class uses A4 paper and KOMA-Script's nominal |fontsize=11pt| setting.
With this setting, \cs{normalsize} selects 10.95\,pt type with a
13.6\,pt baseline distance; the option name follows the usual LaTeX
11\,pt convention. The current default font families are documented under
\refKey{font} and \refKey{sansfont}.

The default two-sided layout has the following dimensions:
\begin{center}
\begin{tabular}{@{}ll@{}}
Text block & 165\,mm wide, 250\,mm high \\
Nominal inner margin & 20\,mm \\
Binding correction (\refKey{BCOR}) & 5\,mm \\
Effective inner clearance & 25\,mm \\
Outer margin & 20\,mm \\
Top margin & 20\,mm \\
Bottom margin, including footer & 15\,mm \\
Footer baseline distance (\cs{footskip}) & 12\,mm \\
Margin-note width and separation & 13\,mm and 2\,mm
\end{tabular}
\end{center}
The width is |210mm - 20mm - 5mm - 20mm = 165mm|. Because the
\pkg{geometry} option |includefoot| is active, the height is
|297mm - 20mm - 15mm - 12mm = 250mm|. The footer contains the page
number and the CRC logo; its distance is reserved separately from the text
block. Inner and outer margins switch sides on facing pages. The header
is outside the text block, with 20\,pt reserved for two-line running heads.

Paragraphs have no first-line indentation. Their gap is
|3.5pt plus 1pt minus 0.5pt|: 3.5\,pt normally, with 1\,pt of stretch
and 0.5\,pt of shrink available to TeX. The class sets this through
KOMA-Script's \cs{setparsizes} interface, so a font-size change does not
restore the former half-baseline gap. The third argument below keeps the
final line of a paragraph freely stretchable.
Immediately after a displayed heading, the paragraph gap uses only its natural
dimension (3.5\,pt by default), without stretch or shrink. This applies to
numbered and unnumbered headings, while the gaps between ordinary paragraphs
retain their elasticity. Section, subsection, and subsubsection headings have
|afterskip=0pt|; chapter headings retain their fixed |0.1ex| after-skip.

\begin{dispListing*}{title={Default paragraph and footer spacing in the main preamble.}}
% After \documentclass{dfg-crc}, before \begin{document}:
\setparsizes{0pt}{3.5pt plus 1pt minus 0.5pt}{0pt plus 1fil}
\geometry{footskip=12mm}
\end{dispListing*}
Change the dimensions in this example to adjust the spacing. The
\cs{setparsizes} call may also go directly into
|preamble/dfg-customization.tex|, outside \cs{changeSettings}. Geometry
overrides belong after \cs{documentclass} in the main preamble: the class
applies its geometry defaults after reading the customization file.
Changing \refKey{BCOR} changes the available text width; see its description
below. Figures sized with |width=\linewidth| follow the resulting width
and also change height when their aspect ratio is preserved.

\subsection{Documentclass options}
\begin{docCommand}{documentclass}{\marg{key=value}}
  Adjust on a metalevel various options (e.g.
  \refKey{showmarginalia},
  \refKey{fastcompile},
  \refKey{fastcompile-show-tags},
  \refKey{fastcompile-project},
  \refKey{fastcompile-project-show-images},
  \refKey{fastcompile-project-show-publications},
  \refKey{fastcompile-project-show-funding-tables},
  \refKey{showtags},
  \refKey{showtags-tables},
  \refKey{skip10pub},
  \refKey{cv},
  \refKey{final},
  \refKey{colorscheme})
  for the whole document. Not so much content
  wise but rather organisational.

  See \dfgExampleRef{ex:manual-generate-the-cv-appendix-or-select-one-person}.
\end{docCommand}

\begin{docKey}{BCOR}{=\meta{dim}}{initially \texttt{5mm}}
  Reserve binding space on the inner edge of each page.  The class passes this
  KOMA-Script option to \pkg{geometry} as its binding offset.  With the
  default 20\,mm nominal inner margin, |BCOR=5mm| gives 25\,mm of inner
  clearance and a 165\,mm text block; |BCOR=8mm| gives 28\,mm and 162\,mm.
\end{docKey}

\begin{docKey}{showmarginalia}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Show further information in the marginpar area, esp. total sum in funding tables.
\end{docKey}

\begin{docKey}{fastcompile}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Skip generated tables and lists, role-card grids, Gantt charts, and the CV
  publication block.  Metadata and ordinary database-backed references remain
  available, making this the less aggressive compatibility mode.
\end{docKey}

\begin{docKey}{fastcompile-show-tags}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Show database provenance annotations during either fast-compilation mode.
  In focused project mode, annotations show the starting row and requested
  lookup path because metadata rows are skipped. This option has no effect
  outside fast compilation; final mode disables the annotations.
\end{docKey}

\begin{docKey}{fastcompile-project}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Compile authored project text with minimal calculated framing.  This mode
  implies \refKey{fastcompile}, does not load metadata files unless
  \refKey{fastcompile-project-show-images} needs project rows, and executes only
  the three project-local funding entry types when
  \refKey{fastcompile-project-show-funding-tables} is enabled. It replaces the
  calculated project head with a labeled placeholder occupying the space
  recorded by a normal build in the ordinary \texttt{.aux} file. A multi-page
  header retains its recorded page span. No header fields are measured in
  focused mode. Keep auxiliary files, and refresh them with a normal build
  after changing header data, fonts or layout. A missing record or different
  text width/height produces a visibly marked placeholder reserving half of
  the current \cs{textheight} and a warning; it cannot predict the true space. The mode also
  disables title/front-matter helpers when wrapped with
  \cs{dfgIfFastCompileProjectF}, and uses draft links.  Graphics also default
  to draft placeholders unless \refKey{fastcompile-project-show-images} is enabled.
  Database references fall back to their IDs so prose remains readable. Apart
  from the optional project funding tables, generated tables and lists retain
  the same visible skipped-item notice as \refKey{fastcompile}.
\end{docKey}

\begin{docKey}{fastcompile-project-show-images}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Render images and generated plots encountered in the selected project while
  \refKey{fastcompile-project} is active.  Project entries from the metadata
  file are retained for database-backed plots such as
  |\printPlot{{ProjectCollaboration}{B06}}|; other metadata entries,
  calculated headings, generated tables and the remaining fast-mode work stay
  disabled.  With the default value, \pkg{graphicx} stays in draft mode,
  displays image placeholders, and \refCom{printPlot} emits the usual skipped
  item notice.
\end{docKey}

\begin{docKey}{fastcompile-project-show-publications}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Show or suppress project publication headings, explicit project \cs{nocite}
  lists, project bibliographies, report references, and ending-project result
  lists while \refKey{fastcompile-project} is active.  Ordinary and final builds
  always enable publication output.  When this option is false in focused
  project mode, inline citation commands render compact bibliography-key
  markers without requesting biber.
\end{docKey}
\begin{docKey}{fastcompile-project-show-funding-tables}
  {\docKeyChoices{true,false}}
  {initially \texttt{true}.}
  Show or suppress \cs{RequestedFundingTable},
  \refCom{RequestedFundingStaffTable}, and
  \cs{RequestedAndExistingFundingDirectCostsTable} while
  \refKey{fastcompile-project} is active. Focused mode processes only the
  corresponding project-local |RequestedFunding|, |RequestedFundingStaff|, and
  |RequestedAndExistingFundingDirectCosts| entries. Local staff-cost and total
  calculations remain available, including the per-year and full-period sums
  of existing direct-cost rows. Multiple rows accumulate in those local sums.
  Missing staff-table values use field-name placeholders such as
  |<firstname>| instead of ``not provided'' in fast compilation, since
  metadata needed for inherited values may have been skipped.
  Auxiliary-file restoration and proposal-wide overview caches stay disabled. This option has no effect on
  ordinary or final builds, where these tables are always rendered.
\end{docKey}
\begin{docKey}{showtags}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Annotate direct database values with their database, row identifier, and
  field, and calculated values with a concise calculation and source-database
  label.  Successive labels alternate between two vertical levels to keep
  adjacent annotations legible. During fast compilation,
  \refKey{fastcompile-show-tags} controls whether these annotations appear.
  In focused project mode, annotations identify the starting row and full
  requested field path because skipped metadata cannot supply destination row
  identifiers. Final mode disables annotations.
\end{docKey}
\begin{docKey}{showtags-tables}
  {\docKeyChoices{true,false}}
  {initially \texttt{true}.}
  Allow provenance tags inside generated table cells when \refKey{showtags} is
  enabled.  Set this to \texttt{false} to retain tags in prose and other output
  while keeping tables uncluttered.  It has no effect when \refKey{showtags} is
  disabled.
\end{docKey}
\begin{docKey}{skip10pub}
  {={\meta{\texttt{true}\textbar\texttt{false}}}}
  {initially \texttt{false}.}
  Especially in the CV part, it might take longer to compile the reference list
  with the 10 most important publications. With this set to \meta{true} the
  reference list will be skipped.
\end{docKey}

\begin{docKey}{colorscheme}
  {\docKeyChoices{rgb,cmyk}}
  {initially \texttt{cmyk}.}
  Set the colorscheme according to your needs. For a PDF that is meant for
  only being displayed on a screen, go with \meta{rgb}, for a printed version
  choose \meta{cmyk}.
\end{docKey}



\begin{docKey}{cv}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  In the document which prints the CVs, set this option to \meta{true}, since
  it will show additional/needed text and modifications.
\end{docKey}


\begin{docKey}{final}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  When your proposal has been finalised and is ready to be submitted, set this
  option to \meta{true} for the final compilation. The capitalized alias
  \texttt{Final} is accepted for compatibility. This option has
  consequences for
  \refKey{showmarginalia},
  \refKey{showtags},
  \refKey{fastcompile},
  \refKey{fastcompile-project},
  \refKey{skip10pub},
  \refKey{fastcompile-project-show-publications},
  \refKey{colorscheme}, and open-access markers in the bibliography. Open-access
  DOI API lookup is enabled only in final documents when \refKey{doiAPIMail}
  is non-empty and LuaSocket is available.
\end{docKey}

\begin{dispListing*}{title={Example configuration for documentclass mit \texttt{final}-flag}}
  \documentclass[
    (*\refKey{final}*)           =true,
  % sets to false:
  (*\refKey{showmarginalia}*) =false,
    (*\refKey{showtags}*)       =false,
    (*\refKey{fastcompile}*)    =false,
    (*\refKey{fastcompile-project}*)=false,
    (*\refKey{fastcompile-project-show-funding-tables}*)=true,
    (*\refKey{skip10pub}*)      =false,
    (*\refKey{fastcompile-project-show-publications}*)=true,
    (*\refKey{colorscheme}*)    =cmyk
  ]{dfg-crc}
\end{dispListing*}

\subsection{Change default settings}
In the \dfgFile{preamble/dfg-customization} you can overwrite the default settings of
this documentclass.



Read these settings in text with \refCom{getValue}, for example
|\num{\getValue{animalHousing@mouse}}\,EUR|.

The following keys are to be set or changed in \refCom{changeSettings}:

\begin{docKeys}[doc parameter={=\meta{file path}}]{
  {doc name=crcLogoPath,
   doc description=initially \texttt{example-image-a}},
  {doc name=affiliationLogoPath,
   doc description=initially \texttt{example-image-b}}
}
  Select the image files used by \cs{crcLogo} and \cs{affiliationLogo}.
  As with \cs{includegraphics}, the file extension may be omitted.
\end{docKeys}

\begin{docKey}{doiAPIMail}{=\meta{email address}}{initially empty}
  Set the contact address required by the DOI API used for automatic
  open-access markers.  Network lookup remains disabled unless this value is
  non-empty, the document uses |final=true|, and LuaLaTeX has socket support.
\end{docKey}

\begin{docKey}{projectTitle}{=\meta{key-value list}}{all contexts initially \texttt{full}}
  Choose |full| (the project's \refKey{name}) or |short| (its optional
  \refKey{short-title}) independently for three contexts:
  |toc| is the project entry in the table of contents; |runningHead| is the
  title beside the PI names in the running head; |projectStart| is the
  \enquote{Project title:} heading at the beginning of the project.
  Omitted subkeys keep their current setting. The initial setting for all
  three is |full|. A missing or blank short title falls back to |name|.
  PDF project bookmarks independently use the project number followed by
  the PI surnames, for example \enquote{A02 \textbar{} Able - Baker}. Surnames retain
  their spelling and the order of |ref-person-id|; first names, academic
  degrees, project status and project titles are omitted. If no surname is
  available, the bookmark contains only the project number.
  Settings obey TeX grouping and may be overridden in the optional project
  setup argument until the matching project tail. The fast project mode
  continues to replay recorded header space without reading title metadata;
  refresh that record in normal mode after a title or selection change.
  |\getValue{projectTitle}| returns the three current selections.

\begin{dispListing*}{title={Short titles only in running heads.}}
% In the existing project metadata entry:
\addEntry{project}{
  id=Q02, number=Q02,
  name={Functional microbiome analysis},
  short-title={Microbiome analysis},
  project-type=service, project-status=C,
  ref-person-id={pi-id}
}
% In the preamble; TOC and project-start heading retain the full name:
\changeSettings{projectTitle={runningHead=short}}
% The complete equivalent selection is:
\changeSettings{projectTitle={toc=full,runningHead=short,projectStart=full}}
\end{dispListing*}

\begin{dispListing*}{title={Independent selection and a local project override.}}
% Use short titles in TOC and running heads, full titles at project starts:
\changeSettings{projectTitle={toc=short,runningHead=short,projectStart=full}}
% Temporarily use the short title at this project's start as well:
\printProject[\changeSettings{projectTitle={projectStart=short}}]{{Head}{Q02}}
% ... project text ...
\printProject{{Tail}{Q02}}
% projectStart=full is restored for the next project.
\end{dispListing*}
\end{docKey}

\begin{docKey}{cvTableAfterSkip}{=\meta{dimension}}{initially \texttt{0pt}}
  Adjust vertical space after the titled CV section boxes, including
  personal data, career, optional information, publications, and privacy.
  Categories A and B receive the adjustment separately; empty or skipped
  publication lists add no space. Negative values reduce the gap; positive
  values add space. Set |0pt| to disable the adjustment entirely.
  Expressions such as |-.5\baselineskip| are stored without expansion and
  evaluated after each box, so they follow the current line spacing. The
  default is zero because the boxes provide their own normal spacing.
  Settings obey TeX grouping. The existing \cs{dfgReduceSpace} command applies
  this setting, and |\getValue{cvTableAfterSkip}| returns its current value
  in points.
\begin{dispListing*}{title={CV section spacing in the customization file}}
\changeSettings{cvTableAfterSkip={-.5\baselineskip}}
% Or retain the table's normal spacing:
\changeSettings{cvTableAfterSkip=0pt}
\end{dispListing*}
\end{docKey}

\begin{docKey}{projectPIOncePerSection}{\docKeyChoices{true,false}}{initially \texttt{true}}
  Show the PIs attached to a project only on that project's first shared
  \refCom{getProject} or \refCom{getProjectPI} reference in each section.
  Later references use the compact project form. Set this to \texttt{false} to
  keep \refCom{getProject} compact and repeat the PI names at every
  \refCom{getProjectPI} reference. References to the current project and
  references in generated tables and lists always remain compact.
\end{docKey}

\begin{docKey}{PIReferenceFirstName}{\docKeyChoices{true,false}}{initially \texttt{false}}
  Include the firstname in unstarred \refCom{getPI} references. The starred
  form always includes it. Set this through \refCom{changeSettings}; it also
  affects person-first \refCom{getPIProject} and \refCom{getPIofProject}.
  Project-first \refCom{getProjectPI} references keep lastnames unless the
  command is starred. Shared PI surnames are automatically disambiguated by
  the first given-name initial in unstarred references, regardless of this
  setting. If that initial is also shared, the full firstname is used.
  Use the starred command to request full firstnames explicitly.
\end{docKey}

\begin{docKey}{projectsTableInstitutionAbbreviations}{\docKeyChoices{true,false}}{initially \texttt{false}}
  Control the institution display in \cs{ProjectsTable} and
  \cs{ProjectLeadersTable}.  With \texttt{true}, both tables use compact
  institution abbreviations; each projects table is followed by a tightly set
  legend containing only the abbreviations used in that table, sorted
  alphabetically by abbreviation.  Reusing one abbreviation for different
  institution names raises a package warning.  With \texttt{false}, full
  institution names are printed and no legend is added.
\end{docKey}

\begin{docKey}{categoryAbbreviations}{\docKeyChoices{true,false}}{initially \texttt{false}}
  Select compact English category labels with
  |\changeSettings{categoryAbbreviations=true}|. The setting applies to
  \cs{dfgCategoryName}, \cs{RequestedFundingTable}, the Category column and
  category-derived position lines of \cs{RequestedFundingStaffTable}, and CV
  positions that use a category label. Explicit or inherited |positionText|
  values retain their supplied text, even when they match a full category name.
  Set |false| to use the full names again; grouped and
  project-local settings are supported. Metadata continue to use the same
  category IDs in either mode. A custom category without a short label falls
  back to its registered full name.

  \begingroup
  \changeSettings{categoryAbbreviations=true}
  \begin{tabular}{@{}ll@{}}
    \textbf{Category ID} & \textbf{Short label} \\
    \texttt{PhD} & \dfgCategoryName{PhD} \\
    \texttt{postDoc} & \dfgCategoryName{postDoc} \\
    \texttt{medDoc} & \dfgCategoryName{medDoc} \\
    \texttt{groupLeader} & \dfgCategoryName{groupLeader} \\
    \texttt{research} & \dfgCategoryName{research} \\
    \texttt{nonResearch} & \dfgCategoryName{nonResearch} \\
    \texttt{student} & \dfgCategoryName{student} \\
    \texttt{assistant} & \dfgCategoryName{assistant} \\
    \texttt{prof} & \dfgCategoryName{prof} \\
    \texttt{prof-W2} & \dfgCategoryName{prof-W2} \\
    \texttt{prof-W3} & \dfgCategoryName{prof-W3}
  \end{tabular}
  \endgroup
\end{docKey}

\begin{dispListing*}{title={Automatic position labels and custom overrides}}
\changeSettings{categoryAbbreviations=true}
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id=A01, funding-status=requested, staff-type=research,
  lastname=TBA, category=postDoc, ref-institution-id=ins1,
  field-of-research=Biology,
  description={Performs the mechanistic experiments.}
}
% With no positionText, the position line is (Postdoc).
% Add positionText={Senior scientist} to retain custom wording.
% Add positionText={} to hide the position line.
\printTable{{RequestedFundingStaff}{A01}}
\end{dispListing*}

\begin{docKeys}[doc parameter={=\meta{option list}},
  doc description=initially empty]{
  {doc name=plotOptions},
  {doc name=ganttPlotOptions},
  {doc name=collaborationPlotOptions}
}
  Configure defaults for \refCom{printPlot} in
  |preamble/dfg-customization.tex|. The shared |plotOptions| list applies to
  Gantt and collaboration plots; the other two lists apply to their respective
  plot types. Each list accepts the same options as the corresponding plot
  call, including |caption|, native |hvFloat| options, and, for collaboration
  plots, |layout|, |arcs|, |area-colors|, and |area-palette|. Put options that
  only one renderer understands in its type-specific list.

  Options are processed in this order: built-in defaults
  (|floatPos=!hb,capPos=bottom|, and collaboration |layout=arc,arcs=false|),
  shared |plotOptions|, type-specific defaults, and per-call options. Later
  options override earlier ones. A legacy trailing caption takes precedence
  over all |caption| keys. Compatibility aliases use the same defaults.
  Settings are local to their TeX group and do not affect unrelated figures.
  Assigning a setting replaces its stored list; use |{}| to clear that layer.
  |\getValue{plotOptions}| and the corresponding type-specific getters return
  the currently stored lists. Native options are validated by |hvfloat| when
  a plot is printed.
\end{docKeys}

\begin{dispListing*}{title={Proposal-wide plot defaults and local overrides}}
\changeSettings{
  plotOptions={floatPos=!t,capPos=bottom},
  ganttPlotOptions={floatCapSep=8pt},
  collaborationPlotOptions={layout=heatmap,arcs=true}
}
\printPlot{{gantt}{Q01}}
\printPlot[floatPos=!hb,capPos=top]{{collaboration}{Q01}}
\end{dispListing*}

The class defines the native |hvFloat| style |proposalPlots| with
|floatPos=!t,capPos=top,floatCapSep=8pt|. Select it directly in the
customization file; no style definition or class hook is required there.
The style is available to both plot types and is only applied when selected.

\begin{dispListing*}{title={Select the built-in hvFloat style for generated plots}}
\changeSettings{plotOptions={style=proposalPlots}}
% An individual plot can override the named style:
\printPlot[capPos=bottom]{{gantt}{Q01}}
\end{dispListing*}

\begin{docKeys}[doc parameter={=\meta{color list}}]{
  {doc name=collaborationAreaColors,
   doc description=initially \texttt{A=projectA,B=projectB,Q=projectQ}},
  {doc name=collaborationAreaPalette,
   doc description=initially a rotating seven-color palette}
}
  Set collaboration-area colors once for every collaboration plot.
  |collaborationAreaColors| is a key--value mapping such as
  |{A=projectA,B=projectB,C=orange}|.  Areas absent from that mapping receive
  colors from |collaborationAreaPalette| in deterministic area order.  The
  corresponding |area-colors| and |area-palette| plot options override these
  settings for one \refCom{printPlot} call.
\end{docKeys}

\begin{docKeys}[doc parameter={=\meta{euros per year}}]{
  {doc name=salary@prof,
   doc description=initially \texttt{126600}},
  {doc name=salary@groupLeader,
   doc description=initially \texttt{105000}},
  {doc name=salary@postDoc,
   doc description=initially \texttt{90600}},
  {doc name=salary@medDoc,
   doc description=initially \texttt{112200}},
  {doc name=salary@PhD,
   doc description=initially \texttt{83700}},
  {doc name=salary@research,
   doc description=initially \texttt{69000}},
  {doc name=salary@nonResearch,
   doc description=initially \texttt{61500}},
  {doc name=salary@student,
   doc description=initially \texttt{1}},
  {doc name=salary@assistant,
   doc description=initially \texttt{1}}
}
  Set the annual salary rates used to calculate requested staff funding when
  a funding entry omits its explicit yearly sums.  The professorial rate is
  shared by the |prof|, |prof-W2|, and |prof-W3| categories.
\end{docKeys}

\begin{docKeys}[doc parameter={=\meta{euros per animal and week}}]{
  {doc name=animalHousing@mouse,
   doc description=initially \texttt{0.75}},
  {doc name=animalHousing@mouseGnotobiotic,
   doc description=initially \texttt{3.9}},
  {doc name=animalHousing@rat,
   doc description=initially \texttt{1.4}}
}
  Set the weekly animal-housing rates used by the upkeep-of-laboratory-animals
  table.  All salary and animal-housing settings accept integer or decimal
  numbers. Register additional animal types and their rates with
  \refCom{DeclareAnimalType}.
\end{docKeys}

\begin{docKey}{thumbindex}{\docKeyChoices{true,false}}{initially \texttt{true}}
  Shows a thumbindex in the outer margin. This can be customized further.
\end{docKey}


Customize further all about the thumbindex. Modification done in
\dfgFile{dfg-customization}.
\begin{docKey}{thumbindex@pattern}{=\meta{int}}{initially \texttt{10}}
  Define how long the pattern of the \refKey{thumbindex} is until it starts again from
  the top of the page.
\end{docKey}

\begin{docKeys}[doc parameter = {=\meta{dim}\textbar\texttt{auto}}]{
    {
      doc name = thumbindex@topmargin,
      doc description = initially \texttt{auto},
    },
    {
      doc name = thumbindex@bottommargin,
      doc description = initially \texttt{auto},
    },
  }
  With \texttt{auto}, the first tab starts at the top of the text block and the
  last tab ends at its bottom; the tabs divide the current \cs{textheight} into
  \refKey{thumbindex@pattern} equal slots.  Set either key to a dimension to
  place that end of the tab stack the specified distance from the corresponding
  page edge.  With the default \texttt{auto} values, the dimensions are
  recalculated for the current page layout, so changes to the text height also
  change the thumb-index spacing. Tabs are positioned directly when the page
  is shipped out; their placement does not depend on picture coordinates from
  an earlier LaTeX pass.
\end{docKeys}


\begin{docKey}{thumbindex@width}{=\meta{dim}}{initially \texttt{1.2cm}}
  Define how far a thumb-index tab extends into the outer margin.  The default
  12\,mm tab fits inside the 13\,mm marginal column.
\end{docKey}

\begin{docKey}{thumbindex@orientation}{\docKeyChoices{outwards,inwards}}{initially \texttt{outwards}}
  Choose which way the thumb-index text faces on both left and right pages.
  With \texttt{outwards}, the tops of the letters point towards the outer page
  edge (the existing orientation). With \texttt{inwards}, they point towards
  the text block: the label is turned by 180 degrees. The tab's position,
  dimensions, and slot order stay the same. In both orientations the label
  is inset 2\,mm from the tab center towards the text block on each page side.
  Set |\changeSettings{thumbindex@orientation=inwards}| in
  |preamble/dfg-customization.tex| to flip the labels.
\end{docKey}

\begin{docKey}{thumbindex@font}{=\meta{ticklist}}{initially \texttt{\cs{bfseries}\cs{Huge}}}
  Define the \meta{font} style of the text in the thumbindex.
\end{docKey}

\begin{docKeys}[doc parameter = {=\meta{colorname}}]{
    {
      doc name =  color@thumbindex@bg,
      doc description = initially \texttt{black},
    },
    {
      doc name = color@thumbindex@font,
      doc description = initially \texttt{white},
    },
  }
  Define the color of the thumbindex: like the background color (\meta{bg}) or
  the color of the \meta{font}
\end{docKeys}

You can adjust any color in this template. In case you want to reuse a custom
color of e.g. your corporate design, set this up first:

\begin{dispListing}
  \definecolor{my-blue}{RGB}{0,84,159}
\end{dispListing}
Afterwards you can use |my-blue| to any of the colors below.

\begin{docKey}{color@reference@boldAuthor}{=\meta{colorname}}{initially \texttt{black}}
  Define the color of emphasized author names in bibliographies.
\end{docKey}

\begin{docKey}{color@reference@PI}{=\meta{colorname} or \texttt{current}}{initially \texttt{black}}
  Define the color of references to principal investigators. Use |current|
  to inherit the surrounding text color at each reference instead of applying
  a fixed color. This applies to \cs{getPI} (including its starred and custom-text
  forms) and the project-reference commands that use it. Set this key in the
  preamble, for example:
  \begin{dispListing}
    \changeSettings{color@reference@PI=current}
    % Or use a named xcolor color:
    \changeSettings{color@reference@PI=blue}
  \end{dispListing}
\end{docKey}

\begin{docKey}{color@reference@WP}{=\meta{colorname}}{initially \texttt{black}}
  Define the color of references to work packages.
\end{docKey}

\begin{docKey}{color@reference@Aim}{=\meta{colorname}}{initially \texttt{black}}
  Define the color of references to aims.
\end{docKey}

\begin{docKey}{color@table@headingsBG}{=\meta{colorname}}{initially \texttt{blue-50}}
  Define the background color of a table header (i.e. first row).
\end{docKey}

\begin{docKey}{color@table@headingsBGalt}{=\meta{colorname}}{initially \texttt{blue-25}}
  Define an alternative background color of a table header (i.e. for
  subdividing row).
\end{docKey}

\begin{docKey}{color@table@headingsFont}{=\meta{colorname}}{initially \texttt{black}}
  Define the color for the font in the header rows.
\end{docKey}

\begin{docKey}{color@table@rows}{=\meta{colorname}}{initially \texttt{black-10}}
  Define the color for alternating rows.
\end{docKey}


\begin{docKey}{color@table@lines}{=\meta{colorname}}{initially \texttt{black-10}}
  Define the color for inner table lines.
\end{docKey}


\begin{docKey}{color@table@outerLines}{=\meta{colorname}}{initially \texttt{black}}
  Define the color for outer table lines and both the horizontal rules and
  dashed vertical grid lines in Gantt charts.
\end{docKey}


\begin{docKey}{color@table@noValue}{=\meta{colorname}}{initially \texttt{black-10}}
  Define the color for cells that are supposed to contain no value.
\end{docKey}

\begin{docKey}{color@table@firstColumn}{=\meta{colorname}}{initially \texttt{black}}
  Set the foreground color of first-column cells in layouts that use this
  setting. Other tables retain their own column styles.
\end{docKey}

\begin{docKey}{color@table@link}{=\meta{colorname}}{initially \texttt{black}}
  Set the table-link color so hyperlinks remain readable against the
  table-heading background.
\end{docKey}

\begin{docKey}{color@table@contFootHead}{=\meta{colorname}}{initially \texttt{black}}
  Set the text color of the continuation heading and footer of long tables.
\end{docKey}

\begin{docKey}{color@table@caption}{=\meta{colorname}}{initially \texttt{black}}
  Set the text color of table captions.
\end{docKey}

\begin{docKeys}[
    doc parameter = {=\meta{colorname}}
  ]{
    {
      doc name        = color@tags@font,
      doc description = initially \texttt{red-100}
    },
    {
      doc name        = color@tags@line,
      doc description = initially \texttt{black-50}
    },
  }
  Adjust the color of \meta{font} or \meta{line} when \refKey{showmarginalia} is activated.
\end{docKeys}

\begin{docKey}{color@item@i}{=\meta{colorname}}{initially \texttt{black}}
  Depending on the color of the table heading, we need to modify the
  color of the hyperlink since it can be the same as the
  colorlink from \refPkg{hyperref}.
\end{docKey}

\begin{docKey}{color@font@alternative}{=\meta{colorname}}{initially \texttt{black-50}}
  Define the alternative color for headline fonts, especially in the CV section, \refKey{cv}.
\end{docKey}

\begin{docKeys}[
    doc parameter = {=\meta{colorname}}
  ]{
    {
      doc name        = color@gantt@frame,
      doc description = initially \texttt{white}
    },
    {
      doc name        = color@gantt@default,
      doc description = initially \texttt{blue-25}
    },
    {
      doc name        = color@gantt@alternative,
      doc description = initially \texttt{green-25}
    },
    {
      doc name        = color@gantt@crosshatch,
      doc description = initially \texttt{black-10}
    },
    {
      doc name        = color@gantt@important,
      doc description = initially \texttt{red}
    },
    {
      doc name        = color@gantt@stripe-one,
      doc description = initially \texttt{blue-25}
    },
    {
      doc name        = color@gantt@stripe-two,
      doc description = initially \texttt{green-25}
    },
  }
  Adjust the colors for the various styles of the gantt chart in the project
  section.
  The style |striped| is a alternating combination of
  \refKey{color@gantt@stripe-one} and \refKey{color@gantt@stripe-two}.
  Set these keys with \refCom{changeSettings} in the customization file,
  before the document starts. For rendered examples and grouped overrides
  of an individual chart, see
  \dfgExampleRef{ex:manual-gantt-five-bar-styles},
  \dfgExampleRef{ex:manual-gantt-custom-colours}, and
  \dfgExampleRef{ex:manual-gantt-grayscale}.
\end{docKeys}


\begin{docKeys}{
    {
      doc name        = biblatexstyleCV,
      doc parameter   = {=\meta{style}},
      doc description = initially \texttt{ext-numeric-comp}
    },
    {
      doc name        = biblatexstyleFeatureCV,
      doc parameter   = {=\meta{clist}},
      doc description = initially \texttt{sorting=none}
    },
    {
      doc name        = biblatexstyleProposal,
      doc parameter   = {=\meta{style}},
      doc description = initially \texttt{ext-authoryear-ecomp}
    },
    {
      doc name        = biblatexstyleFeatureProposal,
      doc parameter   = {=\meta{clist}},
      doc description = initially empty
    },
  }
  Adjust the citation and bibliography style separately for standalone CVs
  and proposals.  The feature values are comma-separated additional
  \pkg{biblatex} package options.  Proposal features default to empty so
  changing styles does not pass unsupported options.  Add style-specific
  options such as \texttt{dashed=false} explicitly when supported.
  Options shared by both modes, including
  \texttt{backend=biber}, \texttt{autocite=inline},
  \texttt{defernumbers=true}, \texttt{giveninits=true}, the citation-name
  limits, and \texttt{maxbibnames=99}, are supplied by the class.
  The class selects the CV pair when the document-class option
  \refKey{cv} is true and the proposal pair otherwise.  The legacy keys
  \texttt{biblatexstyle} and \texttt{biblatexstyleFeature} remain available;
  each applies its value to both modes.
\end{docKeys}

\begin{dispListing*}{title={Configure CV and proposal bibliographies independently.}}
  \changeSettings{
    biblatexstyleCV              = ext-numeric-comp,
    biblatexstyleFeatureCV       = {sorting=none},
    biblatexstyleProposal        = ext-authoryear-ecomp,
    biblatexstyleFeatureProposal = {},
  }
\end{dispListing*}

\begin{docKey}{journalTitle}{=\meta{field}}{initially \texttt{journaltitle}}
Select the journal title printed in bibliographies and full citations:
\texttt{journaltitle} uses the full title; \texttt{shortjournal} uses the
standard \pkg{biblatex} abbreviation field. If \texttt{shortjournal} is absent,
the full journal title and its subtitle are retained. When a short title is
available, the full journal subtitle is omitted. The bibliography style still
controls typography and punctuation.

Store both forms in the same BibTeX entry, preferably using the NLM Title
Abbreviation from the NLM Catalog or PubMed. Do not invent abbreviations for
unidentified journals. This setting selects existing data; it performs no
network requests during compilation.
\begin{dispListing*}{title={Full journal titles by default; abbreviations on request.}}
@article{example,
  author       = {Example, Alice},
  title        = {An example article},
  journaltitle = {Journal of Hepatology},
  shortjournal = {J Hepatol},
  date         = {2026},
}
\end{dispListing*}
\begin{dispListing*}{title={Choose the printed journal-title field.}}
\changeSettings{journalTitle=journaltitle} % default: full titles
% Alternatively:
\changeSettings{journalTitle=shortjournal} % abbreviations with fallback
\end{dispListing*}
The choice can also be scoped to a group around a bibliography or
\cs{fullcite}; changing it does not require a new Biber run when both fields
are already present in the processed bibliography. The source data remain
available in both forms.
\end{docKey}

\paragraph{Bibliography font and entry spacing}
The length \cs{bibitemsep} controls the extra vertical gap between bibliography
entries, independently of the line spacing within an entry. A gap can already
be present without a template override: the alphabetic styles inherit
\cs{itemsep} at package load time; this may already be zero in the current
class and list configuration. Other styles can supply different defaults.

To use footnote-sized text and remove this extra gap, add the following hook
outside \cs{changeSettings} in |preamble/dfg-customization.tex|. The file is
read before \pkg{biblatex}, so its lengths and font command must be changed
after the package has loaded.
\begin{dispListing*}{title={Compact bibliographies through the customization file.}}
\AddToHook{package/biblatex/after}{%
  \renewcommand*{\bibfont}{\normalfont\footnotesize}%
  \setlength{\bibitemsep}{0pt}%
}
\end{dispListing*}
This applies to ordinary \cs{printbibliography} calls and to
\refCom{printProjectBibliography} and \refCom{printFrameBibliography}.
Replace |0pt| with |2pt|, for example, to
keep a small extra gap. The CV publication environment |DFGlist| uses
|nosep| already; to add space there, set |itemsep=2pt| after |nosep| in its
list configuration. There is no \cs{changeSettings} key for entry spacing.

\begin{docKey}{emphasizeAuthors}
  {\docKeyChoices{true,false}}
  {initially \texttt{true}.}
  Emphasize the authors in a e.g. project section when they are authors of a
  referenced publication.
\end{docKey}

\begin{docKey}{emphasizeEntries}
  {\docKeyChoices{true,false}}
  {initially \texttt{false}.}
  Bold a complete entry in \cs{printProjectBibliography} when its
  \texttt{Keywords} field contains the current project ID followed by
  \texttt{-highlight}.  For example, \texttt{B06-highlight} applies only to
  Project B06. In \cs{printFrameBibliography}, the keyword
  \texttt{frametext-highlight} selects complete entries instead. Each keyword
  applies only to its corresponding bibliography context.
  This setting is independent of \refKey{emphasizeAuthors},
  which controls name highlighting.  A \texttt{B06-project} keyword alone does
  not trigger bold type.  To show only the keyword-selected full entries in
  bold, use \texttt{emphasizeAuthors=false} together with
  \texttt{emphasizeEntries=true}.
\end{docKey}

\begin{docKeys}{
    {
      doc name        = font,
      doc parameter = {=\meta{name}},
      doc description = initially \texttt{Arimo}
    },
    {
      doc name        = sansfont,
      doc parameter = {=\meta{name}},
      doc description = initially \texttt{Arimo}
    },
  }
  Define the main font and the sansserif font.
\end{docKeys}

\begin{docKeys}{
    {
      doc name        = fontspec,
      doc parameter = {=\meta{name}},
      doc description = initially \texttt{none}
    },
    {
      doc name        = sansfontspec,
      doc parameter = {=\meta{name}},
      doc description = initially \texttt{ItalicFont=Roboto-LightItalic,\\
        BoldFont=Roboto-Medium,\\
        BoldItalicFont=Roboto-Medium-Italic}
    },
  }
  Customize font and sansserif font features.
\end{docKeys}
The current \refKey{sansfontspec} default explicitly selects Roboto faces
for italic, bold, and bold italic sansserif text. Changing only
\refKey{sansfont} does not remove these selections. To let fontspec select
all faces from one installed family, clear these feature overrides, for
example:
\begin{dispListing*}{title={Select all main and sansserif faces from Arimo.}}
\changeSettings{
  font         = Arimo,
  sansfont     = Arimo,
  sansfontspec = {},
}
\end{dispListing*}
To use Arial instead, replace both family names with |Arial|; that font
must be installed on the compiling system.

\subsection{Thumbindex}
In your document you can use the following commands for displaying or switching
off a thumbindex \emph{locally}.

The tabs are correctly positioned on the first LuaLaTeX run, without an extra
run for remembered TikZ coordinates. This concerns the thumb-index placement
only: the table of contents, cross-references and bibliography may still need
further compilation runs.

\begin{docCommand}{printThumbIndex}{\oarg{options}\marg{string}}
  Select a tab displaying \meta{string} for the current and following pages.
  The complete tab, including its label, is drawn in the page background;
  overlapping document text or graphics are printed over it.
  The optional comma-separated keys |bg| and |fg| set its background and label
  colours. Both accept named colours and \pkg{xcolor} mixtures. Omitted colours
  use |color@thumbindex@bg| and |color@thumbindex@font| from \cs{changeSettings}.
  The overrides last until another tab is selected, within the surrounding
  TeX scope; they do not change these configured defaults.

  Every call starts from the configured defaults, including calls with no
  optional argument or with |[]|. Thus a dark label selected for a light tab
  does not carry over to the next project's tab. The old bare-colour syntax
  remains accepted as shorthand for |bg| only; it also uses the default label
  colour. Unlike the old background inheritance, an omitted background now
  returns to the configured default.

\begin{dispListing*}{title={Tab colours and the compatible background shorthand.}}
\printThumbIndex[bg=black!20,fg=black]{1}
% For the next tab, end the current page first:
\clearpage
\printThumbIndex[blue-100]{A01}
% Equivalent to: \printThumbIndex[bg=blue-100]{A01}
% The label uses the configured default colour again.
\end{dispListing*}

  To override only the label colour, use |\printThumbIndex[fg=black]{1}|.
  A macro may supply a colour value or the entire options argument. If the
  new tab should start on the next page, first finish the current page with
  \cs{clearpage}, then call this command.
\end{docCommand}

\begin{docCommand}{printThumbIndexOff}{}
  Remove the tab from following pages.  This changes visibility only.
\end{docCommand}

\begin{docCommand}{resetThumbIndex}{}
  Reset the thumb-index slot counter.  The next \cs{printThumbIndex} call
  starts at the first slot again.  This changes only the position counter;
  use \cs{printThumbIndexOff} separately if the current tab should be hidden.
\end{docCommand}


\subsection{ORCiD}
The ORCiD is foremost used in the CV section and stated in the entry of a
person. So there is no need for a manual insertion of it. However you can do so
using one of two following commands.

\begin{docCommand}{ORCiD}{\marg{number}}
  Display the ORCiD with the given \meta{number}.
  Adding the ORCiD logo in front.

  See \dfgExampleRef{ex:manual-an-orcid-from-metadata}.
\end{docCommand}

\begin{docCommand}{getORCiD}{\marg{id}}
  Display the ORCiD of the person with the given \meta{id}
  If there is no |orcid|-entry in the database for this person, then a warning will be
  thrown and you can read about in the |.log|-file.

  See \dfgExampleRef{ex:manual-an-orcid-from-metadata}.
\end{docCommand}


\begin{dfgExample}[label={ex:manual-an-orcid-from-metadata}]{An ORCiD from metadata}
\ORCiD{0000-0000-0000-0001}\par
\getORCiD{per1}\par
\getORCiDvalue{per1}
\end{dfgExample}

\section{Bibliography/Publication}
\subsection{Equal contribution}
In some cases it is very important to state that two or more authors
have contributed equally to a publication.
Take the following publication as example:
\begin{dispListing}
  Schneider, K.M.*, C. Elfers*, A. Ghallab, C.V. Schneider,
  E.J.C. Galvez, A. Mohs, W. Gui, L.S. Candels, T.H. Wirtz,
  S. Zuehlke, M. Spiteller, M. Myllys, A. Roulet, A.
  Ouzerdine, B. Lelouvier, K. Kilic, L. Liao, A. Nier, E.
  Latz, I. Bergheim, C.A. Thaiss, J.G. Hengstler, T.
  Strowig, and C. Trautwein. 2020. Intestinal Dysbiosis
  Amplifies Acetaminophen-Induced Acute Liver Injury. Cell.
  Mol. Gastroenterol. Hepatol. 11(4):909-933. *equal contribution
\end{dispListing}
The first authors have \texttt{equal contribution}.
In the bibtex-entry add \emph{two} lines:
\begin{dispListing}
  author+an       = {1=equal;2=equal},
  addendum        = equal,
\end{dispListing}
With \texttt{author+an} you annotate the authors, the numbers refer to the
position of the author in the authors's list.

The complete entry of the mentioned example looks like:

\begin{dispListing}
@article{schneider2020a,
  author          = {Schneider, Kai Markus and Elfers, Carsten and Ghallab,
      Ahmed and Schneider, Carolin Victoria and Galvez, Eric J.C.
      and Mohs, Antje and Gui, Wenfang and Candels, Lena Susanna and
      Wirtz, Theresa Hildegard and Zuehlke, Sebastian and Spiteller,
      Michael and Myllys, Maiju and Roulet, Alain and Ouzerdine,
      Amirouche and Lelouvier, Benjamin and Kilic, Konrad and Liao,
      Lijun and Nier, Anika and Latz, Eicke and Bergheim, Ina and
      Thaiss, Christoph A. and Hengstler, Jan G. and Strowig, Till
      and Trautwein, Christian},
  author+an       = {1=equal;2=equal},
  date            = 2020,
  title           = {Intestinal Dysbiosis Amplifies Acetaminophen-Induced Acute
      Liver Injury},
  volume          = 11,
  pages           = {909--933},
  language        = {pt},
  journal         = {Cellular and Molecular Gastroenterology and Hepatology},
  doi             = {10.1016/j.jcmgh.2020.11.002},
  number          = 4,
  source          = {Crossref},
  url             = {https://doi.org/10.1016/j.jcmgh.2020.11.002},
  publisher       = {Elsevier BV},
  issn            = {2352-345X},
  date            = 2021,
  addendum        = equal,
}
\end{dispListing}
\subsection{Shared last authorship}
Very similar to the \texttt{equal contribution}-part there is also a way to
specify authors who \texttt{shared last authorship}.

In the bibtex-entry add \emph{two} lines:

\begin{dispListing}
  author+an       = {1=sharedLast;2=sharedLast},
  addendum        = sharedLast,
\end{dispListing}

Here is a complete example.

\begin{dispListing}
@Article{roessner2021a,
  Author          = {Roessner, P.M. and Cid, L.Llao and Lupar, E. and Roider,
      T. and Bordas, M. and Schifflers, C. and Arseni, L. and
      Gaupel, A.C. and Kilpert, F. and Krotschel, M. and
      Arnold, S.J. and Sellner, L. and Colomer, D. and
      Stilgenbauer, S. and Dietrich, S. and Lichter, P. and
      Izcue, A. and Seiffert, M.},
  Date            = {2021},
  author+an       = {17=sharedLast;18=sharedLast},
  Addendum        = sharedLast,
  Keywords        = {MM-A},
  Title           = {{EOMES} and {IL}-10 regulate antitumor activity of T
      regulatory type 1 {CD4(+)} T cells in chronic lymphocytic
      leukemia},
  Volume          = {35},
  Pages           = {2311--2324},
  Language        = {en},
  JournalTitle    = {Leukemia}
}
\end{dispListing}


\subsection{Emphasizing authors}
\label{sec:doc:bold-authors}
You can have certain authors in bold letters in your bibliography section to
highlight e.g. the core people of the proposal.

\textbf{Notice:} This feature is automatically triggered (unless switched off, see \refKey{emphasizeAuthors})
for the CV section (see \ref{sec:doc:cv-basic}). We explain its function for additional use.

The switch is also evaluated during rendering. A project with loaded metadata
|project-status=E| defaults to |emphasizeAuthors=true,emphasizeEntries=false|.
Its project leaders' \refKey{name-alias} values are registered automatically.
Optional setup on \cs{printProject} or \cs{printProjectHead} takes precedence
over these defaults, and the matching tail restores the previous settings.


To add a person to the (sectioned) bibliography use \cs{addboldnames}.

\begin{docCommand}{addboldnames}{
  \marg{\brackets{nn},
    \brackets{nn},
    \brackets{nn}}
}

Displaying authors in an emphasized way.
\end{docCommand}

Notice that for each variation of a person’s name you have to add one set of
\marg{nn}.
For example you have an author with different spellings in your |.bib|-file, you
have to list all of them to get them in bold letters (or adjust the entries in
your |.bib|-file).

\begin{dispListing}
  \addboldnames{
    {Max Doe},
    {M. Doe},
    {Doe, Max H.},
    {Doe, Max Heinrich}
  }
\end{dispListing}

After a (sectioned) bibliography and you do not want to display the before
defined authors in bold letters anymore, you can use \cs{resetboldnames}:
\begin{docCommand}{resetboldnames}{}
  Switch off showing the under \refCom{addboldnames} defined names.
\end{docCommand}


In case you do not need to have authors in bold letters
you can disable the feature modification done in \dfgFile{dfg-customization}.


\subsection{Providing publication information}
\label{sec:manual-cv-publications}

Providing the most relevant publications is done through the referenced
|.bib|-file.
Within a bibtex-entry you need to add a keyword with certain values to it
preceeded with the ID of the person.

\begin{itemize}
  \item[-A:]Category A – Articles in peer-reviewed journals, contributions to
        peer-reviewed conferences or to anthology volumes, and book publications
  \item[-B:] Category B – Any other form of published results
\end{itemize}
For example:
\begin{dispListing}
  @article{...,
      keywords = {<ID>-A},
    }
\end{dispListing}

To bold the complete bibliography entry only in Project B06, add its
project-specific highlight keyword alongside any publication keywords:
\begin{dispListing}
  @article{...,
    keywords = {pabst-A,B06-highlight},
  }
\end{dispListing}
This affects project bibliography lists, including project-report references
and published-result lists.  The same entry is not bolded in other projects
unless their own \texttt{<project-id>-highlight} keyword is present.  Set
\texttt{emphasizeEntries=true} in \cs{changeSettings} to enable this feature.
Only one highlight keyword per distinct project is needed, even when several
PIs from that project coauthor the publication.  For a publication to be bold
in both B06 and Q04, use each keyword once:
\begin{dispListing}
  @article{...,
    keywords = {pabst-A,B06-highlight,Q04-highlight},
  }
\end{dispListing}
The optional \texttt{B06-project} keyword can record project membership for
other workflows, but it does not activate \refKey{emphasizeEntries}.  Existing
CV-selection keywords such as \texttt{pabst-A} can stay in the same field.

For the frame-text bibliography in chapter 1, add
\texttt{frametext-highlight} and use \refCom{printFrameBibliography}:
\begin{dispListing}
  @article{...,
    keywords = {pabst-A,B06-highlight,frametext-highlight},
  }
\end{dispListing}
With \texttt{emphasizeEntries=true}, this entry is bold in both the B06
project bibliography and the frame-text bibliography. Neither keyword
changes formatting in other bibliography contexts or in inline citations.

Of course several people can use the same reference for this section:

\begin{dispListing}
  @article{...,
      keywords = {<ID1>-A, <ID2>-B, <ID3>-A},
    }
\end{dispListing}

Open-access markers are handled by |biblatex-ext-oa|. The symbol remains a
link to the detected accessible version. In DOI API mode the class clears
the package's |api:bestoaurl| bibliography macro, suppressing the additional
``open access version at'' text and URL. The bibliography style still
controls ordinary DOI, eprint, and URL output. This does not disable the
open-access lookup or the linked symbol.

If the API-based open-access request does not work for a publication, add
the fallback annotation directly to the relevant |.bib| entry:

\begin{dispListing}
  @article{...,
      options         = {openaccess=auto},
      doi+an:default  = {=openaccess},
    }
\end{dispListing}



\section{Automatic wording and list cardinality}
\paragraph{Automatic singular, plural, and cardinality-dependent output}

The class derives the following visible wording and layout from the number of
metadata items.  These are the places where changing a one-item list to two or
more items changes more than the retrieved data itself.

\begin{description}
  \item[Project PIs]
    \refCom{printProjectHead} counts the comma-separated PI ids in the
    project's \refKey{ref-person-id} field.  Exactly one id selects the
    singular branch; two or more ids select the plural branch.  The field is
    required, so an empty list is invalid metadata; internally it falls back
    to the singular branch.

    This PI count controls all of the following output:
    \par\noindent\textbullet\space the heading \enquote{Project leader} or
        \enquote{Project leaders};
    \par\noindent\textbullet\space the \cs{getPersonInformation} layout, which
        shows one PI in a full-width one-column raster and several PIs in a
        two-column raster of cards, with the same gap below the heading;
    \par\noindent\textbullet\space contract question C1, which uses
        \enquote{project leader at the institution} or
        \enquote{project leaders at the institutions};
    \par\noindent\textbullet\space contract question C2, which switches between
        \enquote{Does the above mentioned person hold a fixed-term position?}
        and \enquote{Do any of the above mentioned persons hold fixed-term
        positions?};
    \par\noindent\textbullet\space contract question C3, which switches between
        \enquote{Will the above mentioned person} and
        \enquote{Will one or more of the above-mentioned persons};
    \par\noindent\textbullet\space contract question C4, which again uses singular or plural
        \enquote{project leader(s)} and \enquote{institution(s)}; and
    \par\noindent\textbullet\space contract answers, where PI surnames are appended in parentheses
        only when several PIs must be distinguished.  Lists of dates or other
        follow-up values likewise append surnames when more than one matching
        PI contributes a value.

  \item[Research areas]
    In \refCom{printProjectHead}, one value in the project's
    \refKey{research-area} field produces the heading
    \enquote{Research area}; two or more values produce
    \enquote{Research areas}.

  \item[Applicant affiliations]
    \refCom{dfgApplicantAffiliationsTF} selects its first argument for one id
    in |meta.ref-affiliation-id| and its second argument for two or more ids.
    This helper controls:
    \par\noindent\textbullet\space whether the title page prints an additional-applicant block;
    \par\noindent\textbullet\space \enquote{applicant university} or
        \enquote{applicant universities} in the existing-direct-costs table;
    \par\noindent\textbullet\space the Chapter~1 heading \enquote{Research profile of the applicant
        university/universities};
    \par\noindent\textbullet\space \enquote{coordinating university/universities} in the Chapter~4
        bylaws heading; and
    \par\noindent\textbullet\space both the noun and verb in the Chapter~5 declaration:
        \enquote{The applicant university confirms} or
        \enquote{The applicant universities confirm}.

    On the title page, \cs{dfgOtherApplicantAffiliationsTF} applies the
    same rule after the first, coordinating affiliation has been removed:
    exactly two applicant affiliations in total produce
    \enquote{Other applicant university}, while three or more produce
    \enquote{Other applicant universities}.

  \item[Existing-staff overview]
    \refCom{OverviewExistingStaffTable} uses the number of applicant
    affiliations for its spanning group heading: one applicant id produces
    \enquote{applicant university}, while several produce
    \enquote{applicant universities}.  Other affiliation columns do not
    affect this wording.

  \item[One-, two-, and longer-item lists]
    Several formatters change punctuation rather than nouns.  In prose,
    \refCom{getPI}, \refCom{getProject}, \refCom{getProjectPI}, and
    \refCom{getPIProject} print one item without a separator, two items with
    \enquote{and}, and three or more with commas plus a final
    \enquote{and}.  Project and PI references inside tables instead use compact
    slash separators.  The complete applicant-name, applicant-location, and
    other-applicant lists exposed by \cs{theCRCaffiliation},
    \cs{theCRCaffiliationLocation}, and
    \cs{theCRCOtherApplicantAffiliations} use the same natural-language rule.
    \refCom{printList}|{ResearchAreasFromProjects}| uses a comma for exactly
    two items and a final \enquote{and} for lists of three or more.
\end{description}

Fixed text written directly in project content is not altered automatically;
authors must choose its singular or plural form themselves.

\section{Project-area entries in the contents}
\begin{docCommand}{dfgTOCprojectPart}{\marg{letter}\oarg{label}\marg{title}}
  Add a project-area heading to the table of contents.  The \meta{letter}
  identifies the project area, \meta{label} defaults to \texttt{Project area},
  and \meta{title} is the text printed after the area label.
\end{docCommand}

\begin{dispListing*}{title={Wrap a project section.}}
  \dfgTOCprojectPart{A}{Microbiota and metabolic pathways}
  \printProjectHead{A01}
  \ldots
  \printProjectTail
\end{dispListing*}


\section{Optional inputs and diagnostics}
\begin{docCommand}{checkFile}{\marg{file}}
  Input \meta{file} if it exists.  If the file is missing, compilation
  continues and a warning is written to the log.  This is used for optional
  metadata, customization, and content files.
\end{docCommand}


\section{Troubleshooting}

The class reports missing or inconsistent data in the terminal and the
\texttt{.log} file.  If your editor does not collect those messages, this
command shows the class messages together:

\begin{dispListing*}{title={Show DFG class messages in a log file}}
grep 'Package dfg' <filename>.log
\end{dispListing*}

\begin{description}
  \item[\texttt{Unknown database name}] The database has not been loaded, or
    the database name was misspelled.  Check the relevant metadata file and
    whether it is input by the class.
  \item[Missing or empty key warnings] The row exists, but the requested field
    is empty.  This is intentional where the template needs to alert the user,
    for example for missing ORCiD values.
  \item[\texttt{Not allowed in LR mode}] Vertical material such as
    \cs{vspace}, \cs{addvspace}, or a paragraph break was inserted in a table
    place that only accepts horizontal material.  Prefer the documented table
    and list commands, or use options such as \texttt{narrow} for compact table
    output.
  \item[Stale output] Regenerate the class with \texttt{make files}, and check
    whether the document uses the generated class from \texttt{local/}.
\end{description}

\section{Complete shared metadata for the examples}
\label{sec:manual-fixtures}
The following records define the people, institutions, affiliations, and
projects used throughout the live examples. They are extracted from the same
DTX records loaded by this manual and generated into
|local/metadata/dfg-metadata.tex| for the local proposal and CV. Matching career
records are generated into |local/metadata/dfg-metadata-cv.tex|. The shared data
are listed once here to avoid repeating the setup before every PI and project
table. Adapt these declarations for your own consortium, then use the table and
list commands from the walkthrough. The final command produces the project-leader table already shown
in the general-information section.

\dfgTableSetup{pis}{Shared input records for the proposal examples}

\section{Release workflow for maintainers}

For a new release, update \cs{dfgVersion} and \cs{dfgVersionDate} at the top of
\texttt{dfg-crc.dtx}, the release line in the
README block, and \texttt{dfg-crc.pkg}. Add a
|\changes{version}{date}{description}| entry in the documented source.
The manual records these entries with \cs{RecordChanges} and prints them
with \cs{PrintChanges}; \texttt{latexmk} runs MakeIndex using
\texttt{gglo.ist} through the repository configuration. Keep the release
changes in one commit. Licensing is recorded at the top of the DTX; no
separate changelog or license file is generated or included in the archive.

\begin{dispListing*}{title={Release and CTAN checks}}
make ctan-check
make check
% Optional online validation without submission:
make ctan-validate
\end{dispListing*}

The focused targets \texttt{make test-command-options} and
\texttt{make test-participating-institutions} run 30 argument/option checks and
10 layout cases, respectively. The command-options fixture also checks
14 document-text cases: the generic date, early customization, later settings,
direct redefinitions, deferred references, and local scope. Both targets are
included in \texttt{make check}.
The target \texttt{make test-workpackage-metadata} checks stored raw fields,
new-key precedence in either source order, omitted and empty labels, partial
migration and deferred macro values. It compiles in normal mode and in focused
project mode with images enabled and disabled, then checks the rendered
headings, nested references and chart labels. Its fixture is extracted from
the DTX; \texttt{ci/check-workpackage-metadata.lua} validates the PDFs. This
target is included in \texttt{make check}.
The target \texttt{make test-project-head-layout} records normal header geometry,
then compiles the same six projects without metadata in focused mode. It
compares following headings and paragraph coordinates, page breaks, section
counters and cache persistence at two text heights. A poisoned metadata file
and database assertions detect unintended metadata reads. Missing-record and
changed-dimension cases check the marked fallback. The fixture and runner are
in \texttt{ci/}; the target is included in \texttt{make check}.
The target \texttt{make test-plot-section-order} checks physical PDF positions
for collaboration and Gantt plots near page boundaries in normal and focused
image builds. It covers explicit/current project IDs, compatibility shorthands
and both caption forms. The fixture keeps the real dispatcher and float wrapper
and substitutes only deterministic picture contents; the checker requires the
plot to follow its section heading on the same or a later page.
The general regression fixture lives in \texttt{ci/test-template.tex}; its
build copy is \texttt{local/test-template.tex}. The manual scratch file
\texttt{local/test.tex} is neither generated nor compiled by these checks.

The first command builds the manual and the curated
\texttt{output/ctan/dfg-crc.zip}, verifies its exact allow-list, extracts it in
a clean temporary directory, runs the portable installer, and compiles a
minimal document against the resulting class.  The online target validates but
does not submit the archive.  Before committing, inspect
\texttt{git status --short}, run \texttt{git diff --check}, and review the ZIP
file list.

\subsection{Maintaining executable examples}
The driver uses |documentation=true| to keep the class typography and rendering
commands while loading its fixtures explicitly. This option defaults to false;
it suppresses automatic proposal customization, metadata, and bibliography
inputs. It is intended for this manual, not for ordinary proposals.
The fixtures and the manual driver are maintained in the DTX. A documentation
build extracts them again, so the manual needs no private proposal files.

Add runnable examples with the manual's |dfgExample| environment. Its required
argument is the title; add a stable |label={ex:manual-name}| option and refer
to it from the relevant command description with |\dfgExampleRef{ex:manual-name}|.
Add |dfg wide| to the options for full-width output
below the code. Each example executes the displayed code in a local group.
Floating output is set to non-floating inside the result panel. Use the
fictional IDs |per1|, |per2|, |ins1|, |aff1|, and |A01| where possible.
Use |dfg project=A03| on the example environment when an example needs a
current-project context, and explain that context in the surrounding text.
Keep data-only declarations, incomplete preamble fragments, full-document
project wrappers, external commands, and BibTeX records in |dispListing|.
The shared project and PI metadata are listed once with |\dfgTableSetup|
in the reference chapter; live table examples and the generated local proposal
use those same records. Maintain matching |cv-person-id| career records in the
|meta-cv| block and fictional bibliography records with |person-id-A| or
|person-id-B| keywords for every PI included in the example CV appendix.
Project-boundary examples show labelled excerpts from the standalone proposal,
because those commands change pages, headers, and bibliography scope.
Running |make doc| checks that the PDFs contain all fifteen active project
chapters, the ending-project example, and twelve PI CVs before compiling the
manual. Inspect the PDF
as well as the build log after changing a layout example.

\chapter{Complete example proposal}
\label{chap:complete-example-proposal}
The following pages show the complete fictional proposal generated from this
DTX using the same metadata as the documentation examples: twelve PIs, six
projects in area A, six in area B, and three in area Q. The title page, general
information, financial overviews, all fifteen active project descriptions, the
former project A00, bylaws, declarations, and back matter are included.
The scientific text, people, figures, and funding values are illustrative.

The proposal is built with |final=true|, which suppresses draft tags and margin
diagnostics. Each imported page is reduced to 82\% and framed, with an
\enquote{Example proposal} label above it. The proposal's own page numbers,
headers, and thumb index remain inside the frame; the manual page number appears
below it, clearly separating the two documents.
For the proposal's own clickable references and bookmarks, open the accompanying
\href{dfg-crc-proposal-example.pdf}{standalone example proposal PDF}.

To regenerate the manual and both complete examples from the DTX, run |make doc| in the template
repository. Use |make proposal-doc-example| to build only the standalone
example. Both the local proposal and the final-mode documentation build use
the same metadata and chapter inputs in |local/|. Its generated wrapper is:
\begin{dispListing}
\PassOptionsToClass{final=true}{dfg-crc}
\input{crc-proposal.tex}
\end{dispListing}

\IfFileExists{dfg-crc-proposal-example.pdf}{%
  \includepdf[pages=-,scale=0.82,frame=true,fitpaper=false,
    pagecommand={\dfgDocImportedPage{Example proposal}},
    link=true,linkname=example-proposal]{dfg-crc-proposal-example.pdf}%
}{%
  \PackageError{dfg-crc documentation}{Complete example proposal PDF missing}
    {Run make proposal-doc-example before compiling the manual.}%
}

\chapter{Complete example CV appendix}
\label{chap:complete-example-cv}
The following pages contain the complete fictional CV appendix generated from
|crc-cv.tex| and the shared consortium metadata. It includes the cover, contents,
and all twelve PI CVs. Each shows three career stages, supplementary research
information, activities, supervision, distinctions, and further information,
followed by two category-A articles, a category-B dataset, and the privacy
statement. The bibliography records
are explicitly fictional and use person-specific selection keywords such as
|per12-A| and |per12-B|. Replace them with real publications and the appropriate keywords,
as explained in Section~\ref{sec:manual-cv-publications}. See \dfgExampleRef{ex:manual-generate-the-cv-appendix-or-select-one-person}
for the code that selects all PIs or one person.

The CV sections use breakable |tcolorbox| containers. Career entries retain
their two-column appearance and can continue onto the following page; section
titles are repeated with a continuation marker. Titles, body text, publication
lists, and consent text use |\normalsize| (the nominal 11\,pt base size).

As with the proposal, the CV is built with |final=true|. Every imported page
is reduced to 82\%, framed, and labelled \enquote{Example CV appendix}; the
manual page number stays outside the frame. Open the accompanying
\href{dfg-crc-cv-example.pdf}{standalone example CV PDF} for its own clickable
references and bookmarks. Run |make cv-doc-example| to regenerate just that
PDF, or |make doc| to rebuild both examples and this manual from the DTX.

\IfFileExists{dfg-crc-cv-example.pdf}{%
  \includepdf[pages=-,scale=0.82,frame=true,fitpaper=false,
    pagecommand={\dfgDocImportedPage{Example CV appendix}},
    link=true,linkname=example-cv]{dfg-crc-cv-example.pdf}%
}{%
  \PackageError{dfg-crc documentation}{Complete example CV PDF missing}
    {Run make cv-doc-example before compiling the manual.}%
}

\part{Implementation reference}
\DocInput{\jobname.dtx}

\part{Independent LaTeX packages}
\label{part:independent-packages}
\chapter{Choose and install a package}
\label{chap:independent-packages}
\label{sec:reusable-packages}

The following packages work with standard document classes such as
\texttt{article} and \texttt{report}. They support pdfLaTeX and LuaLaTeX,
load their own TeX dependencies, and require no proposal metadata or
project-specific fonts. Load only the packages needed by your document.
The proposal class loads the same implementations and supplies adapters for
its metadata and settings; that usage is explained in
Part~\ref{part:proposal-class}.

\begin{description}
\item[\pkg{dfg-plots}] Shared plot dispatch, defaults, and float options;
  Chapter~\ref{chap:module-plots}.
\item[\pkg{dfg-collaboration}] Project connections as arc diagrams or heatmaps;
  Chapter~\ref{chap:module-collaboration}.
\item[\pkg{dfg-gantt}] Narrative workpackages, references, and quarter charts;
  Chapter~\ref{chap:module-gantt}.
\item[\pkg{dfg-timeline}] Events, date ranges, and descriptions;
  Chapter~\ref{chap:module-timeline}.
\item[\pkg{dfg-distribution}] Counts with registered categories and vector icons;
  Chapter~\ref{chap:module-distribution}.
\item[\pkg{dfg-icons}] Registered assets beside paragraphs;
  Chapter~\ref{chap:module-icons}.
\item[\pkg{dfg-bib-highlights}] Author and whole-entry bibliography emphasis;
  Chapter~\ref{chap:module-bib-highlights}.
\item[\pkg{dfg-thumbindex}] Coloured tabs on odd and even page edges;
  Chapter~\ref{chap:module-thumbindex}.
\end{description}

\section{Install and compile a complete example}
Run the portable installer to generate the class, packages, package guide,
and the complete example files shown in this part:
\begin{dispListing}
luatex dfg-crc.ins
latexmk -lualatex dfg-gantt-example.tex
\end{dispListing}
Use |latexmk -pdf| for pdfLaTeX. Bibliography highlighting also requires
Biber; latexmk runs it automatically. Keep the package files listed in each
chapter and any companion data beside the example, or install the package
files in a TeX search directory. Each example uses the standard
\texttt{article} class. The icon example uses sample graphics from the
standard \pkg{mwe} bundle; other examples need no image files.

The developer installer writes these same files into |local/module-examples|.
In the proposal repository they are in |docs/examples|. The independent
guide |dfg-modules.md| describes the public interfaces in more detail.

\section{How these examples enter the manual}
Every source listing below reads the actual example file. The rendered
result comes from compiling that file as a separate document with only the
listed module files. Its preamble, bibliography, and page settings are
independent of this manual. Sources are maintained in the DTX and extracted
by both installers; listings and compiled examples use those same files.

In the template repository, |make module-examples| builds all sixteen examples
and |make doc| also includes them in this manual. The generated helper can
be used from a portable installation:
\begin{dispListing}
python3 dfg-build-module-examples.py
\end{dispListing}
This needs Python~3, latexmk, the selected TeX engine, and Biber. If pdfcrop
and Ghostscript are available, preview PDFs have excess white margins removed.
Full PDFs are always retained; the thumbindex preview preserves its page edges.

\chapter{Shared plot infrastructure}
\label{chap:module-plots}
\pkg{dfg-plots} loads \pkg{hvfloat}. Collaboration and Gantt packages load
this shared core automatically. The example uses both, so copy
|dfg-plots.sty|, |dfg-collaboration.sty|, and |dfg-gantt.sty|.

Use |\dfgPlotSetup| to configure defaults:
\begin{itemize}
\item |plotOptions| applies to both plot types;
\item |ganttPlotOptions| applies to Gantt charts;
\item |collaborationPlotOptions| applies to collaboration plots.
\end{itemize}
Native |hvFloat| options
are forwarded after plot-specific options are consumed. Precedence is
built-in defaults, shared defaults, type defaults, then the individual call.
Changes follow TeX grouping. |caption| appends text to the automatic caption;
|caption={}| removes inherited additional text for that call.
The predefined |proposalPlots| style selects
|floatPos=!t,capPos=top,floatCapSep=8pt|.

|\dfgPlotProject{ID}| supplies the focus when an ID is omitted from
|\printPlot|. Direct |\GanttPlotFigure| and |\CollaborationPlot| commands
use the same defaults. With the proposal class loaded, these commands also
read its live shared and type-specific defaults. The direct collaboration
command uses its declared dataset; class |\printPlot| uses proposal metadata.

% BEGIN MODULE OPTIONS plots
\section{Commands}
\begin{docCommand}[doc label={module-plots-command-dfgPlotSetup}]{dfgPlotSetup}{\marg{options}}
Set shared and type-specific defaults; their precedence is described below.
\end{docCommand}
\begin{docCommand}[doc label={module-plots-command-dfgPlotProject}]{dfgPlotProject}{\marg{ID}}
Select the default focus for plots whose specification omits an ID.
\end{docCommand}
\begin{docCommand}[doc label={module-plots-command-dfgDeclarePlotType}]{dfgDeclarePlotType}{\marg{name}\marg{renderer}}
Register a plot renderer globally. It receives an optional options argument and a mandatory project ID.
\end{docCommand}
\begin{docCommand}[doc label={module-plots-command-printPlot}]{printPlot}{\oarg{options}\marg{plot specification}}
Render a registered plot type, for example \{\{gantt\}\{Study\}\}. A missing ID uses the current default focus.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Shared and type-specific setup}
Pass these keys to \texttt{\textbackslash{}dfgPlotSetup}; standalone \texttt{\textbackslash{}changeSettings} is an alias when the host has not defined it.\par
Changes follow TeX grouping.\par
Each renderer consumes its own keys and forwards remaining keys to hvFloat.
\begin{docKey}[][doc label={module-plots-0-plotOptions}]{plotOptions}{=\meta{value}}{initially \texttt{\{\}}}
Shared options for both plot types, including native float keys. Replaces the previous shared list.
Accepts Key-value list.
\end{docKey}
\begin{docKey}[][doc label={module-plots-0-ganttPlotOptions}]{ganttPlotOptions}{=\meta{value}}{initially \texttt{\{\}}}
Additional Gantt-only defaults. Overrides shared values and is overridden by the individual call.
Accepts Key-value list.
\end{docKey}
\begin{docKey}[][doc label={module-plots-0-collaborationPlotOptions}]{collaborationPlotOptions}{=\meta{value}}{initially \texttt{\{\}}}
Additional collaboration-only defaults, including layout, connection overrides, and float placement. An empty list clears earlier type defaults.
Accepts Key-value list.
\end{docKey}
\subsection{Native float options and extension commands}
Both floating plot wrappers accept native hvFloat keys in the same option list.\par
The complete backend reference is available with texdoc hvfloat.\par
This includes placement, caption position, rotation, non-floating output, and named styles; the package does not introduce a separate whitelist.
\begin{docKey}[][doc label={module-plots-1-floatPos}]{floatPos}{=\meta{value}}{initially \texttt{!hb}}
The wrapper defaults to source/bottom placement. A later style or explicit call can override it.
Accepts Native hvFloat placement value.
\end{docKey}
\begin{docKey}[][doc label={module-plots-1-capPos}]{capPos}{=\meta{value}}{initially \texttt{bottom}}
The wrapper places captions below by default; for example top changes their position.
Accepts Native hvFloat caption position.
\end{docKey}
\begin{docKey}[][doc label={module-plots-1-style}]{style}{=\meta{value}}{}
The supplied proposalPlots style sets floatPos=!t, capPos=top, floatCapSep=8pt. Native styles and remaining keys retain hvFloat semantics.
Accepts An hvFloat style name.
Initially \texttt{No named style selected}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}dfgPlotProject}\{ID\} changes the default focus in its TeX group.\par
\texttt{\textbackslash{}dfgDeclarePlotType}\{name\}\{renderer\} globally registers an exact type name; its renderer is called with [options]\{project\}.\par
Built-in type aliases are gantt/Gantt and collaboration/collaborations/ProjectCollaboration.\par
Explicit IDs override the default only for that rendering.\par
Packages other than bib-highlights have no package-load options; pass their settings to the setup/render commands.
% END MODULE OPTIONS plots

\dfgModuleListing{dfg-plots-example.tex}{Shared defaults for two plot types}{plots}
\dfgModuleResult{plots}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-plots-options-example.tex}{Shared styles and local float overrides}{plots-options}
\dfgModuleResult{plots-options}{1}
\dfgModuleResult{plots-options}{2}

\chapter{Collaboration plots}
\label{chap:module-collaboration}
Copy |dfg-collaboration.sty| and |dfg-plots.sty|. The package also loads TikZ
with its |calc| library.

Declare project IDs with |\DeclareCollaborationProject{ID}{options}|.
Options are |area|, |collaboration|, and |active|; areas default to the first
character of the ID. Connections are undirected; duplicate and self-links
are ignored. Inactive projects are excluded. Declarations follow TeX
grouping; |\clearCollaborationProjects| starts a separate dataset.

The plot option |collaboration={A01,A02}| replaces all connections incident
to the focus for that call, including incoming declarations. An empty list
means no connections. No second project list is needed. Without any declared
dataset, the focus and this explicit connection list provide a complete
ID-only dataset. The optional |show-projects={A01,A02}| restricts displayed
nodes, always including the focus. Neither option changes stored data.
The plural |collaborations| and former filter name |projects| remain aliases.

The default layout is |arc|; use |arcs=true| for connecting arcs, or
|layout=heatmap| for a heatmap. Set colours through |\CollaborationSetup|
or local |area-colors| and |area-palette| options. Unknown targets in a
declared dataset produce a diagnostic; an unknown or inactive focus is an error.

% BEGIN MODULE OPTIONS collaboration
\section{Commands}
\begin{docCommand}[doc label={module-collaboration-command-DeclareCollaborationProject}]{DeclareCollaborationProject}{\marg{ID}\marg{fields}}
Declare or replace project data in the current group.
\end{docCommand}
\begin{docCommand}[doc label={module-collaboration-command-CollaborationSetup}]{CollaborationSetup}{\marg{options}}
Set persistent area-colour defaults in the current group.
\end{docCommand}
\begin{docCommand}[doc label={module-collaboration-command-CollaborationPlot}]{CollaborationPlot}{\oarg{options}\marg{ID}}
Render the independent project registry, with optional per-call connection and display overrides.
\end{docCommand}
\begin{docCommand}[doc label={module-collaboration-command-clearCollaborationProjects}]{clearCollaborationProjects}{}
Clear the independent project registry in the current group.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Project declarations}
Options for \texttt{\textbackslash{}DeclareCollaborationProject}\{ID\}\{options\}.\par
Each declaration replaces that ID in the current TeX group.\par
IDs contain letters, digits, and hyphens and start with a letter or digit.
\begin{docKey}[][doc label={module-collaboration-0-area}]{area}{=\meta{value}}{}
Groups projects and selects their area colour; it need not match the ID prefix.
Accepts Area name.
Initially \texttt{First character of ID}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-0-collaboration}]{collaboration}{=\meta{value}}{initially \texttt{\{\}}}
Stored undirected connections. Duplicate and self-links are ignored; reverse declarations need not be repeated.
Accepts Comma-separated project IDs.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-0-collaborations}]{collaborations}{=\meta{value}}{initially \texttt{\{\}}}
Compatibility alias for the singular declaration key.
Accepts Same as collaboration.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-0-active}]{active}{\docKeyChoices{true,false}}{initially \texttt{true}}
False omits this project and incident edges from plots.
Accepts true or false.
\end{docKey}
\subsection{Area setup}
Options for \texttt{\textbackslash{}CollaborationSetup}; follow TeX grouping.\par
Per-plot area options override these defaults.\par
With the class loaded this setup also updates its area-colour settings.
\begin{docKey}[][doc label={module-collaboration-1-area-colors}]{area-colors}{=\meta{value}}{initially \texttt{\{\}}}
Explicit area colours. Local plots merge individual mappings with the setup mappings.
Accepts Area=colour pairs.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-1-area-palette}]{area-palette}{=\meta{value}}{}
Rotating fallback palette for areas without an explicit colour.
Accepts Nonempty colour list.
Initially \texttt{blue!70!black, teal!80!black, orange!85!black, violet, brown}.
\end{docKey}
\subsection{Per-plot options}
Options for \texttt{\textbackslash{}CollaborationPlot} or the collaboration type of \texttt{\textbackslash{}printPlot}.\par
Each rendering resets built-in defaults, then applies shared, type-specific, and local options.\par
Float keys also pass through to hvFloat.
\begin{docKey}[][doc label={module-collaboration-2-layout}]{layout}{=\meta{value}}{initially \texttt{arc}}
Selects the visual layout. arc-diagram is a value alias for arc.
Accepts arc, arc-diagram, or heatmap.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-arc}]{arc}{}{}
Shorthand for layout=arc.
Accepts Bare key.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-arc-diagram}]{arc-diagram}{}{}
Shorthand for layout=arc.
Accepts Bare key.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-heatmap}]{heatmap}{}{}
Shorthand for layout=heatmap.
Accepts Bare key.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-arcs}]{arcs}{\docKeyChoices{true,false}}{initially \texttt{false}}
Draws connecting arcs in the arc layout.
Accepts true or false; bare key means true.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-no-arcs}]{no-arcs}{}{}
Shorthand for arcs=false.
Accepts Bare key.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-area-colors}]{area-colors}{=\meta{value}}{}
Overrides or adds individual area colours for this rendering.
Accepts Area=colour pairs.
Initially \texttt{Setup mappings}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-area-colours}]{area-colours}{=\meta{value}}{}
British-spelling alias.
Accepts Same as area-colors.
Initially \texttt{Setup mappings}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-area-palette}]{area-palette}{=\meta{value}}{}
Replaces the fallback palette for this call. An empty per-call list leaves the palette unchanged.
Accepts Colour list.
Initially \texttt{Setup palette}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-caption}]{caption}{=\meta{value}}{initially \texttt{\{\}}}
Appends text to the automatic caption. An empty value clears inherited additional caption text.
Accepts TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-collaboration}]{collaboration}{=\meta{value}}{}
Replaces all edges incident to the focus for this rendering, including incoming edges. With no dataset, supplies the other one-off node IDs.
Accepts Comma-separated IDs; \{\} allowed.
Initially \texttt{Stored connections}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-collaborations}]{collaborations}{=\meta{value}}{}
Compatibility alias for the local connection override.
Accepts Same as collaboration.
Initially \texttt{Stored connections}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-show-projects}]{show-projects}{=\meta{value}}{}
Filters displayed nodes. The focus is always included; an empty list shows only the focus.
Accepts Comma-separated IDs; \{\} allowed.
Initially \texttt{All active projects}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-projects}]{projects}{=\meta{value}}{}
Compatibility alias for the display filter; it does not define connections.
Accepts Same as show-projects.
Initially \texttt{All active projects}.
\end{docKey}
\begin{docKey}[][doc label={module-collaboration-2-width}]{width}{=\meta{value}}{}
Requested plot width; layout measurement uses this width.
Accepts TeX dimension.
Initially \texttt{\textbackslash{}linewidth}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}CollaborationPlot}[options]\{ID\} uses the independent registry.\par
\texttt{\textbackslash{}clearCollaborationProjects} clears that registry in the current group.\par
The class adds \texttt{\textbackslash{}ProjectCollaborationPlot}, \texttt{\textbackslash{}collaborationPlot} and its plural alias; its \texttt{\textbackslash{}printPlot} reads class metadata.\par
Node IDs are not arbitrary TeX labels.\par
Edges between filtered or inactive nodes are not shown.
% END MODULE OPTIONS collaboration

\dfgModuleListing{dfg-collaboration-example.tex}{Declared data and a local connection override}{collaboration}
\dfgModuleResult{collaboration}{1}
\dfgModuleResult{collaboration}{2}


\section{Examples with different options}
\dfgModuleListing{dfg-collaboration-options-example.tex}{Colours, display filtering, and empty connections}{collaboration-options}
\dfgModuleResult{collaboration-options}{1}
\dfgModuleResult{collaboration-options}{2}

\chapter{Gantt charts and workpackages}
\label{chap:module-gantt}
Copy |dfg-gantt.sty| and |dfg-plots.sty|. Additional TeX dependencies are
\pkg{pgfgantt}, \pkg{datatool}, \pkg{enumitem}, and \pkg{etoolbox}.

Workpackages supply narrative headings and Gantt rows from one declaration.
|\GanttProject{ID}| selects their project and the default plot focus.
Grouped |title| and |gantt| fields take precedence over legacy |name|,
|description|, |periodStart|, |periodEnd|, and |style| fields.
Styles are |default|, |alternative|, |important|, |crosshatch|, and |striped|.
Nested workpackages and references need no proposal class; references require
the usual second LaTeX pass.

Set |slots|, |first-quarter|, and |year-labels| globally with |\GanttSetup|
or for one plot. The default is 16 quarters beginning in Q3. Vertical rules
after Q4 retain the year boundaries of the original class. Grid validation
runs before geometry calculations; if compilation continues after an invalid
grid error, it recovers to these defaults. Equal start/end values omit a bar;
reversed or non-integer ranges are rejected.

For chart data without narrative text, use:
\begin{dispListing}
\DeclareWorkPackage{Study}{methods}{
  gantt={start=1,end=3}}
\GanttChart[slots=8]{Study}
\end{dispListing}
The |\GanttChart| command renders only the graphic without float options.

% BEGIN MODULE OPTIONS gantt
\section{Commands}
\begin{docCommand}[doc label={module-gantt-command-GanttSetup}]{GanttSetup}{\marg{options}}
Set the quarter grid defaults in the current group.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-GanttProject}]{GanttProject}{\marg{ID}}
Select the project for narrative workpackages and the default plot focus.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-addWP}]{addWP}{\marg{ID}\marg{fields}}
Add a narrative item inside workpackages, with the same data supplying its Gantt row.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-DeclareWorkPackage}]{DeclareWorkPackage}{\marg{project}\marg{ID}\marg{fields}}
Declare a chart row without a narrative list item.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-getWP}]{getWP}{\oarg{project}\marg{IDs}}
Reference one or more narrative workpackages. The optional project replaces the current project for this call.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-GanttChart}]{GanttChart}{\oarg{options}\marg{project}}
Draw a graphic only, without the float wrapper.
\end{docCommand}
\begin{docCommand}[doc label={module-gantt-command-GanttPlotFigure}]{GanttPlotFigure}{\oarg{options}\marg{project}}
Draw a chart with automatic caption and native hvFloat options.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Narrative workpackage fields}
Fields for \texttt{\textbackslash{}addWP}\{ID\}\{fields\} and \texttt{\textbackslash{}DeclareWorkPackage}\{project\}\{ID\}\{fields\}.\par
Set a project before narrative declarations with \texttt{\textbackslash{}GanttProject}.\par
Grouped title/gantt fields take precedence over corresponding legacy fields.
\begin{docKey}[][doc label={module-gantt-0-title}]{title}{=\meta{value}}{initially \texttt{\{\}}}
Narrative heading; normalizes to name. It also supplies the chart description when no chart label/description was given.
Accepts TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-gantt}]{gantt}{=\meta{value}}{}
Sets the workpackage chart fields without entering a second dataset.
Accepts Nested label, start, end, style keys.
Initially \texttt{No grouped chart fields}.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-id}]{id}{=\meta{value}}{}
Accepted by normalization for compatibility; standalone storage uses the mandatory command ID and ignores this field. Prefer the mandatory argument.
Accepts Legacy ID field.
Initially \texttt{Mandatory command argument}.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-name}]{name}{=\meta{value}}{initially \texttt{\{\}}}
Legacy narrative heading. title overrides it.
Accepts TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-description}]{description}{=\meta{value}}{}
Legacy chart label. gantt/label overrides it.
Accepts TeX text.
Initially \texttt{\{\}; falls back to title/name in grouped syntax}.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-periodStart}]{periodStart}{=\meta{value}}{initially \texttt{1}}
Legacy first chart slot. gantt/start overrides it.
Accepts Nonnegative integer.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-periodEnd}]{periodEnd}{=\meta{value}}{initially \texttt{1}}
Legacy final chart slot. gantt/end overrides it. Equal endpoints omit the bar.
Accepts Nonnegative integer, at least start.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-0-style}]{style}{=\meta{value}}{initially \texttt{default}}
Legacy bar appearance. gantt/style overrides it.
Accepts default, alternative, important, crosshatch, striped.
\end{docKey}
\subsection{Nested gantt fields}
Use inside gantt=\{...\} in a workpackage declaration.\par
Start/end are chart-slot indices, not calendar dates.
\begin{docKey}[][doc label={module-gantt-1-label}]{label}{=\meta{value}}{}
Label printed inside the bar.
Accepts TeX text.
Initially \texttt{Workpackage title/name when present}.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-1-start}]{start}{=\meta{value}}{initially \texttt{1}}
First slot. A value greater than end is an error.
Accepts Nonnegative integer.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-1-end}]{end}{=\meta{value}}{initially \texttt{1}}
Last slot. Equal start/end values omit the bar.
Accepts Nonnegative integer.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-1-style}]{style}{=\meta{value}}{initially \texttt{default}}
Solid default/alternative/important colours, a crosshatch pattern, or alternating stripes.
Accepts default, alternative, important, crosshatch, striped.
\end{docKey}
\subsection{Grid setup and individual charts}
Use \texttt{\textbackslash{}GanttSetup} for grouped persistent defaults, \texttt{\textbackslash{}GanttChart} for a graphic, or the standalone Gantt plot wrapper for a floating graphic.\par
The standalone wrapper also consumes caption and forwards remaining float keys to hvFloat.\par
The class retains its own plot adapter.
\begin{docKey}[][doc label={module-gantt-2-slots}]{slots}{=\meta{value}}{initially \texttt{16}}
Number of quarter slots. Validated before geometry calculations.
Accepts Positive integer.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-2-first-quarter}]{first-quarter}{=\meta{value}}{initially \texttt{3}}
First quarter label. Subsequent labels cycle Q1 to Q4.
Accepts Integer 1 to 4.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-2-year-labels}]{year-labels}{=\meta{value}}{initially \texttt{\{\}}}
Successive year-group titles. Missing labels use the funding-year formatter, whose standalone default is Year followed by the group number.
Accepts Comma-separated TeX labels.
\end{docKey}
\begin{docKey}[][doc label={module-gantt-2-caption}]{caption}{=\meta{value}}{initially \texttt{\{\}}}
Appends to the automatic Gantt caption. An empty value clears inherited additional text; it is not a graphic-only GanttChart option.
Accepts TeX text; floating wrapper only.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}GanttProject}\{ID\} selects the workpackage project and generic plot focus.\par
\texttt{\textbackslash{}getWP}[project]\{IDs\} references workpackages, with the optional project replacing the current one for that call.\par
\texttt{\textbackslash{}GanttPlotFigure}[options]\{ID\} wraps a chart in hvFloat.\par
\texttt{\textbackslash{}GanttChart} and legacy \texttt{\textbackslash{}dfgGanttEnvironment} render graphics only.\par
\texttt{\textbackslash{}dfgGanttContent} renders stored rows, and \texttt{\textbackslash{}DFGGanttTitles} renders grid headings inside pgfgantt.\par
Standalone formatter hooks are \texttt{\textbackslash{}dfgFundingYear}\{number\}, \texttt{\textbackslash{}DFGGanttLabel}\{project\}\{id\}, \texttt{\textbackslash{}DFGGanttTag}\{project\}\{field\}\{text\}\{tag\}, and \texttt{\textbackslash{}dfgGanttShowQs}\{quarter\}\{slot\}.\par
The class supplies its own reference/debug formatters.\par
Gantt colours can be redefined through the xcolor names tableHeadingsBG, tableHeadingsFont, tableOuterLines, color@gantt@frame, color@gantt@default, color@gantt@alternative, color@gantt@important, color@gantt@crosshatch, color@gantt@stripe-one, color@gantt@stripe-two.
% END MODULE OPTIONS gantt

\dfgModuleListing{dfg-gantt-example.tex}{Narrative workpackages, references, and a quarter chart}{gantt}
\dfgModuleResult{gantt}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-gantt-options-example.tex}{Quarter grids and different bar styles}{gantt-options}
\dfgModuleResult{gantt-options}{1}
\dfgModuleResult{gantt-options}{2}

\chapter{Event timelines}
\label{chap:module-timeline}
Copy |dfg-timeline.sty|. It loads TikZ, \pkg{fontawesome5}, and \pkg{enumitem}.
Events can use month/day precision, date ranges, year filters, category
icons, and automatic or manual label placement. The same declarations
produce a chart and a description list or prose.

|\clearEvents| starts a new collection. Register a category with:
\begin{dispListing}
\DeclareEventCategory{conference}{Conference}{blue}{\faGlobe}
\end{dispListing}
The proposal's old |preamble/dfg-event-timeline.tex| file is a compatibility loader.

% BEGIN MODULE OPTIONS timeline
\section{Commands}
\begin{docCommand}[doc label={module-timeline-command-addEvent}]{addEvent}{\oarg{formatting}\marg{data}}
Register one dated event. Formatting can be overridden when rendering.
\end{docCommand}
\begin{docCommand}[doc label={module-timeline-command-printEventTimeline}]{printEventTimeline}{\oarg{options}}
Render the selected events as a horizontal timeline.
\end{docCommand}
\begin{docCommand}[doc label={module-timeline-command-printEventDetails}]{printEventDetails}{\oarg{options}}
Render the same event data as individual or aggregated details.
\end{docCommand}
\begin{docCommand}[doc label={module-timeline-command-DeclareEventCategory}]{DeclareEventCategory}{\marg{key}\marg{label}\marg{colour}\marg{icon}}
Register or replace a global category.
\end{docCommand}
\begin{docCommand}[doc label={module-timeline-command-clearEvents}]{clearEvents}{}
Clear event data and stored formatting, preserving categories.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Event data}
Mandatory data argument of \texttt{\textbackslash{}addEvent}[formatting]\{data\}.\par
Events and clearEvents follow TeX grouping; category registrations are global.\par
The optional formatting argument is documented separately below.
\begin{docKey}[][doc label={module-timeline-0-id}]{id}{=\meta{value}}{}
Stable key for later per-render overrides. Duplicate IDs warn and retain the first event.
Accepts Unique ID.
Initially \texttt{Automatically generated event-N}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-date}]{date}{=\meta{value}}{initially \texttt{Required}}
Point date, or beginning of a date range. Month-only dates are positioned mid-month; days and leap years are validated.
Accepts YYYY-MM or YYYY-MM-DD.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-start-date}]{start date}{=\meta{value}}{}
Alias for the start date. If both forms are given, the later assignment wins.
Accepts Same as date.
Initially \texttt{Required when date is absent}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-end-date}]{end date}{=\meta{value}}{}
End of a range, not before its beginning.
Accepts YYYY-MM or YYYY-MM-DD.
Initially \texttt{Start date}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-category}]{category}{=\meta{value}}{initially \texttt{Required}}
Selects colour, legend label, and default icon. Built-ins are retreat, progress, networking, graduate, symposium.
Accepts Registered category key.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-title}]{title}{=\meta{value}}{}
Full event title and details heading.
Accepts TeX text.
Initially \texttt{Required nonempty text}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-label}]{label}{=\meta{value}}{initially \texttt{Title}}
Short chart label when labels=label.
Accepts TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-abbreviation}]{abbreviation}{=\meta{value}}{}
Used when labels=abbreviation and a value is supplied.
Accepts TeX text.
Initially \texttt{Falls back to label/title}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-summary}]{summary}{=\meta{value}}{initially \texttt{\{\}}}
Optional second line in the chart when summary=true; also available to aggregated detail rendering.
Accepts Short TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-description}]{description}{=\meta{value}}{initially \texttt{\{\}}}
Long details text; kept separate from the chart summary.
Accepts TeX text.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-0-icon}]{icon}{=\meta{value}}{}
Overrides the category icon for this event.
Accepts TeX icon command.
Initially \texttt{Category icon}.
\end{docKey}
\subsection{Timeline rendering}
Options for \texttt{\textbackslash{}printEventTimeline}.\par
Each call resets the following defaults; changes are local to that rendering.\par
Labels occupy lanes above the axis; date labels use independent lanes below it.
\begin{docKey}[][doc label={module-timeline-1-width}]{width}{=\meta{value}}{}
Total requested width including label fitting. Insufficient width produces a diagnostic.
Accepts Positive dimension.
Initially \texttt{\textbackslash{}linewidth}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-year}]{year}{=\meta{value}}{initially \texttt{all}}
Filters to events intersecting that year; a range can intersect several years.
Accepts all or four-digit year.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-rotation}]{rotation}{=\meta{value}}{initially \texttt{30}}
Upper event-label angle.
Accepts Angle in degrees.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-rotation}]{date rotation}{=\meta{value}}{initially \texttt{auto}}
Auto follows the effective event-label angle unless independently overridden.
Accepts auto or angle in degrees.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-labels}]{labels}{=\meta{value}}{initially \texttt{label}}
Selects the event text, with the fallbacks documented above.
Accepts title, label, abbreviation.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-summary}]{summary}{\docKeyChoices{true,false}}{initially \texttt{false}}
Adds a nonempty summary below the chart label.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-icons}]{icons}{\docKeyChoices{true,false}}{initially \texttt{true}}
Displays the event icons.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-legend}]{legend}{\docKeyChoices{true,false}}{initially \texttt{true}}
Shows the categories used by the selected events.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-show-labels}]{show labels}{\docKeyChoices{true,false}}{initially \texttt{true}}
Displays upper label text; icons can remain visible independently.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-show-dates}]{show dates}{\docKeyChoices{true,false}}{initially \texttt{true}}
Displays date or date-range labels below the axis.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-label-width}]{label width}{=\meta{value}}{initially \texttt{0pt}}
Zero uses natural text width; positive values constrain/wrap label text.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-label-distance}]{label distance}{=\meta{value}}{initially \texttt{1.8mm}}
Distance from the axis to the first upper label lane.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-lane}]{lane}{=\meta{value}}{initially \texttt{auto}}
Default upper lane request. Lane numbering begins at zero; auto avoids collisions.
Accepts auto or nonnegative integer.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-lane-spacing}]{lane spacing}{=\meta{value}}{initially \texttt{auto}}
Auto uses measured upper-label height plus gap.
Accepts auto or positive dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-lane}]{date lane}{=\meta{value}}{initially \texttt{auto}}
Default date-label lane request, independent of upper lanes.
Accepts auto or nonnegative integer.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-distance}]{date distance}{=\meta{value}}{initially \texttt{1.8mm}}
Distance from the axis to the first lower date lane.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-lane-spacing}]{date lane spacing}{=\meta{value}}{initially \texttt{auto}}
Auto uses measured date-label height plus gap.
Accepts auto or positive dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-gap}]{gap}{=\meta{value}}{initially \texttt{.8mm}}
Collision/automatic-lane gap.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-font}]{font}{=\meta{value}}{}
Upper-label font.
Accepts TeX font commands.
Initially \texttt{\textbackslash{}sffamily\allowbreak\textbackslash{}fontsize\{7.4\}\{9\}\allowbreak\textbackslash{}selectfont}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-font}]{date font}{=\meta{value}}{}
Date-label font.
Accepts TeX font commands.
Initially \texttt{\textbackslash{}sffamily\allowbreak\textbackslash{}fontsize\{6.5\}\{8\}\allowbreak\textbackslash{}selectfont}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-line-color}]{line color}{=\meta{value}}{initially \texttt{EventMuted!40}}
Main timeline axis colour.
Accepts xcolor colour expression.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-line-width}]{line width}{=\meta{value}}{initially \texttt{.6pt}}
Main axis stroke.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-connector-width}]{connector width}{=\meta{value}}{initially \texttt{.35pt}}
Upper-label connector stroke.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-date-connector-width}]{date connector width}{=\meta{value}}{initially \texttt{.3pt}}
Date-label connector stroke.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-range-width}]{range width}{=\meta{value}}{initially \texttt{1.2pt}}
Date-range segment stroke.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-dot-radius}]{dot radius}{=\meta{value}}{initially \texttt{.9mm}}
Radius of event dots.
Accepts Nonnegative dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-1-events}]{events}{=\meta{value}}{initially \texttt{\{\}}}
Overrides specific registered event IDs for this rendering. These overrides take precedence over stored optional addEvent formatting.
Accepts ID=\{formatting keys\} pairs.
\end{docKey}
\subsection{Per-event formatting}
Use in the optional argument of \texttt{\textbackslash{}addEvent} or under events=\{id=\{...\}\} in \texttt{\textbackslash{}printEventTimeline}.\par
Values inherit the timeline settings unless listed otherwise.\par
Local events overrides win over stored formatting.
\begin{docKey}[][doc label={module-timeline-2-lane}]{lane}{=\meta{value}}{}
Upper-label lane for this event.
Accepts auto or nonnegative integer.
Initially \texttt{Timeline lane}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-xshift}]{xshift}{=\meta{value}}{initially \texttt{0pt}}
Horizontal upper-label shift; does not change the event date.
Accepts Signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-yshift}]{yshift}{=\meta{value}}{initially \texttt{0pt}}
Vertical upper-label shift.
Accepts Signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-rotation}]{rotation}{=\meta{value}}{}
Event label/icon angle. When show labels=false, upper icons remain upright.
Accepts Angle in degrees.
Initially \texttt{Timeline rotation}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-date-rotation}]{date rotation}{=\meta{value}}{}
Independent date-label rotation. Auto follows the effective per-event label rotation.
Accepts auto or angle.
Initially \texttt{Timeline date rotation}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-date-direction}]{date direction}{=\meta{value}}{initially \texttt{left}}
Chooses which end/digit of the date label aligns with its connector.
Accepts left or right.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-label-width}]{label width}{=\meta{value}}{}
Per-event text wrapping width.
Accepts Nonnegative dimension.
Initially \texttt{Timeline label width}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-label}]{label}{=\meta{value}}{}
Overrides the rendered short label.
Accepts TeX text.
Initially \texttt{Selected event label}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-icon}]{icon}{=\meta{value}}{}
Overrides the rendered icon.
Accepts TeX icon command.
Initially \texttt{Event/category icon}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-font}]{font}{=\meta{value}}{}
Per-event upper-label font.
Accepts TeX font commands.
Initially \texttt{Timeline upper font}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-date-lane}]{date lane}{=\meta{value}}{}
Per-event lower date lane.
Accepts auto or nonnegative integer.
Initially \texttt{Timeline date lane}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-date-xshift}]{date xshift}{=\meta{value}}{initially \texttt{0pt}}
Horizontal date-label shift.
Accepts Signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-date-yshift}]{date yshift}{=\meta{value}}{initially \texttt{0pt}}
Vertical date-label shift.
Accepts Signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-2-node-options}]{node options}{=\meta{value}}{initially \texttt{\{\}}}
Additional upper-label node styling. These are TikZ options, not timeline keys.
Accepts TikZ node options.
\end{docKey}
\subsection{Event details}
Options for \texttt{\textbackslash{}printEventDetails}.\par
Every call resets the listed defaults.\par
Aggregated rendering groups selected events by category; category override text is applied in that aggregated mode.
\begin{docKey}[][doc label={module-timeline-3-format}]{format}{=\meta{value}}{initially \texttt{list}}
Description-list layout or continuous prose.
Accepts list or prose.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-year}]{year}{=\meta{value}}{initially \texttt{all}}
Same intersection filter as the chart.
Accepts all or four-digit year.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-icons}]{icons}{\docKeyChoices{true,false}}{initially \texttt{true}}
Shows icons in detail headings/prose.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-show-dates}]{show dates}{\docKeyChoices{true,false}}{initially \texttt{true}}
Shows event dates or collected dates.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-nodate}]{nodate}{\docKeyChoices{true,false}}{initially \texttt{false}}
Inverse alias: nodate=true means show dates=false.
Accepts true or false; bare means true.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-aggregated}]{aggregated}{\docKeyChoices{true,false}}{initially \texttt{false}}
Combines events by category and common text rather than printing each event separately.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-3-categories}]{categories}{=\meta{value}}{initially \texttt{\{\}}}
Overrides aggregate category headings/descriptions; it is not a category-selection filter.
Accepts Category=\{title=...,description=...\} pairs.
\end{docKey}
\subsection{Aggregate category overrides}
Nested keys under categories=\{category=\{...\}\} for \texttt{\textbackslash{}printEventDetails}.\par
The category must already be registered.
\begin{docKey}[][doc label={module-timeline-4-title}]{title}{=\meta{value}}{}
Replaces the aggregate heading for this category.
Accepts TeX text.
Initially \texttt{Registered/generated category heading}.
\end{docKey}
\begin{docKey}[][doc label={module-timeline-4-description}]{description}{=\meta{value}}{}
Replaces the aggregate category description.
Accepts TeX text.
Initially \texttt{Automatically combined event text}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}DeclareEventCategory}\{key\}\{label\}\{colour\}\{icon\} registers or replaces a global category.\par
\texttt{\textbackslash{}EventCategoryIcon}\{key\} prints its coloured icon.\par
Built-ins are retreat (Annual retreat, EventRetreat, users), progress (Progress day, EventProgress, comments), networking (Networking, EventNetworking, handshake), graduate (Graduate school retreat, EventGraduate, graduation cap), and symposium (International symposium, EventSymposium, globe).\par
Redefine the EventRetreat, EventProgress, EventNetworking, EventGraduate, EventSymposium, EventInk, EventMuted, EventTalk, or EventMisc xcolor names to customize their colours.\par
\texttt{\textbackslash{}clearEvents} clears event data and stored formatting, preserving categories.\par
There is no persistent timeline setup command: rendering settings reset on every call.
% END MODULE OPTIONS timeline

\dfgModuleListing{dfg-timeline-example.tex}{Dates, a date range, and prose details}{timeline}
\dfgModuleResult{timeline}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-timeline-options-example.tex}{Year filters, label placement, and aggregated details}{timeline-options}
\dfgModuleResult{timeline-options}{1}
\dfgModuleResult{timeline-options}{2}

\chapter{Distribution charts}
\label{chap:module-distribution}
Copy |dfg-distribution.sty|. It loads TikZ and uses LaTeX3.
Register vector symbols with |\DeclareDistributionIcon| and categories with
|\DeclareDistributionCategory|. Category declarations provide their label,
colour, and icon. Supply counts with |\setDistribution| and render them
with |\DistributionChart|. Geometry and counts remain separate.

Counts must be nonnegative integers. Omitted registered categories become
zero. Per-chart options follow TeX grouping.

% BEGIN MODULE OPTIONS distribution
\section{Commands}
\begin{docCommand}[doc label={module-distribution-command-DeclareDistributionIcon}]{DeclareDistributionIcon}{\marg{name}\marg{TikZ code}}
Register a normalized vector icon.
\end{docCommand}
\begin{docCommand}[doc label={module-distribution-command-DeclareDistributionCategory}]{DeclareDistributionCategory}{\marg{key}\marg{label}\marg{colour}\marg{icon}}
Register a category using an existing icon.
\end{docCommand}
\begin{docCommand}[doc label={module-distribution-command-distributionSetup}]{distributionSetup}{\marg{options}}
Set geometry and row-order defaults.
\end{docCommand}
\begin{docCommand}[doc label={module-distribution-command-setDistribution}]{setDistribution}{\marg{counts}}
Replace category counts; omitted registered categories become zero.
\end{docCommand}
\begin{docCommand}[doc label={module-distribution-command-DistributionChart}]{DistributionChart}{\oarg{options}}
Render the current dataset with optional local geometry settings.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Chart geometry, labels, and order}
Use \texttt{\textbackslash{}distributionSetup} for defaults or \texttt{\textbackslash{}DistributionChart}[options] for a single grouped chart.\par
Registered categories initially are postdoc, industry, other, with cap, factory, bulb icons.\par
The additional none icon draws no symbol.
\begin{docKey}[][doc label={module-distribution-0-unit-width}]{unit width}{=\meta{value}}{initially \texttt{7.5mm}}
Width of one count segment.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-bar-height}]{bar height}{=\meta{value}}{initially \texttt{7.8mm}}
Height of each bar.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-row-spacing}]{row spacing}{=\meta{value}}{initially \texttt{10mm}}
Distance between row centres.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-x}]{label x}{=\meta{value}}{initially \texttt{-8mm}}
Horizontal icon/label anchor relative to the axis.
Accepts Signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-width}]{label width}{=\meta{value}}{initially \texttt{15mm}}
Text width of the category label.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-drop}]{label drop}{=\meta{value}}{initially \texttt{4.8mm}}
Downward text offset when label position=below.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-position}]{label position}{=\meta{value}}{initially \texttt{left}}
Category text to the left of the icon, or below it.
Accepts left or below.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-gap}]{label gap}{=\meta{value}}{initially \texttt{2mm}}
Gap between left-positioned label and icon.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-icon-radius}]{icon radius}{=\meta{value}}{initially \texttt{3.4mm}}
Radius of the category icon background.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-icon-raise}]{icon raise}{=\meta{value}}{initially \texttt{auto}}
Auto is 0pt for left labels and 2.3mm for below labels.
Accepts auto or signed dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-value-gap}]{value gap}{=\meta{value}}{initially \texttt{3mm}}
Gap from the end of a bar to its numeric count.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-axis-padding}]{axis padding}{=\meta{value}}{initially \texttt{2mm}}
Axis extension beyond the first and last bars.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-axis-width}]{axis width}{=\meta{value}}{initially \texttt{.45pt}}
Axis stroke width.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-axis-dot-radius}]{axis dot radius}{=\meta{value}}{initially \texttt{.4mm}}
Radius of the dots at the axis ends.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-separator-width}]{separator width}{=\meta{value}}{initially \texttt{.4pt}}
White strokes between count segments.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-text-color}]{text color}{=\meta{value}}{initially \texttt{DistributionText}}
Category and count text colour.
Accepts xcolor colour expression.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-axis-color}]{axis color}{=\meta{value}}{initially \texttt{DistributionAxis}}
Axis and endpoint-dot colour.
Accepts xcolor colour expression.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-label-font}]{label font}{=\meta{value}}{}
Category-label font.
Accepts TeX font commands.
Initially \texttt{\textbackslash{}sffamily\allowbreak\textbackslash{}bfseries\allowbreak\textbackslash{}fontsize\{8.8\}\{10\}\allowbreak\textbackslash{}selectfont}.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-value-font}]{value font}{=\meta{value}}{}
Numeric-count font.
Accepts TeX font commands.
Initially \texttt{\textbackslash{}sffamily\allowbreak\textbackslash{}bfseries\allowbreak\textbackslash{}fontsize\{11\}\{12\}\allowbreak\textbackslash{}selectfont}.
\end{docKey}
\begin{docKey}[][doc label={module-distribution-0-order}]{order}{=\meta{value}}{}
Selects and orders displayed rows. Unknown or repeated categories are errors.
Accepts Nonempty list of distinct registered categories.
Initially \texttt{postdoc, industry, other; new categories append}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}DeclareDistributionIcon}\{name\}\{TikZ code\} declares a normalized vector symbol; cap, factory, bulb, and none are built in.\par
\texttt{\textbackslash{}DeclareDistributionCategory}\{key\}\{label\}\{colour\}\{icon\} adds or replaces a category; its icon must exist.\par
\texttt{\textbackslash{}setDistribution}\{category=count,...\} replaces counts, treating omitted registered categories as zero.\par
Negative/non-integer counts, unknown categories, and duplicates are errors; rejected data leave the last valid counts intact.\par
\texttt{\textbackslash{}DistributionChart}[options] renders the current dataset.\par
Colour hooks are DistributionPostdoc, DistributionIndustry, DistributionOther, DistributionText, and DistributionAxis.\par
The stock geometry has no sign/range validation; use sensible positive sizes for bars and spacing.
% END MODULE OPTIONS distribution

\dfgModuleListing{dfg-distribution-example.tex}{A custom category and vector icon}{distribution}
\dfgModuleResult{distribution}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-distribution-options-example.tex}{Geometry, label placement, and row order}{distribution-options}
\dfgModuleResult{distribution-options}{1}
\dfgModuleResult{distribution-options}{2}

\chapter{Registered paragraph icons}
\label{chap:module-icons}
Copy |dfg-icons.sty|. It loads \pkg{graphicx}, \pkg{wrapstuff}, and
\pkg{etoolbox}. The example uses the TeX installation's sample images;
replace them with your own files in a real document.

|\DeclareIcon{name}{options}| registers exact names, variants, and aliases;
there is no whitelist of proposal-specific assets. A single |file| serves
both shapes; one supplied variant is the fallback for the other.
|\getIcon[options]{name1,name2}| places a group beside the following paragraph.
Graphic options are forwarded to \pkg{graphicx}.
|\IconIfRegisteredTF{name}{yes}{no}| checks registration.

Registrations are global. Redeclaring a name replaces its files and complete
alias list, removing old aliases. Names are case-sensitive and surrounding
spaces are ignored. Blank names and declarations without assets are errors.
Explicit names and aliases take precedence over automatic filename aliases.
Reusing another icon's explicit alias is an error and leaves the registry
unchanged. Ambiguous automatic aliases keep their first owner; use explicit
aliases or full registered paths to distinguish identical basenames.
Legacy shorthand names must be registered explicitly with |aliases|; a file
named |icon-logo-square.pdf| does not implicitly register |icon-logo|.

% BEGIN MODULE OPTIONS icons
\section{Commands}
\begin{docCommand}[doc label={module-icons-command-DeclareIcon}]{DeclareIcon}{\marg{name}\marg{assets}}
Globally register graphic variants and explicit aliases.
\end{docCommand}
\begin{docCommand}[doc label={module-icons-command-getIcon}]{getIcon}{\oarg{options}\marg{names}}
Place registered icons side by side next to the following paragraph.
\end{docCommand}
\begin{docCommand}[doc label={module-icons-command-IconIfRegisteredTF}]{IconIfRegisteredTF}{\marg{name}\marg{yes}\marg{no}}
Test registration of a name or alias after trimming spaces.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Icon registration}
Options for \texttt{\textbackslash{}DeclareIcon}\{name\}\{options\}.\par
Names and aliases are registered globally.\par
At least one asset is needed; redeclaration replaces the complete alias list.
\begin{docKey}[][doc label={module-icons-0-file}]{file}{=\meta{value}}{initially \texttt{\{\}}}
Default asset for both shapes unless a variant is supplied.
Accepts Graphics filename/path.
\end{docKey}
\begin{docKey}[][doc label={module-icons-0-square}]{square}{=\meta{value}}{}
Square-shape asset.
Accepts Graphics filename/path.
Initially \texttt{file or supplied vertical variant}.
\end{docKey}
\begin{docKey}[][doc label={module-icons-0-vertical}]{vertical}{=\meta{value}}{}
Portrait-shape asset.
Accepts Graphics filename/path.
Initially \texttt{file or supplied square variant}.
\end{docKey}
\begin{docKey}[][doc label={module-icons-0-aliases}]{aliases}{=\meta{value}}{initially \texttt{\{\}}}
Additional explicit names. Conflicts with another icon are errors and leave the registry unchanged. Filename, basename, and PDF-to-SVG aliases are also registered automatically, without overriding explicit names.
Accepts Comma-separated exact names.
\end{docKey}
\subsection{Paragraph icon placement}
Options for \texttt{\textbackslash{}getIcon}[options]\{comma-separated names\}.\par
All placement options reset per call.\par
Remaining options are forwarded to graphicx includegraphics for every image; see texdoc graphics for its complete backend reference.
\begin{docKey}[][doc label={module-icons-1-shape}]{shape}{=\meta{value}}{initially \texttt{square}}
Selects the registered variant, with the registration fallback rules.
Accepts square or vertical.
\end{docKey}
\begin{docKey}[][doc label={module-icons-1-square}]{square}{}{}
Shorthand for shape=square.
Accepts Bare key; no value.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-icons-1-vertical}]{vertical}{}{}
Shorthand for shape=vertical.
Accepts Bare key; no value.
Initially \texttt{Not selected separately}.
\end{docKey}
\begin{docKey}[][doc label={module-icons-1-gap}]{gap}{=\meta{value}}{initially \texttt{.6em}}
Spacing between grouped images and between the image group and paragraph text.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-icons-1-height}]{height}{=\meta{value}}{}
Reserved paragraph lines. Total image height is capital-H height plus (height-1) baselines. This computed totalheight is applied after forwarded graphicx keys.
Accepts Positive integer.
Initially \texttt{4 lines for square; 5 for vertical}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}IconIfRegisteredTF}\{name\}\{yes\}\{no\} tests a registered name or alias after trimming spaces.\par
Missing graphics files produce a warning and example-image fallback at rendering time, rather than failing registration.\par
Graphics lookup follows graphicspath and driver extension order.\par
The computed totalheight is appended after forwarded graphicx options, so it controls the final icon height; width, trim, clip, page, and angle retain graphicx semantics.
% END MODULE OPTIONS icons

\dfgModuleListing{dfg-icons-example.tex}{Own asset names and grouped paragraph icons}{icons}
\dfgModuleResult{icons}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-icons-options-example.tex}{Variants, grouped icons, and graphic options}{icons-options}
\dfgModuleResult{icons-options}{1}
\dfgModuleResult{icons-options}{2}

\chapter{Bibliography highlighting}
\label{chap:module-bib-highlights}
Copy |dfg-bib-highlights.sty| and |dfg-bib-highlights-example.bib|.
Load \pkg{biblatex} with the desired backend and style first. The package
also loads \pkg{xcolor}. The author-hash backend requires Biber.

Register names with |\addboldnames|, bracing names that contain commas.
Author emphasis matches Biber hashes. Entries carrying the selected keyword
are entirely bold. The |emphasizeAuthors| and |emphasizeEntries| switches
are independent and support local changes through |\BibHighlightSetup|.
|\resetboldnames| clears the active hash registry.
|\printHighlightedBibliography[options]{keyword}| selects a keyword for one list.
Ordinary BibLaTeX filters and styles still apply.

The generated author-names file is written beside the job by default.
Run LaTeX, Biber, then LaTeX twice, or use latexmk. Package option |noauthors|
disables the author-hash backend and keeps its registration commands as no-ops.

% BEGIN MODULE OPTIONS bib-highlights
\section{Commands}
\begin{docCommand}[doc label={module-bib-highlights-command-BibHighlightSetup}]{BibHighlightSetup}{\marg{options}}
Set independent author and entry highlighting options.
\end{docCommand}
\begin{docCommand}[doc label={module-bib-highlights-command-addboldnames}]{addboldnames}{\marg{names}}
Register selected authors; brace names containing commas.
\end{docCommand}
\begin{docCommand}[doc label={module-bib-highlights-command-resetboldnames}]{resetboldnames}{}
Clear the active author-hash registry.
\end{docCommand}
\begin{docCommand}[doc label={module-bib-highlights-command-printHighlightedBibliography}]{printHighlightedBibliography}{\oarg{bibliography options}\marg{keyword}}
Select the highlight keyword locally and forward list options to BibLaTeX. This does not filter the list by keyword.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Package loading}
Only noauthors is a load-time package option.\par
Load biblatex first to choose its backend/style.\par
Setup options below are passed to BibHighlightSetup, not to usepackage.
\begin{docKey}[][doc label={module-bib-highlights-0-noauthors}]{noauthors}{}{}
Disables creation/registration of the auxiliary author-hash bibliography. Author registration/reset commands become no-ops. Whole-entry highlighting remains available.
Accepts Bare load-time option.
Initially \texttt{Not selected: hash backend enabled}.
\end{docKey}
\subsection{Highlight setup}
Options for \texttt{\textbackslash{}BibHighlightSetup}.\par
Settings follow TeX grouping.\par
The class connects the two switches and author colour to its own live customization.
\begin{docKey}[][doc label={module-bib-highlights-1-emphasizeAuthors}]{emphasizeAuthors}{\docKeyChoices{true,false}}{initially \texttt{true}}
Turns matching-author bold/colour emphasis on or off independently of whole-entry emphasis.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-bib-highlights-1-emphasizeEntries}]{emphasizeEntries}{\docKeyChoices{true,false}}{initially \texttt{true}}
Enables bold type for entries carrying the selected keyword.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-bib-highlights-1-keyword}]{keyword}{=\meta{value}}{}
Selects entries for complete bold type. printHighlightedBibliography supplies a local keyword for one list; it does not filter out other entries.
Accepts BibLaTeX keyword.
Initially \texttt{\{\}; no whole-entry keyword selected}.
\end{docKey}
\begin{docKey}[][doc label={module-bib-highlights-1-color}]{color}{=\meta{value}}{initially \texttt{black}}
Colour of matching author names; does not recolour the entire entry.
Accepts xcolor colour expression.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}addboldnames}\{\{Family, Given\},...\} registers names through Biber hashes.\par
\texttt{\textbackslash{}resetboldnames} clears the active hash registry.\par
Declare \texttt{\textbackslash{}DFGBoldNamesFile} before loading the package to change the auxiliary .bib path; the default is \texttt{\textbackslash{}jobname}-boldAuthors.bib and its directory must exist.\par
\texttt{\textbackslash{}printHighlightedBibliography}[options]\{keyword\} uses the keyword locally and forwards all bracketed options to BibLaTeX printbibliography (see texdoc biblatex); it does not add a keyword filter.\par
Advanced adapter hooks are \texttt{\textbackslash{}DFGBibIfAuthorsTF}\{yes\}\{no\}, \texttt{\textbackslash{}DFGBibIfEntriesTF}\{yes\}\{no\}, and expandable \texttt{\textbackslash{}DFGBibNameColor}.\par
Match-name aliases must be registered explicitly with addboldnames.
% END MODULE OPTIONS bib-highlights

\dfgModuleListing{dfg-bib-highlights-example.bib}{Companion bibliography records}{bib-highlights-data}
\dfgModuleListing{dfg-bib-highlights-example.tex}{Independent author and whole-entry emphasis}{bib-highlights}
\dfgModuleResult{bib-highlights}{1}


\section{Examples with different options}
\dfgModuleListing{dfg-bib-highlights-options-example.tex}{Author colour and independent entry highlighting}{bib-highlights-options}
\dfgModuleResult{bib-highlights-options}{1}
\dfgModuleResult{bib-highlights-options}{2}

\chapter{Page-edge thumbindex}
\label{chap:module-thumbindex}
Copy |dfg-thumbindex.sty|. It loads TikZ and \pkg{scrlayer-scrpage}.
The example uses an ordinary two-sided article, with no proposal metadata.

Use |\ThumbIndexSetup| for width, colours, orientation, and slot count.
Explicit |topmargin| and |bottommargin| are physical page-edge distances;
|auto| follows the live text block. |\printThumbIndex| advances to a new
slot, |\printThumbIndexOff| removes tabs, and |\resetThumbIndex| resets the
sequence. The package handles odd/even outer edges and facing-page rotation.
The class shares these live settings through its existing customization keys.

% BEGIN MODULE OPTIONS thumbindex
\section{Commands}
\begin{docCommand}[doc label={module-thumbindex-command-ThumbIndexSetup}]{ThumbIndexSetup}{\marg{options}}
Set live tab geometry, appearance, and orientation.
\end{docCommand}
\begin{docCommand}[doc label={module-thumbindex-command-printThumbIndex}]{printThumbIndex}{\oarg{colours}\marg{label}}
Advance to the next slot and install a tab in normal and plain running heads.
\end{docCommand}
\begin{docCommand}[doc label={module-thumbindex-command-printThumbIndexOff}]{printThumbIndexOff}{}
Remove installed tab heads without resetting the slot counter.
\end{docCommand}
\begin{docCommand}[doc label={module-thumbindex-command-resetThumbIndex}]{resetThumbIndex}{}
Reset the slot counter without removing the current tab.
\end{docCommand}
\section{Complete option reference}
Defaults below describe standalone use. Boolean keys accept true or false;
a bare boolean key means true, with inverse aliases described explicitly.
\subsection{Live thumbindex setup}
Options for \texttt{\textbackslash{}ThumbIndexSetup}; follow TeX grouping and share the class live state when used with dfg-crc.\par
Defaults here describe an ordinary standalone document.\par
Activate a scrlayer-scrpage page style to use the running heads.
\begin{docKey}[][doc label={module-thumbindex-0-enabled}]{enabled}{\docKeyChoices{true,false}}{initially \texttt{true}}
Controls whether printThumbIndex installs a new tab. Turning this false does not remove a tab already installed; use printThumbIndexOff for that.
Accepts true or false.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-pattern}]{pattern}{=\meta{value}}{initially \texttt{8}}
Number of vertical slots before wrapping to the first slot.
Accepts Positive integer.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-width}]{width}{=\meta{value}}{initially \texttt{12mm}}
Nominal tab width; edge overhang is handled internally.
Accepts Dimension.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-font}]{font}{=\meta{value}}{}
Tab-label font.
Accepts TeX font commands.
Initially \texttt{\textbackslash{}sffamily\allowbreak\textbackslash{}bfseries}.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-bg}]{bg}{=\meta{value}}{initially \texttt{black}}
Default background for subsequent printThumbIndex calls.
Accepts xcolor colour expression.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-fg}]{fg}{=\meta{value}}{initially \texttt{white}}
Default tab text colour.
Accepts xcolor colour expression.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-orientation}]{orientation}{=\meta{value}}{initially \texttt{outwards}}
Inwards adds 180 degrees to the odd/even outward rotations.
Accepts outwards or inwards.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-topmargin}]{topmargin}{=\meta{value}}{initially \texttt{auto}}
Physical distance from the page top; auto follows the live text block.
Accepts auto or dimension.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-0-bottommargin}]{bottommargin}{=\meta{value}}{initially \texttt{auto}}
Physical distance from the page bottom; auto follows the live text block. The remaining height is divided into pattern equal slots.
Accepts auto or dimension.
\end{docKey}
\subsection{Individual tabs}
Options for \texttt{\textbackslash{}printThumbIndex}[options]\{label\}.\par
Each call begins from the current setup colours and installs the selected tab on subsequent normal/plain pages until another call or printThumbIndexOff.\par
A bare colour without an equals sign is background shorthand.
\begin{docKey}[][doc label={module-thumbindex-1-bg}]{bg}{=\meta{value}}{}
Background override for this tab; does not change the setup default.
Accepts xcolor colour expression.
Initially \texttt{Current setup background}.
\end{docKey}
\begin{docKey}[][doc label={module-thumbindex-1-fg}]{fg}{=\meta{value}}{}
Text-colour override for this tab; does not change the setup default.
Accepts xcolor colour expression.
Initially \texttt{Current setup foreground}.
\end{docKey}
\subsection{Command arguments and customization hooks}
\texttt{\textbackslash{}printThumbIndexOff} removes installed tab heads without resetting the slot counter.\par
\texttt{\textbackslash{}resetThumbIndex} resets the counter without removing a displayed tab.\par
Lower-level \texttt{\textbackslash{}evenpageletterthumb}\{label\} and \texttt{\textbackslash{}oddpageletterthumb}\{label\} draw the left/right edge tab.\par
Normal and plain heads are both installed by printThumbIndex.\par
Width and explicit margins are dimension inputs without additional sign validation; margins must leave room on the page.\par
Standalone defaults apply here; class defaults may differ and are read live.
% END MODULE OPTIONS thumbindex

\dfgModuleListing{dfg-thumbindex-example.tex}{Four pages with odd/even tabs and an off switch}{thumbindex}
\dfgModuleThumbResults



\section{Examples with different options}
\dfgModuleListing{dfg-thumbindex-options-example.tex}{Inward tabs, colour overrides, reset, and off}{thumbindex-options}
\dfgModuleThumbResultsFor{thumbindex-options}{1,2,3,4,5}

\appendix
\chapter{Change history}
\label{chap:change-history}
% Long historical command names need the full text width.
\begingroup
\makeatletter
\renewenvironment{theglossary}
  {\GlossaryParms\let\item\@idxitem\raggedright\ignorespaces}
  {\par}
\makeatother
\PrintChanges
\endgroup
\printbibliography
\end{document}
%</driver>
% \fi
% \chapter{Code documentation}
% \changes{0.4.0}{2026-11-24}{Resolve live-example project links to the corresponding pages of the embedded complete proposal and supply the example-only spokesperson destination.}
% \changes{0.4.0}{2026-11-24}{Give staff and funding metadata documentation distinct hyperlink labels and correct the table-colour option reference, including the real defaults.}
% \changes{0.4.0}{2026-11-24}{Rename the documented source, portable installer, and manual to dfg-crc.dtx, dfg-crc.ins, and dfg-crc.pdf; update build, CI, installation, and release references following CTAN maintainer feedback.}
% \changes{0.4.0}{2026-11-24}{Select the supported picture calc mode before loading hvfloat in the class and standalone plot package, avoiding the picture v2 disabled-package warning.}
% \changes{0.4.0}{2026-11-24}{Keep the repository README as a separate file instead of embedding it in the manual appendix.}
% \changes{0.4.0}{2026-11-24}{Preserve the vertical Q4 year-boundary rules and original PGF coordinate arithmetic in configurable Gantt grids, matching the pre-modular class.}
% \changes{0.4.0}{2026-11-24}{Widen the CV label/stage column to one quarter of the row width. Keep multiline labels from stretching detail paragraphs while reserving enough row height and preserving page breaks.}
% \changes{0.4.0}{2026-11-24}{Use the standard docCommand and docKey reference format for reusable packages; add configured examples alongside minimal examples and rebuild the complete CV appendix with breakable sections and normal-size text.}
% \changes{0.4.0}{2026-11-24}{Document every package-owned option with values, defaults, aliases, scope, and effects; check coverage against the implemented key families.}
% \changes{0.4.0}{2026-11-24}{Start the manual with proposal/CV usage, followed by the implementation reference and finally the independent package documentation. Include sixteen complete example files and their independently compiled output; export examples, companion data, and a build helper from both installers.}
% \changes{0.4.0}{2026-11-24}{Standardize the collaboration plot type, declaration key, and local override on the singular spelling; retain plural aliases and name the optional node filter show-projects.}
% \changes{0.4.0}{2026-11-24}{Share live plot defaults with direct package commands, validate Gantt grids before geometry calculations, and make icon alias replacement and conflict handling deterministic.}
% \changes{0.4.0}{2026-11-24}{Extract collaboration, Gantt/workpackages, event timelines, distributions, registered icons, bibliography highlighting, and the thumbindex as independent packages loaded by the class. Add standalone data APIs, collaboration overrides, package documentation, and installer support.}
% \changes{0.3.10}{2026-11-24}{Use the normal document font size for CV box titles, content, publication lists, and consent text.}
% \changes{0.3.10}{2026-11-23}{Add shared and type-specific plot option defaults through changeSettings, including the built-in proposalPlots hvfloat style, scoped overrides, and getValue access.}
% \changes{0.3.10}{2026-11-23}{Forward native hvfloat options from Gantt and collaboration plot calls with local default overrides, preserving plot-specific keys and caption behavior.}
% \changes{0.3.10}{2026-11-23}{Allow CRC/TRR references to wrap after the slash while preserving plain-text PDF bookmarks.}
% \changes{0.3.10}{2026-11-23}{Keep explicit spaces in the hyperref pdfborder value under expl3 syntax so link annotations have a valid zero-width border.}
% \changes{0.3.10}{2026-11-23}{Preserve legal page breaks between adjacent CV sections by retaining standard tcolorbox after-spacing and appending cvTableAfterSkip after the final box part.}
% \changes{0.3.10}{2026-11-23}{Refactor CV sections as titled breakable tcolorboxes, including career entries, optional descriptions, publication lists and privacy text. Preserve metadata and public commands, and default cvTableAfterSkip to zero for the new box layout.}
% \changes{0.3.10}{2026-11-23}{Add cvTableAfterSkip for configurable spacing after CV tables and each non-empty publication list. Evaluate relative dimensions at use, support scoped settings and a zero-space no-op, and expose the value through getValue.}
% \changes{0.3.9}{2026-11-20}{Standardize Gantt figure labels as fig:gantt-A02 in both caption variants; document references and migration from undashed labels.}
% \changes{0.3.9}{2026-11-18}{Vertically centre table headers with valign=m, including spanning staff and financial headings. Keep caller alignment overrides and update the guide and release notes.}
% \changes{0.3.9}{2026-11-14}{Use native raggedright centrally for left-aligned table cells. Size existing-staff affiliation columns to their contents and share regular abbreviation notes between existing- and requested-staff tables.}
% \changes{0.3.8}{2026-11-13}{Label project PDF bookmarks with the project number and PI surnames in metadata order, independently of visible titles and project status.}
% \changes{0.3.8}{2026-11-13}{Recommend plain metadata identity fields and document the compilation cost of presentation macros that disable indexes.}
% \changes{0.3.8}{2026-11-13}{Allow unavailable existing-instrumentation costs as n.a. without numeric parsing, use a text multiplication sign for quantities, and document the global PI-name cache fallback for macro-valued names.}
% \changes{0.3.8}{2026-11-13}{Restrict completion highlighting in the early-career roster to surname and first name cells. Keep the other column styles and PhD/MD row colours, including empty or missing defence-date handling.}
% \changes{0.3.8}{2026-11-13}{Control table alignment through halign instead of paragraph alignment in font declarations. Preserve left-aligned body defaults while honouring explicit column, row and cell settings and retaining centred project-overview headings.}
% \changes{0.3.8}{2026-11-13}{Keep early-career names left aligned, widen appointment durations and shared-instrumentation project cells, retain spacing in the abbreviated doctoral-candidate label and use the normal running-head font.}
% \changes{0.3.8}{2026-11-13}{Implement PI-specific bibliography notes in protected expl3 code, preserving literal empty-text handling, expanded token comparisons, paragraph output and alternative text colour. Correct the documentation of calls outside expl3 syntax.}
% \changes{0.3.7}{2026-11-11}{Add optional project short-title metadata and independent full/short selections for TOC, running head and project-start title. Default to full titles, fall back to name for missing or blank short titles, preserve scoped setup and metadata-free fast headers.}
% \changes{0.3.7}{2026-11-11}{Remove the hanging indent from wrapped remarks in theme main, including appended printTable notes, while preserving native note templates.}
% \changes{0.3.7}{2026-11-11}{Draw complete thumb-index tabs in the shipout background so page text and graphics can cover them, retaining first-pass positioning and page-style visibility.}
% \changes{0.3.7}{2026-11-11}{Allow FundingDirectCostsTable to continue across pages between rows. Keep its optional unnumbered heading with the first row and preserve the column formats and common table spacing.}
% \changes{0.3.7}{2026-11-11}{Reserve half of the current text height for approximate focused-mode project headers when no matching normal-build geometry is available. Keep recorded header replay unchanged and identify the larger fallback in its label and warning.}
% \changes{0.3.7}{2026-11-11}{Add per-tab bg and fg colour options to printThumbIndex. Retain the bare-colour background shorthand and reset omitted colours to configured defaults on each selection, preventing colour carry-over. Document examples, macro arguments and the changed default-reset behaviour.}
% \changes{0.3.7}{2026-11-11}{Place thumb-index tabs at shipout using frozen page-edge coordinates so they are correct in the first LuaLaTeX pass. Preserve running-head fonts, colours and page-style visibility. Document that contents, cross-references and bibliography may still require additional compilation runs.}
% \changes{0.3.7}{2026-11-11}{Fit the closing project overview to the available page height by proportionally shrinking the table only when necessary. Retain natural type size for shorter tables and the original logo size.}
% \changes{0.3.7}{2026-11-11}{Restore the original 20 mm top and 15 mm bottom margins, undoing the 5 mm translation of running heads, text and footers while preserving the text block dimensions.}
% \changes{0.3.7}{2026-11-10}{Reuse complete project-header space recorded by normal builds for focused-mode placeholders. Skip header metadata and layout work; preserve page spans, following body positions and section counters, with a marked approximate fallback and page-dimension checks. Add metadata-free geometry regression tests.}
% \changes{0.3.7}{2026-11-10}{Keep generated collaboration and Gantt plots below preceding section headings by using here-or-bottom float placement in both caption branches; avoid LaTeX promoting failed here-only placement to a top float. Add page-boundary ordering regression coverage.}
% \changes{0.3.7}{2026-11-09}{Separate work-package titles from grouped Gantt options. Retain flat-key compatibility with order-independent precedence, explicit empty labels and focused-mode support; document migration and add executable label-fallback examples and metadata regression checks.}
% \changes{0.3.6}{2026-11-09}{Cache raw ID lookups for PI and project references and prefetch project-leader table data. Retain funding-phase and surname indexes, invalidate on raw database edits, and preserve dynamic formatting and hyperlink targets. Document the automatic caches, invalidation rules and reader fallbacks.}
% \changes{0.3.5}{2026-11-06}{Preserve page-footnote text and hyperlinks inside printTable notes by saving boxed footnotes until the table has finished. Support nested research-area lists and retain normal footnote numbering without requiring a wrapper environment.}
% \changes{0.3.4}{2026-11-06}{Terminate all fixed Figures in EUR notices with a full stop so appended table notes start a new sentence.}
% \changes{0.3.4}{2026-11-06}{Document the leading TableEnv outer-specification argument and compact early-career table layout. Render the category-abbreviation reference directly from the registered class labels.}
% \changes{0.3.4}{2026-11-06}{Add a per-call note option to printTable. Render it in the final tabularray footer, append to existing notes, support unbreakable tables and formatted paragraphs, and preserve target options and empty-note behavior.}
% \changes{0.3.4}{2026-11-06}{Bold the entire early-career researcher row when dateDefense is nonempty, preserving topic italics and row colours. Keep former-project references unannotated in this roster and support legacy databases without a dateDefense column.}
% \changes{0.3.4}{2026-11-06}{Print staff-roster legends in normal weight as abbreviation: full institution name (parent-affiliation abbreviation), followed after a semicolon by the used affiliation abbreviations and full names. Keep comma-separated first-use order, deduplication, and legacy affiliation-only references.}
% \changes{0.3.3}{2026-11-06}{Print each staff-roster institution legend entry directly as abbreviation: full institution name (full parent affiliation name). Omit the redundant separate affiliation list while retaining entries for affiliation-only legacy rows.}
% \changes{0.3.3}{2026-11-06}{Use the selected category label for a staff-roster position line when no positionText is supplied or inherited. Preserve custom position text verbatim and keep explicit empty roster overrides hidden.}
% \changes{0.3.3}{2026-11-06}{Add the categoryAbbreviations customization setting for compact English personnel category labels in commands, funding tables, staff rosters, and CV category fallbacks. Preserve full names by default, custom category fallbacks, metadata validation, and local settings scope.}
% \changes{0.3.3}{2026-11-06}{Allow requested non-research staff, as well as existing non-research staff, to omit their field of research. Keep the cell grey and empty without a warning or missing-value placeholder; retain supplied values and validation for research staff.}
% \changes{0.3.3}{2026-11-06}{Unify long-table and direct-cost-block spacing using the normal subsection-to-text gap derived from the final fonts and paragraph spacing, with explicit length overrides. Preserve that gap when a heading moves to the next page with its table; keep continuation tables aligned at the page top.}
% \changes{0.3.2}{2026-11-05}{Use the same contact-card raster for one and several project leaders, with one full-width column for a single PI and two columns otherwise, so the gap below the project-leader heading is consistent.}
% \changes{0.3.2}{2026-11-05}{Make the paragraph gap immediately after displayed headings rigid while preserving elastic gaps between ordinary paragraphs. Replace the table dispatcher's empty-box anchor with a zero-size rule to avoid added interline space. Match the requested-funding staff roster's leading gap to ordinary uncaptioned tables when it follows a heading.}
% \changes{0.3.2}{2026-11-04}{Allow paragraph breaks in the mandatory content argument of dfgBox and document its complete command signature.}
% \changes{0.3.2}{2026-11-04}{Match the research-area legend to project tables by including non-ending research and service projects. Rebuild the formatted list for each call so exclusions do not retain codes from earlier calls. Widen the research-area column to 15 mm so its heading fits, allow 2.5 mm for the project status marker, and keep the codes centered as text without a row-level ragged-right override.}
% \changes{0.3.2}{2026-11-04}{Add configurable laboratory-animal types, grouping by registered type IDs, dynamic represented-group and grand totals, direct count and selectable cost queries, explicit missing-value diagnostics, and backward-compatible housing rates and table database arguments.}
% \changes{0.3.2}{2026-11-03}{Accept optional project setup code on printProject Head and printProjectHead. Apply local settings before the header and retain them until the matching unified or legacy Tail. Ending projects default to author emphasis instead of whole-entry emphasis, with explicit setup taking precedence. Author highlighting can be enabled and disabled during rendering.}
% \changes{0.3.2}{2026-11-03}{Add the journalTitle setting to choose full journaltitle or standard shortjournal data in bibliographies and full citations, with full-title fallback and local scope.}
% \changes{0.3.2}{2026-11-03}{Use the nominal 11 pt base size and Arimo as the default main and sansserif families; set subsection and subsubsection headings to 11 pt. Document the remaining explicit Roboto face overrides and how to clear them.}
% \changes{0.3.2}{2026-11-03}{Widen the default text block to 165 mm by using a 20 mm nominal inner margin plus the existing 5 mm binding correction. Set the footer distance to 12 mm, yielding a 250 mm text height, and use a 3.5 pt paragraph gap with 1 pt stretch and 0.5 pt shrink. Document the dimensions and customization order.}
% \changes{0.3.2}{2026-11-03}{Retain linked open-access symbols while suppressing the DOI API backend's additional open-access text and URL.}
% \changes{0.3.2}{2026-11-03}{Rebalance the gender and doctorate columns of the project-leader overview. Compact the contract and legal-issue lists in project heads, retaining conditional follow-up answers.}
% \changes{0.3.2}{2026-10-23}{Omit academic degrees from research and non-research staff job-description lead-ins while retaining them in the staff roster above.}
% \changes{0.3.2}{2026-10-23}{Restore the conditional contract dates and funding sources for project leaders by keeping internal answers consistent with the yes/no follow-up conditions.}
% \changes{0.3.1}{2026-10-20}{Move the license notice to the source header and use LaTeX-generated change history instead of separate generated Markdown files.}
% \changes{0.3.1}{2026-10-20}{Preserve CRC/TRR numbers and titles in PDF bookmarks, including starred references and optional titles, without hyperref PDF-string warnings. Use plain-text spacing in the PDF author metadata.}
% \changes{0.3.1}{2026-10-20}{Fix the missing space after command names in the deprecation warnings for \texttt{\textbackslash{}getPIProject} and \texttt{\textbackslash{}getProjectPI}.}
% \changes{0.3.0}{2026-10-20}{Add first-funding-period numbers and percentages, including gender breakdowns and totals, to the project-leader equality table in section 1.4.2 B, only for third-funding-period proposals. Document commands for the table values and keep the statistics cache consistent across grouped calls.}
% \changes{0.3.0}{2026-10-20}{Default to the DFG female-only project-leader overview, including third-period status-quo counts and percentages. Use \texttt{\textbackslash{}printTable[all-sexes]\{GenderEqualityProjectLeaders\}} for f/m/d figures in all three periods, alongside the objective columns. Display options apply to one table, with options before the table name.}
% \changes{0.2.18}{2026-10-20}{Update all seven standard salary defaults to the DFG personnel rates for 2027, with matching documentation, template comments, and default checks.}
% \changes{0.2.18}{2026-10-20}{Add expandable \texttt{\textbackslash{}getValue\{key\}} access to all customization settings, including live numeric rates, text, booleans, dimensions, and mode-specific bibliography aliases. Document formatting, local scope, and unknown-key errors; add regression coverage for all 72 settings.}
% \changes{0.2.18}{2026-10-20}{Sort the existing-instrumentation table by project ID, including alternate databases, while retaining shared equipment as a single row.}
% \changes{0.2.17}{2026-10-16}{Add \texttt{\textbackslash{}printFrameBibliography} for chapter 1 references. With \texttt{emphasizeEntries!=true}, entries tagged \texttt{frametext-highlight} are bold; project highlights remain independent and the normal bibliography font size is preserved. Update the starter chapter and document the keyword.}
% \changes{0.2.16}{2026-10-15}{Let \texttt{aims[label!=\{RDM Aims\}]} set the numbered item prefix and the name used by \texttt{\textbackslash{}cref}, \texttt{\textbackslash{}Cref}, and \texttt{\textbackslash{}getAim}, independently for each list.}
% \changes{0.2.16}{2026-10-15}{Keep custom aim labels compatible with expl3 releases that do not provide the \texttt{\textbackslash{}str\_mdfive\_hash:V} variant.}
% \changes{0.2.15}{2026-10-15}{Keep project references inside \texttt{\textbackslash{}getPIWithProject} and the legacy \texttt{\textbackslash{}getPIProject} compact, so PI names are not repeated inside the project list. Starred forms still include first names, independently of \texttt{projectPIOncePerSection}.}
% \changes{0.2.14}{2026-10-11}{Make validation warnings identify the rejected item, accepted values or required format, and whether the value is ignored, retained, or replaced. Fix funding-period and institution-order diagnostics and the animal-species choice list; require complete staff-funding category names.}
% \changes{0.2.13}{2026-10-09}{Ignore surrounding spaces in research-area codes when processing project headings, overview tables, and individual research-area lookups.}
% \changes{0.2.13}{2026-10-09}{Keep the generated class header and footer filename as \texttt{dfg-crc.cls} in both development and release extraction, independent of the output directory.}
% \changes{0.2.12}{2026-10-08}{Emit each legacy PI/project command's deprecation warning only once per LaTeX run, including repeated calls inside groups and lowercase aliases. Calls through the replacement commands remain warning-free.}
% \changes{0.2.12}{2026-10-08}{Use \texttt{\textbackslash{}frontmatter} for Roman-numbered preliminary pages and \texttt{\textbackslash{}mainmatter} before Chapter 1 to restart Arabic page numbering at 1. Existing proposal drivers need the same update because template update targets preserve them.}
% \changes{0.2.12}{2026-10-08}{Narrow the first column of \texttt{OverviewExistingStaff} from \texttt{X[4,l]} to \texttt{X[3,l]}, retaining equal-width institution columns. Break the junior research group leader label before "leaders". Maintain this in the DTX class source rather than a proposal customization override.}
% \changes{0.2.12}{2026-10-08}{Add the proposal workspace's standalone \texttt{test-overview-staff.tex} layout test: 85 complete fictional staff records, seven categories, and nine real affiliations. It uses an isolated database, documents a two-pass LuaLaTeX build, and has been checked in the rendered PDF.}
% \changes{0.2.11}{2026-10-07}{Add lowercase aliases for PI and project commands, including \texttt{\textbackslash{}getpiwithproject}, \texttt{\textbackslash{}getprojectwithpi}, and \texttt{\textbackslash{}getpiofproject}, preserving starred forms, optional arguments, formatting, links, and legacy warnings.}
% \changes{0.2.11}{2026-10-07}{Accept the mixed spellings \texttt{\textbackslash{}getPIwithProject}, \texttt{\textbackslash{}getProjectwithPI}, and \texttt{\textbackslash{}getPIOfProject} alongside the canonical command names.}
% \changes{0.2.11}{2026-10-07}{Prevent tables printed immediately after headings from overlapping them at natural page breaks; \texttt{\textbackslash{}printTable} adds a guarded \texttt{\textbackslash{}null\textbackslash{}nobreak}.}
% \changes{0.2.10}{2026-10-02}{Show field-name placeholders for missing staff metadata in fast compilation, and render fast database and project references as red typewriter placeholders such as \textless{}person-id\textgreater{}.}
% \changes{0.2.10}{2026-10-02}{Add the opt-in fastcompile-show-tags option. When enabled, fast reference annotations identify the source row and requested lookup path, including project-number lookups.}
% \changes{0.2.10}{2026-10-02}{Add ID-oriented person-first and project-first PI references; warn when the older getPIProject and getProjectPI commands are used.}
% \changes{0.2.10}{2026-10-02}{Let PIReferenceFirstName make unstarred getPI, person-first PI/project references, and getPIofProject include first names. Project-first references continue to use last names unless starred.}
% \changes{0.2.8}{2026-10-02}{Let an explicit empty \texttt{positionText} in a \texttt{RequestedFundingStaff} row suppress the person's prefilled position; omitted values still inherit it.}
% \changes{0.2.7}{2026-09-27}{Allow \texttt{color@reference@PI!=current} to inherit the surrounding text color in PI references; named colors and the black default remain supported.}
% \changes{0.2.7}{2026-09-27}{Document the customization hook for footnote-sized bibliographies with \texttt{\textbackslash{}bibitemsep!=0pt}, explaining inherited entry spacing and the separate compact CV publication list.}
% \changes{0.2.7}{2026-09-27}{Move thumb-index labels 2 mm towards the text block on both page sides, preserving tab dimensions and placement for either label orientation.}
% \changes{0.2.7}{2026-09-27}{Explicitly center project identifiers vertically in the project overview.}
% \changes{0.2.7}{2026-09-27}{Embed the second Gantt stripe colour in the PDF pattern so macOS viewers render it correctly; retain per-chart palette changes and stripe geometry.}
% \changes{0.2.7}{2026-09-27}{Add one baseline of space above section, subsection, and subsubsection headings; continue body text on the next line without an extra blank line. Document the existing paragraph breaks before and after \texttt{\textbackslash{}printTable}.}
% \changes{0.2.7}{2026-09-27}{Add \texttt{thumbindex@orientation!=outwards\textbar{}inwards} to \texttt{\textbackslash{}changeSettings}. Keep outward-facing labels by default; inward-facing labels turn 180 degrees on both left and right pages without changing tab placement.}
% \changes{0.2.6}{2026-09-18}{Expand all twelve example CVs with three career stages, all five optional sections, two fictional category-A articles, and a category-B dataset each. Rebuild the standalone CV appendix and its framed inclusion in the manual.}
% \changes{0.2.6}{2026-09-18}{Link each name printed by \texttt{\textbackslash{}getPIofProject} (including its starred form) to the PI table, using the same target and reference styling as \texttt{\textbackslash{}getPI}.}
% \changes{0.2.6}{2026-09-18}{Add \texttt{\textbackslash{}getPIofProject*} for full PI names joined with commas and a final “and”; explicit properties and a custom final separator remain supported.}
% \changes{0.2.6}{2026-09-18}{Use one shared consortium dataset for the local proposal, local CV appendix, and manual: twelve PIs, six A projects, six B projects, and three Q projects. Generate individual project files and career/optional CV records for every PI, with explicitly fictional publication examples selected by person keywords.}
% \changes{0.2.6}{2026-09-18}{Add rendered Gantt examples for all five bar styles, a custom colour palette, and grayscale fills/patterns. Explain preamble-wide colour settings versus grouped changes for a single chart, with links from the relevant descriptions.}
% \changes{0.2.6}{2026-09-18}{Build the embedded proposal from the manual's shared project and PI metadata: six A projects, six B projects, three Q projects, and twelve PIs. Include every active project chapter and use former project A00 for the ending-project example, keeping B02 new as declared in the documentation.}
% \changes{0.2.6}{2026-09-18}{Embed the complete final-mode CV appendix beside the proposal example and distribute its standalone PDF through the documentation build, CTAN archive, CI artifacts, and \texttt{update-all}. Frame and label every imported CV page.}
% \changes{0.2.6}{2026-09-18}{Add stable labels to rendered example boxes and clickable example references to command and environment descriptions, including the CV entry points.}
% \changes{0.2.6}{2026-09-18}{Make \texttt{dfgLocation}, \texttt{dfgDate}, \texttt{dfgTitle}, and \texttt{InfoTeX} available before customization is loaded and configurable through \texttt{\textbackslash{}changeSettings}. Preserve pre-class definitions and direct redefinitions; replace the fixed submission date with the generic \texttt{\textbackslash{}providecommand\{\textbackslash{}dfgDate\}\{\textless{}date\textgreater{}\textbackslash{}xspace\}}.}
% \changes{0.2.6}{2026-09-18}{Reorganize the manual into shared commands, a proposal-order walkthrough, and a separate metadata/configuration reference. Introduce record creation, lookup, reference traversal, and dispatcher syntax before specialised output.}
% \changes{0.2.6}{2026-09-18}{Consolidate repeated galleries and shared PI/project metadata; keep rendered examples beside their explanations and retain all built-in table/list/plot targets. Explain new, continuing, ending, and reference-only projects and distinguish status from service, training, and administration project types.}
% \changes{0.2.5}{2026-09-17}{Include the complete fictional starter proposal as a chapter in the manual and distribute its standalone PDF. Show imported pages at 82\% size inside a frame, with a separate-document label and the manual page number outside. Generate its final-mode wrapper from the DTX; \texttt{make doc} builds the proposal before importing every page.}
% \changes{0.2.5}{2026-09-17}{Complete the rendered gallery for all built-in table, list, and plot targets, including female-researcher objectives, project-leader participation, all finance overviews, animal upkeep, filtered research areas, and plot aliases. Group examples in proposal order and show the input records for each new table.}
% \changes{0.2.5}{2026-09-17}{Restore page breaking for wide example boxes after disabling side-by-side layout; allow long input listings and table results to continue across pages.}
% \changes{0.2.5}{2026-09-17}{Expand the complete A06 funding example to all five funding groups: staff, direct costs, fellowships, global funds, and instrumentation. Show annual amounts and a one-off equipment purchase, with combined yearly totals.}
% \changes{0.2.5}{2026-09-17}{Add six complete funding/personnel examples: existing and requested equipment, doctoral candidates, named staff and vacancies, annual staff quantities, and existing direct-cost funding. Show every input record and explain units, ongoing/completed doctorates, and the custom-database table option.}
% \changes{0.2.5}{2026-09-17}{Add practical live examples for branching metadata lookups, person statistics, staff counts, nested and cross-project references, contact cards, bibliographies, research areas, applicant wording, rules, and signatures. Show the funding records and the salary setting in the requested-funding example. Extract the complete input records for project and PI table examples from the same DTX fixtures. Render table results outside their code boxes. Demonstrate the project-status legend, automatic funding-period wording, and research-area list with its DFG classification footnote.}
% \changes{0.2.5}{2026-09-17}{Expand the independent manual fixtures to six active A projects, six B projects, three Q projects, twelve PIs, six institutions, and four affiliations. Include continuing/new research, service, training, administration, and a former-project reference. Add live examples throughout the command reference, including PI/project links, project counts, names, institution options, role cards, metadata retrieval, and project/PI overview tables.}
% \changes{0.2.5}{2026-09-17}{Demonstrate explicit and current-project collaboration/Gantt plots, layout aliases, connecting arcs, captions, and area colours. Add live \texttt{TableEnv} column/row options, aim/work-package references, signatures, figures, and publication results. Give repeated plot examples unique figure labels.}
% \changes{0.2.5}{2026-09-17}{Nest individual generated-file descriptions beneath a shared implementation section, including the customization file and the documentation fixtures.}
% \changes{0.2.5}{2026-09-17}{Typeset the manual with \texttt{dfg-crc} itself and add executable code/result examples for metadata lookups, references, lists, contact cards, boxes, tables, and collaboration plots. Use stacked output for wide examples.}
% \changes{0.2.5}{2026-09-17}{Add opt-in \texttt{documentation!=true} to load manual fixtures explicitly, without importing proposal customizations, metadata, or default bibliography files. Generate all documentation fixtures from the DTX.}
% \changes{0.2.4}{2026-09-17}{Add \texttt{\textbackslash{}get[database]\{id\}\{relation\}\{field\}} for generic \texttt{ref-\textless{}database\textgreater{}-id} traversal, including multi-step paths, multiple IDs, destination deduplication, explicit reference-key spellings, and direct/starred lookup compatibility. Keep final-value formatting and destination \texttt{showtags} annotations. Preserve stored ID order, separate results with commas, and warn without emitting dangling separators when a branch cannot be resolved.}
% \changes{0.2.4}{2026-09-17}{Retain database keyset information when focused builds skip metadata rows, so shorthand reference paths are consumed correctly for custom databases too.}
% \changes{0.2.4}{2026-09-17}{Add 33 reference-lookup regression cases to \texttt{make check}, including custom keysets, multiple IDs, shared destinations, finite cyclic paths, missing data, direct/starred compatibility, and focused-build placeholders. Check rendered separators and duplicate removal in the PDF when Poppler is available.}
% \changes{0.2.3}{2026-09-17}{Add flowing, balanced participating-institution columns with \texttt{columns!=2}, \texttt{columns!=3}, etc., and configurable \texttt{column sep} (12 pt by default). Keep each affiliation and its institutions together, without equal-height row padding. Retain \texttt{raster columns} for aligned rows and reset layout and sorting options for each call.}
% \changes{0.2.3}{2026-09-17}{Start flowing institution lists with a paragraph break and a medium vertical skip. Remove the extra 7 pt gap between an affiliation heading and its institutions; retain 10 pt between affiliation groups.}
% \changes{0.2.3}{2026-09-17}{Recognize parent and nested work packages together in \texttt{\textbackslash{}getWP}, preserving hierarchical sorting and range boundaries, including lists such as \texttt{\textbackslash{}getWP\{wp1a,wp1b,wp2,wp3a,wp3b\}}.}
% \changes{0.2.3}{2026-09-17}{Include project-local existing direct costs in focused fast-build totals, instead of displaying zero; retain accumulation across multiple funding rows.}
% \changes{0.2.3}{2026-09-17}{Default \texttt{biblatexstyleFeatureProposal} to empty, so changing bibliography styles does not implicitly pass the unsupported \texttt{dashed!=false} option.}
% \changes{0.2.3}{2026-09-17}{Prevent tables from overlapping preceding text by ending paragraphs before \texttt{\textbackslash{}printTable}, using a shared 6 pt gap, and removing negative spacing from \texttt{TableEnv} and its captions.}
% \changes{0.2.3}{2026-09-17}{Reserve \texttt{local/test.tex} for manual experiments. Maintain the general regression document in \texttt{ci/test-template.tex} and compile its copy as \texttt{local/test-template.tex}; extraction and automated checks leave the manual file untouched.}
% \changes{0.2.3}{2026-09-17}{Add 30 command-option checks and 10 participating-institution layout cases to the DTX and \texttt{make check}, covering defaults, empty/leading/legacy options, precedence, grouped names, arguments, databases, boolean flags, PI rasters, column widths and gaps, spacing, sorting, filtering, and duplicate removal. Extend funding and work-package regressions for the corrected cases and retain the new test logs and PDFs as CI artifacts.}
% \changes{0.2.3}{2026-09-17}{Install Poppler utilities for CTAN checks and report missing PDF-inspection tools before running the installation test. Refine ChkTeX suppressions for expl3 bracket parsing and TikZ coordinate syntax.}
% \changes{0.2.2}{2026-09-17}{print fast-compilation project identifiers in bold black while retaining error colours add a 7 pt gap below affiliation headings in participating-institution boxes standardize leading options for lists and role-based PI rasters, combining sorting, formatting, database selection, and layout before the main argument while retaining compatible trailing options and grouped list names add configurable raster columns and spacing to participating-institution lists, with one affiliation per cell and compatible count/alphabetical sorting}
% \changes{0.2.1}{2026-09-17}{align PI-box titles ragged right and reserve the tallest title's height throughout each raster, keeping the contact information aligned after wrapping increase the default column gap to 12 pt in both PI rasters allow a line break between phone and email while keeping each contact intact and retaining the one-em gap when both fit on the same line print affiliation names in bold in \texttt{\textbackslash{}printList\{ParticipatingInstitutions\}}}
% \changes{0.2.0}{2026-09-14}{typeset fenced README code in the PDF manual with a monospaced verbatim font align the default thumb-index stack with the current text block, dividing \texttt{\textbackslash{}textheight} into equal tabs while retaining explicit page-edge margin settings print person-specific institutions through \texttt{\textbackslash{}printList\{\{Institutions\}\{id\}\}} throughout the class and examples, retaining \texttt{\textbackslash{}dfgInstitutionList} as an alias show \texttt{\textbackslash{}printPlot} as the Gantt command in the manual and clarify the distinct thumb-index show, hide, and reset operations accept lowercase plot types with or without a project ID, including \texttt{\textbackslash{}printPlot\{\{gantt\}\{B06\}\}} and \texttt{\textbackslash{}printPlot\{\{collaborations\}\{B06\}\}} open the user documentation with an overview of the proposal template and move log-message guidance into troubleshooting keep the changelog as a separate generated file instead of including it in the documentation PDF}
% \changes{0.1.8}{2026-09-14}{bold entire project bibliography entries tagged \texttt{\textless{}project-id\textgreater{}-highlight} when \texttt{emphasizeEntries} is enabled, without affecting other project lists document that one highlight keyword per distinct project is enough even when several PIs from that project coauthor an entry align numbered section and subsection titles in a shared 12 mm number column increase the default text height by 5 mm with 20 mm top and 15 mm bottom margins, without changing the inner binding or outer note margins separate each staff member's name from the job description with a normal space move the text block 5 mm toward the binding by using 25 mm inner and 20 mm outer margins without changing its width or the binding correction remove the trailing blank Gantt row and leave a very small gap before its bottom rule}
% \changes{0.1.7}{2026-09-14}{place collaboration-plot captions below the image with or without optional caption text, matching the Gantt-chart caption layout}
% \changes{0.1.6}{2026-09-14}{reserve binding space with the configurable \texttt{BCOR} option (5 mm by default), while keeping a 160 mm text block and fitting notes into the narrower outer margin give thumb-index tabs regular rounded corners and rotated labels that fit the outer marginal column on both sides of a two-sided page separate the \texttt{WP} or \texttt{WPs} prefix from work-package numbers with a narrow, unbreakable space while retaining sorted and compressed references remove project-area letters below collaboration-plot nodes and show connecting arcs only when \texttt{arcs!=true} is requested; align wide plots with the text edge on both sides of a spread omit empty staff positions without warnings, placeholders, or extra lines; align numbered staff descriptions with a hanging indent tighten heading, caption, project-header, legal-issue, PI-card, bibliography, and aims-box typography and spacing reduce the shared gap above generated tables to 4 pt and match dashed Gantt vertical grid lines to the horizontal rule colour place Gantt captions below the chart whether or not additional caption text is supplied, keeping the default \texttt{Fig.} label visible abbreviate English figure caption labels to \texttt{Fig.} keep direct-cost table headings with their tables at page boundaries use the footnote-sized project bibliography wrapper for project reports and published-result lists}
% \changes{0.1.5}{2026-09-07}{apply the default table font size at theme scope so cell-local declarations such as \texttt{font!=\textbackslash{}bfseries} retain \texttt{\textbackslash{}footnotesize}, while explicit size declarations remain available as overrides document the table-font inheritance and override behaviour}
% \changes{0.1.4}{2026-09-04}{add \texttt{make update-all} to rebuild and copy both the generated class and manual PDF into a separately controlled proposal worktree allow existing non-research staff to omit \texttt{field-of-research} without a warning or a missing-value placeholder, and grey out the empty cell as not applicable keep the \texttt{to} connector in compact \texttt{\textbackslash{}getWP} ranges at normal font weight and retain references to nested work packages under later parent work packages, with focused regression coverage warn when a \texttt{RequestedFundingStaff} row omits both \texttt{ref-person-id} and \texttt{ref-institution-id}, because its institution cannot otherwise be resolved render staff job descriptions as itemized lists with consistent indentation make the generic \texttt{TableEnv} options argument genuinely optional by defaulting it to an empty option list make \texttt{ProjectLeadersTable} follow \texttt{projectsTableInstitutionAbbreviations} when choosing full institution names or abbreviations, with regression coverage increase the default vertical spacing between and after rows of PI boxes printed by \texttt{\textbackslash{}getPIsWithRole}}
% \changes{0.1.3}{2026-08-07}{allow generated plots in focused project builds when \texttt{fastcompile-project-show-images!=true}, retaining the project metadata they need make the collaboration arc diagram the default project-collaboration plot, with an \texttt{arcs!=false}/\texttt{no-arcs} option and explicit heatmap selection add the unified \texttt{\textbackslash{}printProject} command for project heads and tails while retaining the original commands as compatibility interfaces give PI, work-package, and aim references independent configurable colours format generic table body text consistently at footnote size, including table-cell content that overrides theme row settings correct collaboration-plot colour propagation, width and node placement, and support suppressing connecting arcs without suppressing project nodes document singular/plural-sensitive contract-question wording and avoid a documentation-driver list-label dimension overflow}
% \changes{0.1.2}{2026-08-03}{default \texttt{\textbackslash{}ProjectsTable} to full institution names and refine the optional abbreviation mode with small, table-local, alphabetically sorted legends containing only the institutions used in each table warn when one institution abbreviation denotes different institution names, and retain the corrected non-empty legend check treat \texttt{id} as a database-local unique key: a later \texttt{\textbackslash{}addEntry} with the same identifier warns, removes every earlier matching row, and becomes the stored entry tighten the former-project legend spacing, vertically center project identifiers, and add release regressions for the new defaults and duplicate-ID replacement}
% \changes{0.1.1}{2026-08-03}{add the \texttt{projectsTableInstitutionAbbreviations} setting to choose compact institution abbreviations with a full-name legend or full institution names without a legend in \texttt{ProjectsTable} make \texttt{resetThumbIndex} public so manually separated document parts can restart the thumb-index sequence document the new ProjectsTable display setting, the public thumb-index reset command, and the post-0.1.0 CTAN update procedure}
% \changes{0.1.0}{2026-08-03}{harden dynamic collaboration plots and project-area counts, preserve deterministic row and edge order, keep inactive nodes white, and add configurable colors for arbitrary project areas suppress redundant zero decimal parts in numeric and EUR output while preserving explicitly fractional values populate the section 2.1.1 direct-cost overview from project-local existing-funds declarations, classify applicant affiliations from the CRC metadata, present aggregated monetary table values as full integer euros with the note “Figures in EUR”, retain informational existing-instrumentation costs as “Figures in thousands”, and preserve decimals for those costs and explicit animal-housing rates restore siunitx model alignment in guarded tagged numeric columns and use compact slash-separated project references inside table cells while retaining natural-language joins in prose prepare the first CTAN release with a portable installer, synchronized release metadata, explicit LPPL 1.3c licensing, reproducible archive and clean-install checks, and CI release artifacts}
% \changes{0.0.53}{2026-08-02}{generate collaboration heatmap and arc-diagram rows dynamically from project areas, support optional project-area metadata with ID-prefix fallback, cycle colors for additional areas, and document the resulting behavior}
% \changes{0.0.52}{2026-08-02}{release the complete project-template, funding-calculation, TOC, and converter updates, including half-year staff-cost calculation, compact project TOC numbers, complete active-project examples, and focused regression coverage}
% \changes{0.0.51}{2026-08-02}{generate a self-contained project-collaboration regression file from the DTX, extend the dummy proposal metadata with explicit collaboration, list, ending, and reference-only cases, show both collaboration plot calls in the dummy project chapter, and document the collaboration metadata relationship and dispatcher syntax keep project numbers compact in the table of contents so section titles retain their normal indentation apply half-year factors to automatically calculated staff costs in years 1 and 5, test the resulting four-year salary total across five funding columns, and show both automatic and explicit staff-cost entries in every active generated project example and converted project template}
% \changes{0.0.50}{2026-08-02}{add compact project-collaboration heatmaps and equal-peak arc diagrams with labeled nodes, tight project-area rules, ending/reference-only filtering, and hvFloat captions, a common plot dispatcher for collaboration and Gantt graphics, mirrored marginal leaders, and safe expansion of funding-source metadata}
% \changes{0.0.49}{2026-08-02}{keep table marginalia fixed to their row anchors, place them safely in the outer margin, and format their sums consistently}
% \changes{0.0.48}{2026-08-01}{add running marginal totals to the central funding overview tables and keep marginal annotations inside the page}
% \changes{0.0.47}{2026-08-01}{omit redundant zero decimal parts from monetary values in the requested-funding project table}
% \changes{0.0.46}{2026-08-01}{forward the xparse no-value sentinel correctly so \texttt{\textbackslash{}getProjectPI} works in focused project builds}
% \changes{0.0.45}{2026-08-01}{make \texttt{\textbackslash{}getProject} share the first-reference PI expansion and per-section state of \texttt{\textbackslash{}getProjectPI} when \texttt{projectPIOncePerSection!=true}}
% \changes{0.0.44}{2026-08-01}{move the two alternating provenance-label levels closer together}
% \changes{0.0.43}{2026-08-01}{omit an empty staff academic degree cleanly instead of displaying and warning about a missing value}
% \changes{0.0.42}{2026-08-01}{keep alternating provenance labels strictly zero-width, zero-height, and zero-depth so they never alter prose line spacing or table-row height}
% \changes{0.0.41}{2026-08-01}{distinguish multiple unnamed staff vacancies by their role metadata when checking requested-funding rosters for duplicates}
% \changes{0.0.40}{2026-08-01}{alternate successive provenance tags across two vertical levels and reserve table-cell headroom so rules do not obscure the labels make the CI build portable to minimal runners that do not provide an external \texttt{time} command}
% \changes{0.0.39}{2026-08-01}{show project PIs only on the first \texttt{\textbackslash{}getProjectPI} reference to each project per section by default, with a configurable opt-out}
% \changes{0.0.38}{2026-08-01}{join comma-separated project references from \texttt{\textbackslash{}getProject} as a natural-language list}
% \changes{0.0.37}{2026-08-01}{add compile-based GitLab CI validation and a latest-only Pages deployment of the local dummy proposal extract generated files with plain LuaTeX so clean CI clones need neither a pre-generated installer nor a full documentation build}
% \changes{0.0.36}{2026-08-01}{mark reference-only projects with an asterisk and a local legend in generated tables and lists while retaining the explicit prose wording}
% \changes{0.0.35}{2026-08-01}{restore provenance tags for direct database values and calculated results, with independently suppressible table-cell tags}
% \changes{0.0.34}{2026-08-01}{show the standard skipped-item notice for generated tables and lists in focused project builds apply the same fast-mode notice to direct \texttt{\textbackslash{}OverviewExistingStaffTable} calls support comma-separated applicant affiliations in title-page metadata, funding totals, section labels, and existing-staff headings reuse a referenced person's category and organisation in staff rows when no row-level override is supplied use \texttt{positionText} consistently for the staff roster while retaining \texttt{position} as a compatibility alias add institution abbreviations and use them as compact labels in generated tables while retaining full names in legends render work-package names only at the top level and start sub-workpackage prose without an extra space}
% \changes{0.0.33}{2026-07-30}{add orthogonal \texttt{consider-for-lists} and \texttt{reference-only} project controls exclude non-considered projects from generated project aggregates and active-project counts add cached \texttt{\textbackslash{}getProjectCount} totals for all active projects and the A, B, and Q areas mark reference-only projects as former projects without creating broken project-section links add a consolidated information-retrieval command reference to the documentation and proposal README}
% \changes{0.0.32}{2026-07-30}{rename the focused-project switches to \texttt{fastcompile-project-show-images} and \texttt{fastcompile-project-show-publications} apply the selected graphics draft state explicitly after \texttt{graphicx} loads so image toggling is reliable enable real project images in the active focused-project proposal configuration}
% \changes{0.0.31}{2026-07-30}{keep sub-workpackage names bold and join their following prose into the same paragraph add an opt-in \texttt{fastcompile-project-images} switch for rendering project figures during focused drafting identify fast project drafts with a running project header and a hook-based page watermark}
% \changes{0.0.30}{2026-07-30}{add a dedicated \texttt{fastcompile-project} text-drafting mode that skips metadata databases, calculated project headers, and auxiliary funding restoration add an independent \texttt{project-publications} switch for project publication headings, nocite lists, bibliographies, reports, and result lists use draft graphics, hyperlinks, and microtypography in project-fast mode while retaining authored project prose, sections, labels, aims, and work packages provide database-free fallbacks for project/person references and silence per-item skip output in project-fast builds make final-mode precedence effective before metadata and package setup, and add public fast-project/publication conditionals avoid registering bibliography sources or reading stale bbl data when project-fast publication output is disabled add no-Data-Hub fast project make targets for publication-free and publication-enabled drafting}
% \changes{0.0.29}{2026-07-20}{add an empty-page-style project-overview backmatter page to the generated proposal template improve DOCX conversion of project placeholders and general work-package and subwork-package structures seed converted project files with requested-staff examples and float barriers around publication and diversity sections keep Gantt charts directly after the work packages with strict \texttt{h} placement and a following float barrier move salary and animal-housing rates into validated \texttt{changeSettings} keys and remove the separate generated \texttt{dfg-salaries.tex} file add configurable CRC and affiliation logo paths and retain the former salary and housing commands as expandable compatibility accessors map W2/W3 professorial funding to the shared configurable rate clarify requested-staff applicability rules, validate DFG categories, and use visible no-value backgrounds without alternating row colors separate research and non-research staff groups with a conditional horizontal rule while retaining one row-spanning label per group print resolved existing-staff surnames in bold and format job-description lead-ins as number, academic degree, first name, and last name replace an empty requested-instrumentation overview table with a funding-period-specific explanatory sentence make proposal CI builds reproducible with pinned images, a single Data Hub refresh job, parallel smoke checks, and clean authoritative builds keep live DOI lookups opt-in and preserve generated Data Hub file timestamps when their contents are unchanged support unnamed staff vacancies with \texttt{lastname!=\{TBA\}} without requiring a synthetic first name or academic degree make generated-class Flymake diagnostics useful by suppressing ChkTeX's expl3/Lua false positives and fixing the remaining typography warnings remove the unused \texttt{l3keys2e} dependency and replace \texttt{pdftexcmds} timing with the kernel-native expl3 timer}
% \changes{0.0.28}{2026-07-18}{add the DFG project-level RequestedFundingStaff roster with four official staff groups, continuous numbering, institution/affiliation legends, and job descriptions extend the existing staff key family with validated roster metadata and resilient missing-reference diagnostics calculate omitted yearly staff sums from DFG salary constants, percentage, and quantity while retaining explicit sums as overrides document the roster schema, table call, automatic staff-cost formula, and a complete four-group example polish the staff roster typography and spacing and resolve institutions with their parent-affiliation legend render roster categories as personnel categories such as Prof, PhD, and Research rather than salary-table descriptions extract a focused regression test for the staff roster and automatic salary totals as local/test.tex reuse existing RequestedFundingStaff rows for the chapter-2 overview of existing staff, grouped by DFG category and affiliation fix the CV smoke-build target to use the generated crc-cv.tex filename}
% \changes{0.0.27}{2026-07-17}{replace repeated requested-funding database sums with incremental LaTeX3 property-list indexes reduce each project funding table from five filtered database traversals to one preserve the optional conversion-missing bibliography when generating release classes document the funding-cache architecture, correctness guarantees, and complete-proposal benchmark}
% \changes{0.0.26}{2026-07-16}{add project-local report references and result lists for quality-assured publications, other results, and patents}
% \changes{0.0.25}{2026-07-14}{configure biblatex styles and additional options separately for CV and proposal documents load bibliography customization before biblatex so style settings take effect}
% \changes{0.0.24}{2026-07-14}{emphasize bibliography aliases for every PI assigned to a project}
% \changes{0.0.23}{2026-07-03}{collect all institutions from comma-separated PI institution references in the participating institutions list}
% \changes{0.0.22}{2026-06-24}{rename documentclass for compatibility reason to dfg-crc.cls}
% \changes{0.0.21}{2026-06-23}{reuse the standard institution-list formatter in the project leaders table}
% \changes{0.0.20}{2026-06-22}{add more vertical spacing between multiple institutions in standard institution lists avoid a leading institution-list line break when the institution name is empty expand user documentation for institution metadata, compilation, generated files, and release steps enable open-access markers in biblatex output and document manual BibTeX fallback annotations enable LuaTeX socket support in makefile builds for DOI API lookup load open-access bibliography markers only for final documents}
% \changes{0.0.19}{2026-06-15}{align optional CV table layout with mandatory CV entries add and document CRC/TRR reference commands}
% \changes{0.0.18}{2026-06-11}{extend documentation for PI and project helper commands make documentation examples more coherent and concrete fix typos and stale yes/no key documentation}
% \changes{0.0.17}{2026-06-10}{small functional fix for cv, adding missing spaces change font of section headers in cv}
% \changes{0.0.16}{2026-06-08}{put the test for existing cv-database at proper position, so there is no error when calling dfgCV directly.}
% \changes{0.0.15dev}{2026-05-29}{cv: test for empty start and end}
% \changes{0.0.14}{2026-05-29}{rename all 'true/false' to 'yes/no' since xlsx cannot handle it.}
% \changes{0.0.13}{2026-05-25}{fix dfgTOCprojectPart now properly working with bookmarks.}
% \changes{0.0.12}{2026-05-23}{calculate overview of requested instrumentation and staff from the various projects. no dedicated database is needed.}
% \changes{0.0.11}{2026-05-23}{change symbol of last shared authorship, so it is easier to differentiate. Fallback if there is no cv for a PI of current funding period. Add a version information on the titlepage.}
% \changes{0.0.10}{2026-05-13}{adjusting addEntry when cv-bool active.}
% \changes{0.0.9}{2026-05-12}{renaming -name- to -positionText- for being streamlined.}
% \changes{0.0.7}{2026-05-10}{improving bibliography stuff for cv section}
% \changes{0.0.6}{2026-05-07}{various optimizations regarding runtime creating tables}
% \changes{0.0.5}{2026-05-04}{a lot of refactoring to speed up compiling tables, putting PI information into tcolorboxes for better handling (raster)}
% \changes{0.0.4}{2026-05-01}{working on more efficient code like reducing database queries.}
% \changes{0.0.3}{2026-03-11}{documentation extended}
% \changes{0.0.3}{2026-03-11}{documentation extended}
% \changes{0.0.2}{2026-02-14}{intensive documentation ; more funding tables added}
% \changes{0.0.1}{2026-01-05}{initial setup ;}
%
% The following part is meant for developers. Don't worry if you might not
% understand parts of the code.
% We try to use as much \LaTeX3 as possible for a more granular data handling.
% \iffalse
%<*file>
%<*cls>
% \fi
% \section{Documentclass}
%
% The class requires the June 2022 LaTeX kernel, whose native
% \cs{ProcessKeyOptions} interface processes class options through expl3 key
% families.  \cs{ProvidesExplClass} declares the class to the kernel and
% simultaneously activates the \pkg{expl3} (LaTeX3) syntax, so every line
% from here onwards may use the \texttt{:}, \texttt{\_} and \texttt{@@}
% conventions of the L3 programming layer.
%
% The \meta{version} and \meta{date} values come from the single definition
% at the very top of the |.dtx| file (|\def\dfgVersion| etc.), so a version
% bump only ever needs to be made in one place.
%    \begin{macrocode}
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplClass
{dfg-crc}
{\dfgVersionDate}
{\dfgVersion}
{Create DFG Collaborative Research Centre proposals and CVs}
%    \end{macrocode}
% \subsection{Message catalogue}
%
% All user-visible diagnostics are declared here once using \cs{msg\_new:nnn}
% from the L3 message system.  Centralising them serves several purposes:
% \begin{enumerate}
%   \item The exact wording of every log line can be reviewed and updated in
%         one place without searching through the entire code.
%   \item They are bound to the \texttt{dfg} module name, so a user can grep
%         the |.log| with |grep "Package dfg"| to see a condensed overview.
%   \item Using the L3 message system instead of raw |\PackageWarning| gives
%         consistent formatting, the file\/line context via
%         \cs{msg\_line\_context:}, and the ability to suppress or redirect
%         messages at a global level with \cs{msg\_redirect\_module:nnn}.
% \end{enumerate}
% The engine check fails early with a direct instruction instead of letting
% \pkg{fontspec} or a later \cs{directlua} call produce a less helpful error.
% The next message is emitted when an optional input file (e.g.\ a metadata
% or preamble fragment) cannot be found on the search path.  Compilation is
% not aborted, but the user is strongly warned.
%    \begin{macrocode}
\msg_new:nnn { dfg } { unsupported-engine }
{
  The~dfg-crc~class~requires~LuaLaTeX.^^J
  Compile~this~document~with~lualatex~or~latexmk~-lualatex.
}
\sys_if_engine_luatex:F
  { \msg_fatal:nn { dfg } { unsupported-engine } }

\msg_new:nnn { dfg } { file-not-found }
{ File~'#1'~not~found.^^J
  ~You~can~proceed~without~it~
  but~it~is~not~recommended.
}
%    \end{macrocode}
% \paragraph{database-not-found}
% Emitted by \refCom{getEntry}, \refCom{compareEntry} and each table command when the
% database name passed by the user does not exist in the datatool register.
% The most common cause is a typo in the database name, or calling a retrieval
% command before the corresponding \refCom{addEntry} block has been processed.
%    \begin{macrocode}
\msg_new:nnn { dfg } { database-not-found }
{ Unknown~ database~ name:~ #1^^J^^J
  Database~'#1'~not~found~\msg_line_context:.~
  Either~you~have~misspelled~it~or~
  ~the~database~has~not~yet~been~created.
}
%    \end{macrocode}
% \paragraph{database-name-not-given}
% Fired when the optional \meta{database} argument of \refCom{getEntry} is empty
% because \cs{tmpLocalDB} has not been set and no explicit database name was
% supplied.  The message text suggests two remedies: set \cs{tmpLocalDB} at
% the top of a section, or pass the database name inline.
%    \begin{macrocode}
\msg_new:nnn { dfg } { database-name-not-given }
{ Missing~ database~ name~ for~ entry:~ #1^^J ^^J
  You~forgot~to~pass~a~database~name~\msg_line_context:.~
  You~can~provide~a~name~with~ e.g.~ '\def\tmpLocalDB{<database>}'
  ~or~within~entries~like~
  '\getEntry[<database>]{<id>}{<field>}'.
}
%    \end{macrocode}
% \paragraph{biblatex-ext-oa-doiapi-unavailable}
% Warns when \pkg{biblatex-ext-oa}'s DOI API integration cannot be enabled
% because |socket.http| is not available in the current LuaTeX run.  The
% package is still loaded, so manual BibTeX annotations continue to work.
%    \begin{macrocode}
\msg_new:nnn { dfg } { biblatex-ext-oa-doiapi-unavailable }
{ biblatex-ext-oa~ DOI~ API~ lookup~ disabled:~ LuaSocket~ module~
  'socket.http'~ is~ not~ available~ in~ this~ LuaTeX~ run.~
  Compile~ with~ '--socket'~ to~ enable~ DOI~ API~ requests.~
  Open-access~ markers~ still~ work~ from~ manual~ BibTeX~ annotations.
}
%    \end{macrocode}
% \paragraph{biblatex-ext-oa-doiapi-email-missing}
% DOI lookups require a real contact address.  An empty default keeps network
% access opt-in and prevents all users of the class from sharing a placeholder
% or maintainer address.
%    \begin{macrocode}
\msg_new:nnn { dfg } { biblatex-ext-oa-doiapi-email-missing }
{ biblatex-ext-oa~ DOI~ API~ lookup~ disabled:~ no~contact~address~was~set.^^J
  Set~'doiAPIMail=<address>'~with~\string\changeSettings~to~enable~lookups.
  Open-access~markers~still~work~from~manual~BibTeX~annotations.
}
%    \end{macrocode}
% \paragraph{missing-orcid}
% Triggered specifically by \refCom{getORCiD} when the |orcid| field is absent
% or empty for the requested person.  The message body reproduces the exact
% \refCom{addEntry} snippet the user needs to fill in, lowering the barrier to
% fixing the data.
%    \begin{macrocode}
\msg_new:nnn { dfg } { missing-orcid }
{DB:~'#1';~ID:~'#2';~null/empty:~'orcid'.~^^J^^J
  The~ORCiD~for~the~person~with~the~ID~'#2'~has~not~been~given.~
  You~asked~for~it~\msg_line_context: ~^^J
  If~the~person~has~an~ORCiD, ~go~to~where~you~have~written~^^J
  \addEntry{#1}{^^J
  	id   =#2, ^^J
  	orcid=<INSERT~ORCID~HERE>^^J
  }
}
%    \end{macrocode}
% \paragraph{missing-key}
% Generic warning for any database field that is null or empty when
% \refCom{getEntry} tries to retrieve it.  The check is deliberately suppressed
% during the tabularray cell-measuring pass (|\lTblrMeasuringBool| is |true|)
% to prevent each cell from generating duplicate log entries — tabularray
% renders each cell twice for width calculation before the final output pass.
%
%    \begin{macrocode}
\msg_new:nnn { dfg } { missing-key }
{DB:~'#1';~ID:~'#2';~null/empty:~'#3'.^^J^^J
  In~ the~ database~ '#1', the~ key~ '#3'~ which~ belongs~ to~ the~ ID~ '#2'~
  is~ either~ null/not~ given~ or~ simply~ empty.~^^J
  You~ asked~ for~ it~ \msg_line_context:  }
%    \end{macrocode}
% \paragraph{item-skipped / \cs{dfgItemSkipped}}
% Tables built from the datatool databases are the most expensive part of
% each compilation run because they involve full database queries.  When
% either |fastcompile| mode is active, generated table/list commands call
% \cs{dfgItemSkipped} instead of rendering the real content.  This
% prints a red placeholder in the PDF and issues an |item-skipped| note to
% the log.  The colour |red| is overridden to |white| when |final=true|, so
% the placeholder is invisible in a submission build.
%    \begin{macrocode}
\msg_new:nnn { dfg } { item-skipped }
{Item~ #1~ skipped~ (compile-time).^^J
  To~ see~ the~ item,~ disable~ fast~ compilation^^J
  in~ the~ documentclass-options.^^J
  The~ item~ is~ \msg_line_context:  }
\NewDocumentCommand{\dfgItemSkipped}{m}{%
  \msg_note:nne {dfg}{item-skipped}{ #1 }
  \group_begin:
  \color{error}
  Item~ \emph{\normalcolor#1}~ skipped~ due~ to~ faster~ compilation.~\\
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { To~ see~ the~ item,~ set~ \texttt{fastcompile-project=false}~(default)~ }
  { To~ see~ the~ item,~ set~ \texttt{fastcompile=false}~(default)~ }
  in~ the~ documentclass-options.
  \group_end:
}
%    \end{macrocode}
% \paragraph{research-area-not-found}
% The property list \cs{g\_@@\_dfg\_research\_areas\_prop} contains every
% DFG research area code from the official classification list.  When a code
% stored in the |project| database does not appear in that map the formatted
% label cannot be generated and this warning is raised.  The raw code is still
% printed so the proposal remains compilable.
%    \begin{macrocode}
\msg_new:nnn { dfg } { research-area-not-found }
{ Unknown~ research~ area:~ #1^^J^^J
  Doublecheck~ the~ research~ area~ in~ the~ database:~^^J
  \addEntry{project}{~^^J
  	research-area~ =~ {#1}~^^J
  }
}
%    \end{macrocode}
% \paragraph{item-not-matched}
% Raised as a generic fall-through in \cs{str\_case:VnF} dispatchers where
% a string value is not matched by any of the expected branches.
%    \begin{macrocode}
\msg_new:nnn { dfg } { item-not-matched }
{ The~ string~ '#1'~does~not~match.~^^J^^J
  Doublecheck~ your~input!~^^J
  The~ item~ is~ \msg_line_context:
}
%    \end{macrocode}
% \paragraph{unknown-key and invalid-value}
% These two messages are the default handlers wired into the
% |unknown .code:n| and |\meta{choice} / unknown .code:n| slots of every
% \cs{keys\_define:nn} block.  They give the user immediate feedback in
% the log whenever a key name is misspelled or a value is outside the
% permitted set, instead of silently ignoring the input or producing a
% cryptic low-level TeX error.
%    \begin{macrocode}
\msg_new:nnn { dfg } { unknown-key }
{
  Key~ '\l_keys_path_str'~ is~ unknown~ and~ being~ ignored.~^^J^^J
  You~passed~the~value~'#1'~ to~ that~ key.~^^J
  Check~the~key~spelling~and~the~keys~documented~for~this~family.~^^J
  The~value~was~supplied~\msg_line_context:.
}
%    \end{macrocode}
%   Warning issued when a key receives a value outside its set of
%   permitted alternatives.  This message is the standard fallback for
%   keys defined with the \refPkg{l3keys} \texttt{.choices:nn} property
%   when their |/unknown| handler delegates to the dispatcher
%   \cs{person\_questions\_invalid:n}.  The two arguments are the rejected
%   value and a comma-separated list of the values that would have been
%   accepted.  The full key path is taken from \cs{l\_keys\_path\_str}, so
%   the warning identifies not only the offending value but also which
%   key was being set when the error occurred -- useful when the same
%   value name (such as |yes| or |1|) is plausible for several keys but
%   only valid for some of them.  The warning does not stop processing;
%   the database field is simply not created for the rejected value, and
%   subsequent keys in the same \refCom{addEntry} call continue to be parsed.
%   Diagnostics list input values users can supply, not internal variable
%   names. List-valued keys report each rejected item separately, preserving
%   valid items. Format checks use |invalid-format| with examples; handlers
%   that replace an invalid choice use |invalid-value-fallback| and name the
%   replacement. Date warnings explicitly state that the input is retained.
%    \begin{macrocode}
\msg_new:nnn { dfg } { invalid-value }
{
  Invalid~value~'#1'~for~key~'\l_keys_path_str'.~^^J^^J
  Allowed~values~are:~'#2'.~^^J
  This~value~is~ignored.~^^J
  The~value~was~supplied~\msg_line_context:.
}
\msg_new:nnn { dfg } { invalid-value-fallback }
{
  Invalid~value~'#1'~for~key~'\l_keys_path_str'.~^^J^^J
  Allowed~values~are:~'#2'.~^^J
  Using~'#3'~instead.~^^J
  The~value~was~supplied~\msg_line_context:.
}
\msg_new:nnn { dfg } { invalid-format }
{
  Invalid~value~'#1'~for~key~'\l_keys_path_str'.~^^J^^J
  Expected~#2.~This~value~is~ignored.~^^J
  The~value~was~supplied~\msg_line_context:.
}
\msg_new:nnn { dfg } { unknown-name }
{
  Unknown~#1~'#2'.~^^J
  Allowed~values~are:~'#3'.~^^J
  A~mismatch~marker~is~printed.~^^J
  The~value~was~used~\msg_line_context:.
}
\msg_new:nnn { dfg } { unknown-institution-order }
{
  Invalid~order~'#1'~for~ParticipatingInstitutions.~^^J
  Allowed~values~are:~'alpha,~count'.~Using~'alpha'~instead.~^^J
  The~order~was~supplied~\msg_line_context:.
}
\msg_new:nnn { dfg } { invalid-project-count-area }
{
  No~active,~list-considered~projects~were~found~for~area~'#1'~in~
  \string\getProjectCount;~printing~0.
}
\msg_new:nnn { dfg } { collaboration-focus-not-found }
{
  Cannot~draw~the~project~collaboration~plot:~focus~project~'#1'~is~not~an~
  eligible~row~of~the~project~database.
}
\msg_new:nnn { dfg } { collaboration-target-not-found }
{
  Ignoring~collaboration~'#1--#2':~project~'#2'~is~not~an~eligible~row~of~
  the~project~database.
}
\msg_new:nnn { dfg } { plot-current-project-missing }
{
  Cannot~print~the~'#1'~plot:~no~current~project~has~been~set.~Start~a~
  project~first,~or~pass~an~explicit~project~ID.
}
%    \end{macrocode}
%
%   Warning issued when a date-typed key receives a value that does not
%   match the ISO-8601 calendar-date shape \texttt{YYYY-MM-DD}.  Used by
%   the contract-information helper \cs{dfg\_contract\_date:nn} for the
%   fields \refKey{C2a}, \refKey{C2b}, and \refKey{C3a}, all of which
%   are expected to hold dates.  The two arguments are the field name
%   and the offending value.  The check is purely structural: it
%   verifies that the value consists of four digits, a hyphen, two
%   digits, a hyphen, and two digits, but it does not validate the
%   resulting date as a real calendar entry (so \texttt{2025-13-45}
%   passes the format check).  When the warning fires, the supplied
%   value is still recorded in the database so the typeset output makes
%   the malformed entry visible; this trades log-cleanliness for ease
%   of locating the source of the problem in the rendered document.
%    \begin{macrocode}
\msg_new:nnn { dfg } { invalid-date }
{
  Invalid~date~'#2'~for~key~'\l_keys_path_str'~(field~'#1').~^^J
  Expected~YYYY-MM-DD,~for~example~2026-10-11,~or~an~empty~value.~^^J
  The~supplied~value~is~retained;~correct~its~format~in~the~source.~^^J
  The~value~was~supplied~\msg_line_context:.
}
%    \end{macrocode}
% \paragraph{Requested-funding staff diagnostics}
% The staff roster is deliberately permissive at output time: incomplete or
% unresolved records remain visible in the document while these messages make
% the underlying metadata problem searchable in the log.
%    \begin{macrocode}
\msg_new:nnn { dfg } { requested-staff-no-data }
{ No~RequestedFundingStaff~data~have~been~provided~for~project~'#1'. }
\msg_new:nnn { dfg } { requested-staff-required }
{ RequestedFundingStaff~entry~is~missing~required~metadata:~#1. }
\msg_new:nnn { dfg } { requested-staff-institution-required }
{
  RequestedFundingStaff~entry~for~project~'#1'~has~neither~ref-person-id~nor~
  ref-institution-id.~Provide~ref-institution-id~when~the~person~is~not~
  referenced;~otherwise~the~institution~cannot~be~resolved.
}
\msg_new:nnn { dfg } { requested-staff-missing-field }
{
  Project~'#1':~#3~staff~no.~#2~(funding-status=#3):~#4~is~missing.
}
\msg_new:nnn { dfg } { existing-staff-missing-commitment }
{
  Project~'#1':~existing~staff~no.~#2~(funding-status=existing):~
  commitment~is~missing.~^^J
  Set~commitment={hours~per~week}~for~this~existing~staff~row.~^^J
  Requested~staff~(funding-status=requested)~do~not~require~commitment.~
  If~this~row~is~requested~staff,~correct~its~funding-status.
}
\msg_new:nnn { dfg } { requested-staff-unresolved-person }
{ Project~'#1':~person~reference~'#2'~cannot~be~resolved. }
\msg_new:nnn { dfg } { requested-staff-unresolved-institution }
{ Project~'#1':~institution~reference~'#2'~cannot~be~resolved. }
\msg_new:nnn { dfg } { requested-staff-unresolved-affiliation }
{ Project~'#1':~affiliation~reference~'#2'~cannot~be~resolved. }
\msg_new:nnn { dfg } { requested-staff-missing-abbreviation }
{ Affiliation~'#1'~has~no~abbreviation;~its~full~name~is~used. }
\msg_new:nnn { dfg } { duplicate-institution-abbreviation }
{
  Institution~abbreviation~'#1'~is~assigned~to~different~institutions:~^^J
  '#2'~and~'#3'~(institution~ids:~#4).~^^J
  Use~a~unique~abbreviation~for~each~institution.
}
\msg_new:nnn { dfg } { duplicate-entry-id }
{
  Duplicate~id~'#2'~in~database~'#1'.~^^J
  The~earlier~row(s)~are~removed;~the~later~entry~replaces~them.~^^J
  The~replacement~is~\msg_line_context:.
}
\msg_new:nnn { dfg } { requested-staff-duplicate }
{ Duplicate~RequestedFundingStaff~entry~for~#1. }
\msg_new:nnn { dfg } { funding-staff-cost-unavailable }
{ Automatic~staff-cost~calculation~is~not~available~for~#1. }
\msg_new:nnn { dfg } { existing-staff-no-data }
{ No~existing~staff~rows~were~found~in~database~'#1'. }
\msg_new:nnn { dfg } { existing-staff-no-organisation }
{ Existing~staff~entry~'#1'~cannot~be~assigned~to~an~affiliation. }
%    \end{macrocode}
% 
% \begin{macro}{\StartTimer}
% \begin{macro}{\StopTimer}
%   A simple pair of profiling helpers for measuring how long a
%   stretch of \LaTeX{} code takes to execute.  Wrap the code under
%   investigation between |\StartTimer| and
%   |\StopTimer{|\meta{label}|}|; the elapsed time in milliseconds
%   is written to the terminal and the |.log| file, prefixed with
%   the supplied \meta{label} so several measurements in one run
%   can be told apart.
%
%   Typical use:
%   \begin{quote}
%     |\StartTimer|\\
%     |\ParticipatingInstitutionsList[count]|\\
%     |\StopTimer{ParticipatingInstitutionsList}|
%   \end{quote}
%   producing a line such as
%   \begin{quote}
%     |TIMING ParticipatingInstitutionsList: 115 ms|
%   \end{quote}
%   in the log.
%
%   Only one measurement can be in progress at any one time, since
%   the start time is held in a single shared integer variable.
%   For nested or overlapping measurements, define additional
%   counters or switch to the labelled-timer variant.
%
%   The implementation uses the kernel-native expl3 function
%   |\sys_timer:|, which abstracts over the engine-specific timer and avoids an
%   additional package dependency.
%    \begin{macrocode}
\int_new:N \l_@@_timer_int
%    \end{macrocode}
%   Storage for the start timestamp.  We use an |int| rather than a
%   |tl| so the later subtraction in |\int_eval:n| is unambiguous.
%    \begin{macrocode}
\NewDocumentCommand { \StartTimer } { }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  { \int_set:Nn \l_@@_timer_int { \sys_timer: } }
}
%    \end{macrocode}
%   |\sys_timer:| expands to the time since job start in
%   \emph{scaled seconds} -- units of $1/65536$~s.  We capture
%   that raw value here and convert to milliseconds only at
%   reporting time, to keep the start-up overhead minimal.
%    \begin{macrocode}
\NewDocumentCommand { \StopTimer } { m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \iow_term:x
    {
      TIMING~#1:~
      \int_eval:n
      { ( \sys_timer: - \l_@@_timer_int ) * 1000 / 65536 }
      \c_space_tl ms
    }
  }
}
%    \end{macrocode}
%   The arithmetic computes elapsed scaled-seconds first, then
%   multiplies by~$1000$ before dividing by~$65536$.  Doing the
%   multiplication first preserves precision: a naive
%   |(now - start) / 65536 * 1000| would truncate sub-second
%   measurements to zero.  The result is an integer count of
%   milliseconds, accurate to roughly $\pm 1$~ms.
%
%   |\iow_term:x| writes to the terminal \emph{and} the log,
%   fully expanding its argument once -- which is what makes
%   |\int_eval:n| produce a literal number rather than the
%   unevaluated expression.  |\c_space_tl| inserts a real space
%   between the number and the |ms| unit; a literal space there
%   would be consumed by |expl3|'s tokenisation rules.
%
%   Note that the reported time is wall-clock and includes any
%   |\typeout|, file~I/O, or shell-escape work performed inside
%   the timed block.  For tight measurements of pure computation,
%   silence debugging output during the run, and take the second
%   of two consecutive timings to avoid first-run effects such
%   as font caching or |.aux| reads.
% \end{macro}
% \end{macro}
% \subsection{Documentclass Options}
%
% We have very few global options we use from the KOMAscript.
% But you can use any known option of the KOMAscript |scrbook|.
% The initial |parskip=half-| option establishes the KOMA paragraph style;
% \cs{setparsizes} below replaces its gap with the compact 3.5\,pt default.
%    \begin{macrocode}
\PassOptionsToClass{
  fontsize  =11pt, % DFG template
  twoside   =true,
  BCOR      =5mm,
  headings  =optiontoheadandtoc,
  parskip   =half-,
  numbers   =noenddot,
  toc       =indentunnumbered
}{scrbook}
%    \end{macrocode}
% \subsection{Class options (\texttt{dfg/class} key family)}
%
% All class-level toggles live in the |dfg/class| key family and are
% processed via \cs{ProcessKeyOptions}.  They control the two major compilation modes
% (\refKey{fastcompile}, \refKey{fastcompile-project}, \refKey{final}) plus
% several debugging and output flags.
%
% The general design principle is that every flag defaults to |false| or
% to a safe, submission-ready value.  Authors enable the helpers they need
% during drafting and simply remove them (or set |final=true|) before
% submitting.  Setting |final=true| enforces this by hard-resetting all
% drafting flags to |false| automatically.
%    \begin{macrocode}
\keys_define:nn { dfg / class }
{
%    \end{macrocode}
% The manual loads explicit example inputs, independent of proposal files.
%    \begin{macrocode}
documentation .bool_set:N = \l_@@_class_documentation_bool,
documentation .initial:n = false,
%    \end{macrocode}
% \refKey{final}: Set to |true| immediately before submission.
% It forces |cmyk| colour model (required for print), silently sets
% |fastcompile=false|, |showtags=false|, |showmarginalia=false| and
% |skip10pub=false|, and turns the draft-green placeholder colour
% to white so it is invisible in the output.
%    \begin{macrocode}
final      .bool_set:N = \l_@@_class_final_bool,
final      .initial:n  = false,
Final      .meta:n     = { final = #1 },
Final      .default:n  = true,
%    \end{macrocode}
% \refKey{fastcompile}: When |true|, generated tables and lists are replaced by
% a placeholder.  It also suppresses role-card grids, the Gantt chart, and the
% ten-publications CV block while retaining metadata-backed prose references.
% Automatically disabled when |final=true|.
%    \begin{macrocode}
fastcompile   .bool_set:N = \l_@@_class_fastcompile_bool,
fastcompile   .initial:n  = false,
%    \end{macrocode}
% \refKey{fastcompile-project}: Aggressive project-text drafting mode.  It
% implies \refKey{fastcompile}, but additionally prevents metadata rows from
% being loaded or restored, replaces calculated project headings with
% recorded-space placeholders, uses draft rendering for graphics and links, and provides
% literal fallbacks for database-backed references.  Authored sections,
% paragraphs, aims, work packages, labels, and inline citations remain.
% Automatically disabled when |final=true|.
%    \begin{macrocode}
fastcompile-project .bool_set:N = \l_@@_class_fastcompile_project_bool,
fastcompile-project .initial:n  = false,
%    \end{macrocode}
% \refKey{fastcompile-project-show-images}: Opt back into real image rendering while
% aggressive project drafting is active.  It has no effect on ordinary builds,
% where graphics are rendered normally.  Final mode resets it to |false|
% together with the other drafting controls.
%    \begin{macrocode}
fastcompile-project-show-images .bool_set:N = \l_@@_class_fastcompile_project_show_images_bool,
fastcompile-project-show-images .initial:n  = false,
%    \end{macrocode}
% \refKey{fastcompile-project-show-publications}: Controls the standard project publication
% heading, explicit project \cs{nocite} lists, project bibliographies,
% project-report references, and ending-project result lists during focused
% project drafting.  Ordinary and final builds force it to |true|.
%    \begin{macrocode}
fastcompile-project-show-publications .bool_set:N = \l_@@_class_fastcompile_project_show_publications_bool,
fastcompile-project-show-publications .initial:n  = false,
%    \end{macrocode}
% \refKey{fastcompile-project-show-funding-tables}: Retain the three
% project-local funding tables in aggressive project drafting mode.  The
% option defaults to |true| and has no effect outside that mode.
%    \begin{macrocode}
fastcompile-project-show-funding-tables .bool_set:N = \l_@@_class_fastcompile_project_show_funding_tables_bool,
fastcompile-project-show-funding-tables .initial:n  = true,
%    \end{macrocode}
% \refKey{fastcompile-show-tags}: Enables provenance overlays during fast
% compilation. Focused project lookups show their source row and requested
% field path because metadata rows are skipped.
%    \begin{macrocode}
fastcompile-show-tags .bool_set:N = \l_@@_class_fastcompile_show_tags_bool,
fastcompile-show-tags .initial:n  = false,
%    \end{macrocode}
% \refKey{showtags}: Enables provenance overlays for direct database values and
% concise source labels for calculated values in ordinary builds. During fast
% compilation, \refKey{fastcompile-show-tags} controls the setting instead.
%    \begin{macrocode}
showtags   .bool_set:N = \l_@@_class_showtags_bool,
showtags   .initial:n  = false,
%    \end{macrocode}
% \refKey{showtags-tables}: Controls only provenance overlays rendered in table
% cells.  It defaults to |true|, but remains inert unless \refKey{showtags} is
% enabled.  Keeping it separate lets authors debug prose without widening or
% visually overloading dense generated tables.
%    \begin{macrocode}
showtags-tables  .bool_set:N = \l_@@_class_showtags_tables_bool,
showtags-tables  .initial:n  = true,
%    \end{macrocode}
% \refKey{showmarginalia}: Enables marginal notes that display running
% subtotals alongside the funding tables.  Useful for cross-checking
% calculated sums during data entry.  Disabled by |final=true|.
%    \begin{macrocode}
showmarginalia .bool_set:N = \l_@@_class_showmarginalia_bool,
showmarginalia .initial:n  = false,
%    \end{macrocode}
% \refKey{skip10pub}: Suppresses the mandatory ten-publication block in
% each CV section.  Because each bibliography list requires a full biber
% run and can take several seconds per PI, skipping it during early drafting
% significantly reduces compilation time.  Automatically disabled by |final=true|.
%    \begin{macrocode}
skip10pub  .bool_set:N = \l_@@_class_skipTENpublications_bool,
skip10pub  .initial:n  = false,
%    \end{macrocode}
% \refKey{colorscheme}: Passed directly to \cs{selectcolormodel} at
% \cs{AtBeginDocument}.  Use |cmyk| for press-quality PDF output (DFG
% submission default) or |RGB| for on-screen review.  Overridden to
% |cmyk| when |final=true|.
%    \begin{macrocode}
colorscheme .tl_set:N   =  \l_@@_class_color_model_tl,
colorscheme .initial:n  = cmyk,
%    \end{macrocode}
% \refKey{cv}: Set to |true| in the standalone CV document
% (|crc-cv.tex|).  When |true|, the class adjusts heading styles
% and suppresses proposal-specific front matter so the output is a
% self-contained curriculum vitae suitable for DFG submission.
%    \begin{macrocode}
cv   .bool_set:N = \l_@@_class_cv_bool,
cv   .initial:n  = false,
unknown .code:n = { \PassOptionsToClass{\CurrentOption}{scrbook} },
}
%    \end{macrocode}
% \subsection{Conditional execution based on class options}
%
% The class option |cv| toggles whether the document is rendered as a
% CV (curriculum vitae) supplement.  Internally this is stored in the
% expl3 boolean |\l_@@_class_cv_bool|.  Since end-user document files
% should not be required to wrap conditional content in
% |\ExplSyntaxOn|\,/\,|\ExplSyntaxOff|, the following three commands
% expose the switch through a conventional \LaTeX{} interface.
%
% \DescribeMacro{\dfgIfCV}
% |\dfgIfCV|\marg{true code}\marg{false code}\par
% Executes \meta{true code} if the |cv| option is active, otherwise
% \meta{false code}.  Use this when both branches need to produce
% content, for instance to switch between a full bibliography and a
% short selected-publications list:
% \begin{quote}
% |\dfgIfCV{\printbibliography[heading=none]}{\printshortbib}|
% \end{quote}
%
% \DescribeMacro{\dfgIfCVT}
% |\dfgIfCVT|\marg{true code}\par
% Shorthand for the common case where only the true branch matters.
% Typical use is gating a section that exists only in the CV variant:
% \begin{quote}
% |\dfgIfCVT{\par\textcolor{tableHeadingsFont}{Appendix:~Research~profiles}}|
% \end{quote}
% Equivalent to |\dfgIfCV{|\meta{true code}|}{}| but avoids the empty
% second argument and reads more naturally in document source.
%
% \DescribeMacro{\dfgIfCVF}
% |\dfgIfCVF|\marg{false code}\par
% Mirror image of |\dfgIfCVT|: executes \meta{false code} only when the
% |cv| option is \emph{not} active.  Useful for content that belongs in
% the main proposal but should be suppressed in the CV variant.
%
% None of these commands evaluates its arguments unless the relevant
% branch is taken, so wrapping expensive or side-effecting code is safe.
% All three are defined with |\NewDocumentCommand|, so their arguments
% are read as standard mandatory braced groups and may contain verbatim
% material only where the underlying typesetting context permits.
%
%    \begin{macrocode}
\NewDocumentCommand \dfgIfCV  { +m +m }
  { \bool_if:NTF \l_@@_class_cv_bool {#1} {#2} }
\NewDocumentCommand \dfgIfCVT { +m }
  { \bool_if:NT  \l_@@_class_cv_bool {#1} }
\NewDocumentCommand \dfgIfCVF { +m }
  { \bool_if:NF  \l_@@_class_cv_bool {#1} }

\NewDocumentCommand \dfgIfFinalF { +m }
  { \bool_if:NF  \l_@@_class_final_bool {#1} }
\NewDocumentCommand \dfgIfFastCompileProject { +m +m }
  { \bool_if:NTF \l_@@_class_fastcompile_project_bool {#1} {#2} }
\NewDocumentCommand \dfgIfFastCompileProjectT { +m }
  { \bool_if:NT \l_@@_class_fastcompile_project_bool {#1} }
\NewDocumentCommand \dfgIfFastCompileProjectF { +m }
  { \bool_if:NF \l_@@_class_fastcompile_project_bool {#1} }
\NewDocumentCommand \dfgIfProjectPublications { +m +m }
  { \bool_if:NTF \l_@@_class_fastcompile_project_show_publications_bool {#1} {#2} }
%    \end{macrocode}
% Unknown options are forwarded by the key handler above, so ordinary
% KOMA-Script options remain available without processing the class options a
% second time.  Finally process and execute all options and key-values.
%    \begin{macrocode}
\ProcessKeyOptions[ dfg / class ]
% Resolve mode precedence before any package, customisation, metadata, or
% auxiliary-file work can observe the drafting booleans.
\bool_if:NTF \l_@@_class_final_bool
{
  \bool_set_false:N \l_@@_class_fastcompile_bool
  \bool_set_false:N \l_@@_class_fastcompile_project_bool
  \bool_set_false:N \l_@@_class_fastcompile_project_show_images_bool
  \bool_set_true:N  \l_@@_class_fastcompile_project_show_funding_tables_bool
  \bool_set_false:N \l_@@_class_showtags_bool
  \bool_set_false:N \l_@@_class_showmarginalia_bool
  \bool_set_false:N \l_@@_class_skipTENpublications_bool
  \bool_set_true:N  \l_@@_class_fastcompile_project_show_publications_bool
}
{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \bool_set_true:N  \l_@@_class_fastcompile_bool
    \bool_set_false:N \l_@@_class_showmarginalia_bool
    \bool_set_true:N  \l_@@_class_skipTENpublications_bool
    \PassOptionsToPackage{draft}{hyperref}
    \PassOptionsToPackage{draft}{microtype}
  }
  { \bool_set_true:N \l_@@_class_fastcompile_project_show_publications_bool }
  \bool_if:NT \l_@@_class_fastcompile_bool
  {
    \bool_if:NTF \l_@@_class_fastcompile_show_tags_bool
      { \bool_set_true:N \l_@@_class_showtags_bool }
      { \bool_set_false:N \l_@@_class_showtags_bool }
  }
}
\LoadClass{scrbook}
% A negative initial value requests the font-derived default; a nonnegative
% value supplied by the customization file or preamble overrides it.
\newlength{\dfgTablePreSep}
\setlength{\dfgTablePreSep}{-1pt}
%    \end{macrocode}
% Use KOMA-Script's paragraph interface so the compact gap also applies after
% font-size changes.  Retain zero indentation and a freely stretchable final
% line.  The customization file is loaded later and may override these values
% with \cs{setparsizes}.
%    \begin{macrocode}
\setparsizes{0pt}{3.5pt plus 1pt minus 0.5pt}{0pt plus 1fil}
\PassOptionsToPackage{table}{xcolor} % getting rid of errors and conflicts.
\RequirePackage{xcolor}
%    \end{macrocode}
% \subsection{Colour palette}
%
% All colours follow the RWTH Aachen corporate-identity palette and are
% defined in all four models at once (|cmyk/RGB/HTML/gray|) using xcolor's
% multiple-model syntax.  This allows the same symbolic name to be used
% regardless of the active colour model chosen via |colorscheme=|.
%
% Each hue comes in five tints named |-100| (full) through |-10| (near
% white), matching the official RWTH tint steps.  This naming scheme is
% intentional: table headers, zebra stripes and box backgrounds are all
% specified in terms of these canonical names (e.g. |blue-50|, |black-10|),
% so a complete rebranding only requires changing the definitions here.
%
% The ORCiD brand green is also declared here since it is used by
% \cs{orcidIcon} throughout the document.
%    \begin{macrocode}
\definecolor{blue-100}{cmyk/RGB/HTML/gray}{1,.50,0,0/0,84,159/00549F/1}% primary
\definecolor{blue-75}{cmyk/RGB/HTML/gray}{.75,.38,0,0/64,127,183/407FB7/.75}%
\definecolor{blue-50}{cmyk/RGB/HTML/gray}{.45,.14,0,0/142,186,229/8EBAE5/.5}% secondary
\definecolor{blue-25}{cmyk/RGB/HTML/gray}{.23,.07,0,0/199,221,242/C7DDF2/.25}%
\definecolor{blue-10}{cmyk/RGB/HTML/gray}{.09,.03,0,0/232,241,250/E8F1FA/.1}%

\definecolor{black-100}{cmyk/RGB/HTML}{0,0,0,1/0,0,0/000000}%
\definecolor{black-75}{cmyk/RGB/HTML}{0,0,0,.75/100,101,103/646567}%
\definecolor{black-50}{cmyk/RGB/HTML}{0,0,0,.5/156,158,159/9C9E9F}%
\definecolor{black-25}{cmyk/RGB/HTML}{0,0,0,.25/207,209,210/CFD1D2}%
\definecolor{black-10}{cmyk/RGB/HTML}{0,0,0,.1/236,237,237/ECEDED}%

\definecolor{green-100}{cmyk/RGB/HTML}{.7,0,1,0/87,171,39/57AB27}%
\definecolor{green-75}{cmyk/RGB/HTML}{.52,0,.75,0/141,192,96/8DC060}%
\definecolor{green-50}{cmyk/RGB/HTML}{.35,0,.5,0/184,214,152/B8D698}%
\definecolor{green-25}{cmyk/RGB/HTML}{.18,0,.25,0/221,235,206/DDEBCE}%
\definecolor{green-10}{cmyk/RGB/HTML}{.07,0,.1,0/242,247,236/F2F7EC}%

\definecolor{red-100}{cmyk/RGB/HTML}{.15,1,1,0/204,7,30/CC071E}%
\definecolor{red-75}{cmyk/RGB/HTML}{.11,.75,.75,0/216,92,65/D85C41}%
\definecolor{red-50}{cmyk/RGB/HTML}{.8,.5,.5,0/230,150,121/E69679}%
\definecolor{red-25}{cmyk/RGB/HTML}{.4,.25,.25,0/243,205,187/F3CDBB}%
\definecolor{red-10}{cmyk/RGB/HTML}{.2,.1,.1,0/250,235,227/FAEBE3}%

\definecolor{bordeaux-100}{cmyk/RGB/HTML}{.25,1,.70,.20/161,16,53/A11035}%
\definecolor{bordeaux-75}{cmyk/RGB/HTML}{.19,.75,.52,15/182,82,86/B65256}%
\definecolor{bordeaux-50}{cmyk/RGB/HTML}{.13,.5,.35,.1/205,139,135/CD8B87}%
\definecolor{bordeaux-25}{cmyk/RGB/HTML}{.06,.25,.18,.05/229,197,192/E5C5C0}%
\definecolor{bordeaux-10}{cmyk/RGB/HTML}{.03,.1,.07,.02/245,232,229/F5E8E5}%

\definecolor{orcid}{cmyk/RGB}{0.15,0.00,0.59,0.20/174,205,84}
%    \end{macrocode}
% Let’s start with the common section on packages etc.
% \subsection{Customisation key family (\texttt{dfg/custom})}
% We provide as much as possible all settings to customize to your desire and
% needs.
% The customization is done with key-values, which we set up below.
%
%    \begin{macrocode}
% Public document text exists before the customization file is read. Keep
% externally supplied definitions (including InfoTeX from the build command).
\providecommand{\dfgLocation}{
  \bool_if:NTF \l_@@_class_fastcompile_bool
    { \textcolor{error}{<Location>} }
    { <Location> }\xspace
}
\providecommand{\dfgDate}{
  \bool_if:NTF \l_@@_class_fastcompile_bool
    { \textcolor{error}{<date>} }
    { <date> }\xspace
}
\providecommand{\dfgTitle}{\enquote{\get[meta]{crc}{name}}\xspace}
\providecommand{\InfoTeX}{LuaLaTeX~ (via~ Overleaf).}
\bool_new:N \l_@@_custom_thumbindex_topmargin_set_bool
\bool_new:N \l_@@_custom_thumbindex_bottommargin_set_bool
\dim_new:N \l_@@_custom_thumbindex_topmargin_dim
\dim_new:N \l_@@_custom_thumbindex_bottommargin_dim
\int_new:N \l_@@_custom_thumbindex_rotation_int
\tl_new:N \l_@@_custom_pi_contact_style_tl
\tl_new:N \l_@@_custom_cv_table_after_skip_tl
\tl_new:N \l_@@_custom_plot_options_tl
\tl_new:N \l_@@_custom_gantt_plot_options_tl
\tl_new:N \l_@@_custom_collaboration_plot_options_tl
\tl_new:N \l_@@_custom_journal_title_tl
\tl_new:N \l_@@_custom_project_title_toc_tl
\tl_new:N \l_@@_custom_project_title_runningHead_tl
\tl_new:N \l_@@_custom_project_title_projectStart_tl
\keys_define:nn { dfg / project-title }
{
  toc .choices:nn = {full,short}
    { \tl_set:Nn \l_@@_custom_project_title_toc_tl {#1} },
  toc .initial:n = full,
  toc .value_required:n = true,
  runningHead .choices:nn = {full,short}
    { \tl_set:Nn \l_@@_custom_project_title_runningHead_tl {#1} },
  runningHead .initial:n = full,
  runningHead .value_required:n = true,
  projectStart .choices:nn = {full,short}
    { \tl_set:Nn \l_@@_custom_project_title_projectStart_tl {#1} },
  projectStart .initial:n = full,
  projectStart .value_required:n = true,
}
\keys_define:nn { dfg / custom  }
{
  projectTitle .code:n = \keys_set:nn { dfg / project-title } {#1},
  projectTitle .value_required:n = true,
  % Assign without expansion; metadata references resolve when printed.
  dfgLocation .code:n = \cs_set:Npn \dfgLocation {#1\xspace},
  dfgDate     .code:n = \cs_set:Npn \dfgDate {#1\xspace},
  dfgTitle    .code:n = \cs_set:Npn \dfgTitle {#1\xspace},
  InfoTeX     .code:n = \cs_set:Npn \InfoTeX {#1},

  % You can pass any font you like (and |fontspec| will understand or is known to
  % your system). The current main and sansserif defaults are Arimo; the
  % sansserif face overrides below retain selected Roboto variants.
  font                       .tl_set:N   = \l_@@_custom_font_tl,
  fontspec                   .tl_set:N   = \l_@@_custom_fontspec_tl,
  font                       .initial:n  = Arimo,
  sansfont                   .tl_set:N   = \l_@@_custom_sansfont_tl,
  sansfontspec               .tl_set:N   = \l_@@_custom_sansfontspec_tl,
  sansfont                   .initial:n  = Arimo,
  sansfontspec            .initial:n     = {
  		ItalicFont=Roboto-LightItalic,
  		BoldFont=Roboto-Medium,
  		BoldItalicFont=Roboto-Medium-Italic},
  % \paragraph{Logo paths}
  crcLogoPath                 .tl_set:N   = \l_@@_custom_crc_logo_path_tl,
  crcLogoPath                 .initial:n  = example-image-a,
  affiliationLogoPath         .tl_set:N   = \l_@@_custom_affiliation_logo_path_tl,
  affiliationLogoPath         .initial:n  = example-image-b,
  % \paragraph{Project-reference repetition}
  projectPIOncePerSection      .bool_set:N =
    \l_@@_custom_project_pi_once_per_section_bool,
  projectPIOncePerSection      .initial:n  = true,
  PIReferenceFirstName .bool_set:N =
    \l_@@_custom_pi_reference_firstname_bool,
  PIReferenceFirstName .initial:n = false,
  % Project tables use full institution names by default. Set true for
  % compact abbreviations and a table-local full-name legend.
  projectsTableInstitutionAbbreviations .bool_set:N =
    \l_@@_custom_projects_table_institution_abbreviations_bool,
  projectsTableInstitutionAbbreviations .initial:n = false,
  % Use compact English labels for personnel categories.
  categoryAbbreviations .bool_set:N = \l_@@_custom_category_abbreviations_bool,
  categoryAbbreviations .initial:n = false,
  % Evaluate relative dimensions when each CV block finishes, not at setup.
  cvTableAfterSkip .tl_set:N = \l_@@_custom_cv_table_after_skip_tl,
  cvTableAfterSkip .initial:n = {0pt},
  cvTableAfterSkip .value_required:n = true,
  % Plot options are stored without expansion and parsed when a plot is printed.
  % Merge order: shared defaults, type defaults, then per-call options.
  plotOptions .tl_set:N = \l_@@_custom_plot_options_tl,
  plotOptions .initial:n = {},
  plotOptions .value_required:n = true,
  ganttPlotOptions .tl_set:N = \l_@@_custom_gantt_plot_options_tl,
  ganttPlotOptions .initial:n = {},
  ganttPlotOptions .value_required:n = true,
  collaborationPlotOptions .tl_set:N = \l_@@_custom_collaboration_plot_options_tl,
  collaborationPlotOptions .initial:n = {},
  collaborationPlotOptions .value_required:n = true,
  % Contact labels in PI boxes: icons (default), text labels, or no labels.
  PIcontactStyle .tl_set:N = \l_@@_custom_pi_contact_style_tl,
  PIcontactStyle .initial:n = icons,
  % Collaboration-plot area colors can be set once for the complete proposal.
  % Per-plot area-colors and area-palette options may override these defaults.
  collaborationAreaColors      .tl_set:N =
    \l_@@_custom_collaboration_area_colors_tl,
  collaborationAreaColors      .initial:n =
    { A=projectA, B=projectB, Q=projectQ!75!black },
  collaborationAreaPalette     .code:n =
    {
      \clist_if_empty:nF {#1}
        { \tl_set:Nn \l_@@_custom_collaboration_area_palette_tl {#1} }
    },
  collaborationAreaPalette     .initial:n =
    { orange!80!black, violet!75!black, teal!70!black,
      brown!75!black, magenta!70!black, cyan!70!black, lime!60!black },
  % \paragraph{DFG salary and animal-housing rates}
  salary@prof                 .fp_set:N   = \l_@@_custom_salary_prof_fp,
  salary@prof                 .initial:n  = 126600,
  salary@groupLeader          .fp_set:N   = \l_@@_custom_salary_group_leader_fp,
  salary@groupLeader          .initial:n  = 105000,
  salary@postDoc              .fp_set:N   = \l_@@_custom_salary_postdoc_fp,
  salary@postDoc              .initial:n  = 90600,
  salary@medDoc               .fp_set:N   = \l_@@_custom_salary_meddoc_fp,
  salary@medDoc               .initial:n  = 112200,
  salary@PhD                  .fp_set:N   = \l_@@_custom_salary_phd_fp,
  salary@PhD                  .initial:n  = 83700,
  salary@research             .fp_set:N   = \l_@@_custom_salary_research_fp,
  salary@research             .initial:n  = 69000,
  salary@nonResearch          .fp_set:N   = \l_@@_custom_salary_nonresearch_fp,
  salary@nonResearch          .initial:n  = 61500,
  salary@student              .fp_set:N   = \l_@@_custom_salary_student_fp,
  salary@student              .initial:n  = 1,
  salary@assistant            .fp_set:N   = \l_@@_custom_salary_assistant_fp,
  salary@assistant            .initial:n  = 1,
  animalHousing@mouse         .fp_set:N   = \l_@@_custom_animal_mouse_fp,
  animalHousing@mouse         .initial:n  = 0.75,
  animalHousing@mouseGnotobiotic .fp_set:N =
    \l_@@_custom_animal_mouse_gnotobiotic_fp,
  animalHousing@mouseGnotobiotic .initial:n = 3.9,
  animalHousing@rat           .fp_set:N   = \l_@@_custom_animal_rat_fp,
  animalHousing@rat           .initial:n  = 1.4,
  % \paragraph{Thumb-index keys}
  % These keys control the decorative side tab on the outer margin.
  % The index divides the text block into \meta{pattern} equal-height slots by
  % default.  Explicit page-edge margins can override either end of the stack.
  % Each call to \cs{printThumbIndex}
  % advances the slot counter; when it reaches \meta{pattern} it wraps,
  % creating a repeating stripe aiding chapter navigation.
  %
  thumbindex                 .bool_set:N = \l_@@_custom_thumbindex_bool,
  thumbindex                 .initial:n  = true,
  %
  thumbindex@pattern         .int_set:N  = \l_@@_custom_thumbindexpattern_int,
  thumbindex@pattern         .initial:n  = 10,
  %
  thumbindex@topmargin .code:n =
    {
      \str_if_eq:nnTF {#1} {auto}
        { \bool_set_false:N \l_@@_custom_thumbindex_topmargin_set_bool }
        {
          \dim_set:Nn \l_@@_custom_thumbindex_topmargin_dim {#1}
          \bool_set_true:N \l_@@_custom_thumbindex_topmargin_set_bool
        }
    },
  thumbindex@topmargin .initial:n = auto,
  %
  thumbindex@bottommargin .code:n =
    {
      \str_if_eq:nnTF {#1} {auto}
        { \bool_set_false:N \l_@@_custom_thumbindex_bottommargin_set_bool }
        {
          \dim_set:Nn \l_@@_custom_thumbindex_bottommargin_dim {#1}
          \bool_set_true:N \l_@@_custom_thumbindex_bottommargin_set_bool
        }
    },
  thumbindex@bottommargin .initial:n = auto,
  %
  thumbindex@width     .dim_set:N  = \l_@@_custom_thumbindex_width_dim,
  thumbindex@width .initial:n  = 1.2cm,
  %
  thumbindex@orientation .choice:,
  thumbindex@orientation / outwards .code:n =
    \int_zero:N \l_@@_custom_thumbindex_rotation_int,
  thumbindex@orientation / inwards .code:n =
    \int_set:Nn \l_@@_custom_thumbindex_rotation_int {180},
  thumbindex@orientation .initial:n = outwards,
  thumbindex@orientation .value_required:n = true,
  %
  thumbindex@font .tl_set:N = \l_@@_custom_thumbindex_font_tl,
  thumbindex@font .initial:n = \bfseries\Huge,
  % \paragraph{Bibliography keys}
  % |emphasizeAuthors| controls the bold-name mechanism.  When true (the
  % default), it marks every PI's name in bold across all bibliography and
  % citation lists.
  % |emphasizeEntries| independently bolds entire bibliography entries with
  % the current project ID plus |-highlight| in project lists, or with
  % |frametext-highlight| in the frame-text list.
  % CV and proposal bibliography styles and features are stored separately.
  %
  doiAPIMail                  .tl_set:N  = \l_@@_custom_doi_api_mail_tl,
  doiAPIMail                  .initial:n = {},
  %
  emphasizeAuthors           .bool_set:N = \l_@@_custom_emphasize_authors_bool,
  emphasizeAuthors           .initial:n  = true,
  emphasizeEntries           .bool_set:N = \l_@@_custom_emphasize_entries_bool,
  emphasizeEntries           .initial:n  = false,
  % Select the printed field without changing the stored bibliography data.
  journalTitle .choice:,
  journalTitle / journaltitle .code:n =
    \tl_set:Nn \l_@@_custom_journal_title_tl {journaltitle},
  journalTitle / shortjournal .code:n =
    \tl_set:Nn \l_@@_custom_journal_title_tl {shortjournal},
  journalTitle .initial:n = journaltitle,
  journalTitle .value_required:n = true,
  %
  biblatexstyleCV                 .tl_set:N  = \l_@@_custom_biblatexstyle_cv_tl,
  biblatexstyleCV                 .initial:n = ext-numeric-comp,
  biblatexstyleFeatureCV          .tl_set:N  = \l_@@_custom_biblatexfeatures_cv_tl,
  biblatexstyleFeatureCV          .initial:n = {sorting=none},
  biblatexstyleProposal           .tl_set:N  = \l_@@_custom_biblatexstyle_proposal_tl,
  biblatexstyleProposal           .initial:n = ext-authoryear-ecomp,
  biblatexstyleFeatureProposal    .tl_set:N  = \l_@@_custom_biblatexfeatures_proposal_tl,
  biblatexstyleFeatureProposal    .initial:n = {},
  % Compatibility: the former keys apply the supplied value to both modes.
  biblatexstyle .code:n =
    {
      \tl_set:Nn \l_@@_custom_biblatexstyle_cv_tl       {#1}
      \tl_set:Nn \l_@@_custom_biblatexstyle_proposal_tl {#1}
    },
  biblatexstyleFeature .code:n =
    {
      \tl_set:Nn \l_@@_custom_biblatexfeatures_cv_tl       {#1}
      \tl_set:Nn \l_@@_custom_biblatexfeatures_proposal_tl {#1}
    },
  % \paragraph{Colour keys}
  % All colour keys store a colour \emph{name} referencing an already-defined
  % xcolor colour (e.g.\ |blue-50|, |black-10|).  Actual \cs{colorlet}
  % bindings happen in \cs{AtBeginDocument} so preamble overrides are
  % processed first.  Groups: |color@gantt@*| for the five bar styles;
  % |color@table@*| for all table chrome; |color@thumbindex@*| for the
  % thumb tab; |color@tags@*| for the showtags debug annotations.
  %
  color@reference@boldAuthor .tl_set:N   = \l_@@_custom_referenceBoldAuthor_tl,
  color@reference@boldAuthor .initial:n  = black,
  color@reference@PI .tl_set:N           = \l_@@_custom_referencePI_tl,
  color@reference@PI .initial:n          = black,
  color@reference@WP .tl_set:N           = \l_@@_custom_referenceWP_tl,
  color@reference@WP .initial:n          = black,
  color@reference@Aim .tl_set:N          = \l_@@_custom_referenceAim_tl,
  color@reference@Aim .initial:n         = black,

  color@gantt@frame      .tl_set:N    = \l_@@_custom_gantt_frame_tl,
  color@gantt@frame      .initial:n = {white},
  color@gantt@default    .tl_set:N    =\l_@@_custom_gantt_default_tl,
  color@gantt@default    .initial:n = {blue-25},
  color@gantt@alternative    .tl_set:N    =\l_@@_custom_gantt_alternative_tl,
  color@gantt@alternative    .initial:n = {green-25},
  color@gantt@crosshatch .tl_set:N    = \l_@@_custom_gantt_crosshatch_tl,
  color@gantt@crosshatch .initial:n = {black-10},
  color@gantt@important  .tl_set:N    = \l_@@_custom_gantt_important_tl,
  color@gantt@important  .initial:n = {red},
  color@gantt@stripe-one .tl_set:N    = \l_@@_custom_gantt_stripe_one_tl,
  color@gantt@stripe-one .initial:n = {blue-25},
  color@gantt@stripe-two .tl_set:N    = \l_@@_custom_gantt_stripe_two_tl,
  color@gantt@stripe-two .initial:n = {green-25},

  color@table@headingsBG     .tl_set:N   = \l_@@_custom_tableHeadingsBG_tl,
  color@table@headingsBG     .initial:n  = blue-50,
  color@table@headingsBGalt  .tl_set:N   = \l_@@_custom_tableHeadingsBGalt_tl,
  color@table@headingsBGalt  .initial:n  = black-25,
  color@table@headingsFont   .tl_set:N   = \l_@@_custom_tableHeadingsFont_tl,
  color@table@headingsFont   .initial:n  = black,
  color@table@rows           .tl_set:N   = \l_@@_custom_tableRows_tl,
  color@table@rows           .initial:n  = black-10,
  color@table@lines          .tl_set:N   = \l_@@_custom_tableLines_tl,
  color@table@lines          .initial:n  = black-10,
  color@table@outerLines     .tl_set:N   = \l_@@_custom_tableOuterLines_tl,
  color@table@outerLines     .initial:n  = black,
  color@table@noValue        .tl_set:N   = \l_@@_custom_tableNoValue_tl,
  color@table@noValue        .initial:n  = black-10,
  color@table@firstColumn    .tl_set:N   = \l_@@_custom_tableFirstColumn_tl,
  color@table@firstColumn    .initial:n  = black,
  color@table@link           .tl_set:N   = \l_@@_custom_tableLink_tl,
  color@table@link           .initial:n = black,
  color@table@contFootHead   .tl_set:N  = \l_@@_custom_tableContFootHead_tl,
  color@table@contFootHead   .initial:n = black,
  color@table@caption        .tl_set:N  = \l_@@_custom_tableCaption_tl,
  color@table@caption        .initial:n = black,
  color@thumbindex@bg        .tl_set:N  = \l_@@_custom_thumbIndexBG_tl,
  color@thumbindex@bg        .initial:n = black,
  color@thumbindex@font      .tl_set:N  = \l_@@_custom_thumbIndexFont_tl,
  color@thumbindex@font      .initial:n = white,
  color@tags@font            .tl_set:N  = \l_@@_custom_colorTagsFont_tl,
  color@tags@font            .initial:n = red-100,
  color@tags@line            .tl_set:N  = \l_@@_custom_colorTagsLine_tl,
  color@tags@line            .initial:n = black-50,
  % The alternative font color which is used e.g. for the CV headline.
  color@font@alternative     .tl_set:N  = \l_@@_custom_colorfontalternative_tl,
  color@font@alternative     .initial:n = black-50,

  color@item@i               .tl_set:N  = \l_@@_custom_color_item_i_tl,
  color@item@i               .initial:n = black,
  % That’s it with the key-values.
}
%    \end{macrocode}
% Bibliography package options must be fixed before \pkg{biblatex} is loaded.
% Consequently the customization file is read here, after all custom keys have
% been declared but before package loading.  It is not read a second time at the
% end of the class.
%    \begin{macrocode}
\NewDocumentCommand{\changeSettings}{m}
  { \keys_set:nn { dfg / custom } {#1} }
% Compatibility alias for proposals created before the command was pluralised.
\NewDocumentCommand{\changeSetting}{m}
  { \changeSettings{#1} }
%    \end{macrocode}
% Read live storage, not cached input: typed values are normalised, grouped
% changes unwind, and internal overrides remain visible. Keep the registry
% in sync with all public keys in |dfg/custom|.
%    \begin{macrocode}
\prop_const_from_keyval:Nn \c_@@_custom_getters_prop
  {
    font = { \tl_use:N \l_@@_custom_font_tl },
    fontspec = { \tl_use:N \l_@@_custom_fontspec_tl },
    sansfont = { \tl_use:N \l_@@_custom_sansfont_tl },
    sansfontspec = { \tl_use:N \l_@@_custom_sansfontspec_tl },
    crcLogoPath = { \tl_use:N \l_@@_custom_crc_logo_path_tl },
    affiliationLogoPath = { \tl_use:N \l_@@_custom_affiliation_logo_path_tl },
    projectPIOncePerSection = { \bool_if:NTF \l_@@_custom_project_pi_once_per_section_bool {true} {false} },
    PIReferenceFirstName = { \bool_if:NTF \l_@@_custom_pi_reference_firstname_bool {true} {false} },
    projectsTableInstitutionAbbreviations = { \bool_if:NTF \l_@@_custom_projects_table_institution_abbreviations_bool {true} {false} },
    categoryAbbreviations = { \bool_if:NTF \l_@@_custom_category_abbreviations_bool {true} {false} },
    cvTableAfterSkip = { \dim_eval:n {\l_@@_custom_cv_table_after_skip_tl} },
    plotOptions = { \tl_use:N \l_@@_custom_plot_options_tl },
    ganttPlotOptions = { \tl_use:N \l_@@_custom_gantt_plot_options_tl },
    collaborationPlotOptions = { \tl_use:N \l_@@_custom_collaboration_plot_options_tl },
    projectTitle = {
      toc=\tl_use:N \l_@@_custom_project_title_toc_tl,
      runningHead=\tl_use:N \l_@@_custom_project_title_runningHead_tl,
      projectStart=\tl_use:N \l_@@_custom_project_title_projectStart_tl
    },
    PIcontactStyle = { \tl_use:N \l_@@_custom_pi_contact_style_tl },
    collaborationAreaColors = { \tl_use:N \l_@@_custom_collaboration_area_colors_tl },
    salary@prof = { \fp_use:N \l_@@_custom_salary_prof_fp },
    salary@groupLeader = { \fp_use:N \l_@@_custom_salary_group_leader_fp },
    salary@postDoc = { \fp_use:N \l_@@_custom_salary_postdoc_fp },
    salary@medDoc = { \fp_use:N \l_@@_custom_salary_meddoc_fp },
    salary@PhD = { \fp_use:N \l_@@_custom_salary_phd_fp },
    salary@research = { \fp_use:N \l_@@_custom_salary_research_fp },
    salary@nonResearch = { \fp_use:N \l_@@_custom_salary_nonresearch_fp },
    salary@student = { \fp_use:N \l_@@_custom_salary_student_fp },
    salary@assistant = { \fp_use:N \l_@@_custom_salary_assistant_fp },
    animalHousing@mouse = { \fp_use:N \l_@@_custom_animal_mouse_fp },
    animalHousing@mouseGnotobiotic = { \fp_use:N \l_@@_custom_animal_mouse_gnotobiotic_fp },
    animalHousing@rat = { \fp_use:N \l_@@_custom_animal_rat_fp },
    thumbindex = { \bool_if:NTF \l_@@_custom_thumbindex_bool {true} {false} },
    thumbindex@pattern = { \int_use:N \l_@@_custom_thumbindexpattern_int },
    thumbindex@width = { \dim_use:N \l_@@_custom_thumbindex_width_dim },
    thumbindex@font = { \tl_use:N \l_@@_custom_thumbindex_font_tl },
    doiAPIMail = { \tl_use:N \l_@@_custom_doi_api_mail_tl },
    emphasizeAuthors = { \bool_if:NTF \l_@@_custom_emphasize_authors_bool {true} {false} },
    emphasizeEntries = { \bool_if:NTF \l_@@_custom_emphasize_entries_bool {true} {false} },
    journalTitle = { \tl_use:N \l_@@_custom_journal_title_tl },
    biblatexstyleCV = { \tl_use:N \l_@@_custom_biblatexstyle_cv_tl },
    biblatexstyleFeatureCV = { \tl_use:N \l_@@_custom_biblatexfeatures_cv_tl },
    biblatexstyleProposal = { \tl_use:N \l_@@_custom_biblatexstyle_proposal_tl },
    biblatexstyleFeatureProposal = { \tl_use:N \l_@@_custom_biblatexfeatures_proposal_tl },
    color@reference@boldAuthor = { \tl_use:N \l_@@_custom_referenceBoldAuthor_tl },
    color@reference@PI = { \tl_use:N \l_@@_custom_referencePI_tl },
    color@reference@WP = { \tl_use:N \l_@@_custom_referenceWP_tl },
    color@reference@Aim = { \tl_use:N \l_@@_custom_referenceAim_tl },
    color@gantt@frame = { \tl_use:N \l_@@_custom_gantt_frame_tl },
    color@gantt@default = { \tl_use:N \l_@@_custom_gantt_default_tl },
    color@gantt@alternative = { \tl_use:N \l_@@_custom_gantt_alternative_tl },
    color@gantt@crosshatch = { \tl_use:N \l_@@_custom_gantt_crosshatch_tl },
    color@gantt@important = { \tl_use:N \l_@@_custom_gantt_important_tl },
    color@gantt@stripe-one = { \tl_use:N \l_@@_custom_gantt_stripe_one_tl },
    color@gantt@stripe-two = { \tl_use:N \l_@@_custom_gantt_stripe_two_tl },
    color@table@headingsBG = { \tl_use:N \l_@@_custom_tableHeadingsBG_tl },
    color@table@headingsBGalt = { \tl_use:N \l_@@_custom_tableHeadingsBGalt_tl },
    color@table@headingsFont = { \tl_use:N \l_@@_custom_tableHeadingsFont_tl },
    color@table@rows = { \tl_use:N \l_@@_custom_tableRows_tl },
    color@table@lines = { \tl_use:N \l_@@_custom_tableLines_tl },
    color@table@outerLines = { \tl_use:N \l_@@_custom_tableOuterLines_tl },
    color@table@noValue = { \tl_use:N \l_@@_custom_tableNoValue_tl },
    color@table@firstColumn = { \tl_use:N \l_@@_custom_tableFirstColumn_tl },
    color@table@link = { \tl_use:N \l_@@_custom_tableLink_tl },
    color@table@contFootHead = { \tl_use:N \l_@@_custom_tableContFootHead_tl },
    color@table@caption = { \tl_use:N \l_@@_custom_tableCaption_tl },
    color@thumbindex@bg = { \tl_use:N \l_@@_custom_thumbIndexBG_tl },
    color@thumbindex@font = { \tl_use:N \l_@@_custom_thumbIndexFont_tl },
    color@tags@font = { \tl_use:N \l_@@_custom_colorTagsFont_tl },
    color@tags@line = { \tl_use:N \l_@@_custom_colorTagsLine_tl },
    color@font@alternative = { \tl_use:N \l_@@_custom_colorfontalternative_tl },
    color@item@i = { \tl_use:N \l_@@_custom_color_item_i_tl },
    dfgLocation = { \dfgLocation },
    dfgDate = { \dfgDate },
    dfgTitle = { \dfgTitle },
    InfoTeX = { \InfoTeX },
    collaborationAreaPalette = { \tl_use:N \l_@@_custom_collaboration_area_palette_tl },
    thumbindex@topmargin = { \bool_if:NTF \l_@@_custom_thumbindex_topmargin_set_bool { \dim_use:N \l_@@_custom_thumbindex_topmargin_dim } {auto} },
    thumbindex@bottommargin = { \bool_if:NTF \l_@@_custom_thumbindex_bottommargin_set_bool { \dim_use:N \l_@@_custom_thumbindex_bottommargin_dim } {auto} },
    thumbindex@orientation = { \int_compare:nNnTF {\l_@@_custom_thumbindex_rotation_int} = {0} {outwards} {inwards} },
    biblatexstyle = { \bool_if:NTF \l_@@_class_cv_bool {\tl_use:N \l_@@_custom_biblatexstyle_cv_tl} {\tl_use:N \l_@@_custom_biblatexstyle_proposal_tl} },
    biblatexstyleFeature = { \bool_if:NTF \l_@@_class_cv_bool {\tl_use:N \l_@@_custom_biblatexfeatures_cv_tl} {\tl_use:N \l_@@_custom_biblatexfeatures_proposal_tl} }
  }
\msg_new:nnn { dfg } { unknown-customization-value }
  { Unknown~customization~key~'#1'~in~\string\getValue.
    ~Use~a~key~supported~by~\string\changeSettings. }
\cs_new:Npn \@@_get_custom_value:n #1
  {
    \prop_if_in:NnTF \c_@@_custom_getters_prop {#1}
      { \exp_args:Ne \use:n { \prop_item:Nn \c_@@_custom_getters_prop {#1} } }
      { \msg_expandable_error:nnn {dfg} {unknown-customization-value} {#1} }
  }
\NewExpandableDocumentCommand \getValue { m }
  { \exp_args:Ne \@@_get_custom_value:n { \tl_trim_spaces:n {#1} } }
% Compatibility accessors retained for the funding and animal-cost code.
\NewExpandableDocumentCommand{\dfgSalaryProf}{}
  { \fp_use:N \l_@@_custom_salary_prof_fp }
\NewExpandableDocumentCommand{\dfgSalaryGroupLeader}{}
  { \fp_use:N \l_@@_custom_salary_group_leader_fp }
\NewExpandableDocumentCommand{\dfgSalaryPostDoc}{}
  { \fp_use:N \l_@@_custom_salary_postdoc_fp }
\NewExpandableDocumentCommand{\dfgSalaryMedDoc}{}
  { \fp_use:N \l_@@_custom_salary_meddoc_fp }
\NewExpandableDocumentCommand{\dfgSalaryPhD}{}
  { \fp_use:N \l_@@_custom_salary_phd_fp }
\NewExpandableDocumentCommand{\dfgSalaryResearch}{}
  { \fp_use:N \l_@@_custom_salary_research_fp }
\NewExpandableDocumentCommand{\dfgSalaryNonResearch}{}
  { \fp_use:N \l_@@_custom_salary_nonresearch_fp }
\NewExpandableDocumentCommand{\dfgSalaryStudent}{}
  { \fp_use:N \l_@@_custom_salary_student_fp }
\NewExpandableDocumentCommand{\dfgSalaryAssistant}{}
  { \fp_use:N \l_@@_custom_salary_assistant_fp }
\NewExpandableDocumentCommand{\dfgMouseHousing}{}
  { \fp_use:N \l_@@_custom_animal_mouse_fp }
\NewExpandableDocumentCommand{\dfgMouseHousingGnotobiotic}{}
  { \fp_use:N \l_@@_custom_animal_mouse_gnotobiotic_fp }
\NewExpandableDocumentCommand{\dfgRatHousing}{}
  { \fp_use:N \l_@@_custom_animal_rat_fp }
%    \end{macrocode}
% \subsection{Laboratory-animal types}
% The registry is available before loading the customization file.  Its
% assignments follow ordinary TeX grouping, like \cs{changeSettings}.
% Built-in housing rates retain their original floating-point registers;
% declarations and the legacy settings therefore share one source of truth.
% Group IDs name a registered type whose plural label is used for the total.
% They are grouping buckets, not an inheritance chain.
%    \begin{macrocode}
\msg_new:nnn { dfg } { animal-type-invalid }
  { Animal~type~'#1':~#2.~The~declaration~is~ignored. }
\msg_new:nnn { dfg } { animal-row-invalid }
  { Animal~table~'#1',~project~'#2':~#3.~Unavailable~numbers~
    are~shown~as~dashes;~totals~omitting~them~are~marked~incomplete. }
\msg_new:nnn { dfg } { animal-total-incomplete }
  { Animal~table~'#1':~the~total~for~'#2'~is~incomplete.~
    Only~supplied,~valid~values~are~summed. }
\prop_new:N \l_@@_animal_types_prop
\seq_new:N \l_@@_animal_type_ids_seq
\tl_new:N \l_@@_animal_id_tl
\tl_new:N \l_@@_animal_label_tl
\tl_new:N \l_@@_animal_plural_tl
\tl_new:N \l_@@_animal_group_tl
\tl_new:N \l_@@_animal_rate_tl
\tl_new:N \l_@@_animal_rate_value_tl
\bool_new:N \l_@@_animal_declaration_valid_bool
\keys_define:nn { dfg / animal-type }
  {
    label        .tl_set:N = \l_@@_animal_label_tl,
    label        .value_required:n = true,
    label-plural .tl_set:N = \l_@@_animal_plural_tl,
    label-plural .value_required:n = true,
    total-group  .tl_set:N = \l_@@_animal_group_tl,
    total-group  .value_required:n = true,
    housing-rate .tl_set:N = \l_@@_animal_rate_tl,
    housing-rate .value_required:n = true,
    unknown .code:n =
      {
        \msg_warning:nnee {dfg}{animal-type-invalid}
          {\l_@@_animal_id_tl}{unknown~key~'\l_keys_key_str'}
        \bool_set_false:N \l_@@_animal_declaration_valid_bool
      }
  }
\cs_new_protected:Npn \@@_animal_type_get:nnN #1#2#3
  {
    \prop_get:NeNTF \l_@@_animal_types_prop {#1/#2} #3
      {} { \tl_clear:N #3 }
  }
\cs_new_protected:Npn \@@_animal_type_reject:n #1
  {
    \msg_warning:nnee {dfg}{animal-type-invalid}
      {\l_@@_animal_id_tl}{#1}
    \bool_set_false:N \l_@@_animal_declaration_valid_bool
  }
\NewDocumentCommand \DeclareAnimalType { m m }
  {
    \tl_set:Ne \l_@@_animal_id_tl { \tl_trim_spaces:n {#1} }
    \bool_set_true:N \l_@@_animal_declaration_valid_bool
    \@@_animal_type_get:nnN {\l_@@_animal_id_tl}{label}
      \l_@@_animal_label_tl
    \@@_animal_type_get:nnN {\l_@@_animal_id_tl}{label-plural}
      \l_@@_animal_plural_tl
    \@@_animal_type_get:nnN {\l_@@_animal_id_tl}{housing-rate}
      \l_@@_animal_rate_tl
    \@@_animal_type_get:nnN {\l_@@_animal_id_tl}{total-group}
      \l_@@_animal_group_tl
    \tl_if_blank:VT \l_@@_animal_group_tl
      { \tl_set_eq:NN \l_@@_animal_group_tl \l_@@_animal_id_tl }
    \keys_set:nn { dfg / animal-type } {#2}
    \tl_trim_spaces:N \l_@@_animal_group_tl
    \exp_args:NnV \regex_match:nnF
      {\A [a-z] [a-z0-9-]* \Z} \l_@@_animal_id_tl
      { \@@_animal_type_reject:n {use~a~lowercase~ID~such~as~'mouse-spf'} }
    \tl_if_blank:VT \l_@@_animal_label_tl
      { \@@_animal_type_reject:n {a~nonempty~'label'~is~required} }
    \tl_if_blank:VT \l_@@_animal_plural_tl
      { \tl_set_eq:NN \l_@@_animal_plural_tl \l_@@_animal_label_tl }
    \tl_set:Ne \l_@@_animal_rate_value_tl { \l_@@_animal_rate_tl }
    \tl_trim_spaces:N \l_@@_animal_rate_value_tl
    \exp_args:NnV \regex_match:nnF
      {\A \d+ (?: \. \d+ )? \Z} \l_@@_animal_rate_value_tl
      { \@@_animal_type_reject:n
          {'housing-rate'~must~be~a~non-negative~number~using~a~decimal~point} }
    \tl_if_eq:NNF \l_@@_animal_id_tl \l_@@_animal_group_tl
      {
        \prop_if_in:NeF \l_@@_animal_types_prop
          {\l_@@_animal_group_tl/label}
          { \@@_animal_type_reject:n
              {declare~the~total-group~'\l_@@_animal_group_tl'~first} }
      }
    \bool_if:NT \l_@@_animal_declaration_valid_bool
      {
        \seq_if_in:NVF \l_@@_animal_type_ids_seq \l_@@_animal_id_tl
          { \seq_put_right:NV \l_@@_animal_type_ids_seq \l_@@_animal_id_tl }
        \str_case:VnF \l_@@_animal_id_tl
          {
            {mouse}
              {
                \fp_set:Nn \l_@@_custom_animal_mouse_fp
                  {\l_@@_animal_rate_value_tl}
                \tl_set:Nn \l_@@_animal_rate_tl {\dfgMouseHousing}
              }
            {mouse-gnotobiotic}
              {
                \fp_set:Nn \l_@@_custom_animal_mouse_gnotobiotic_fp
                  {\l_@@_animal_rate_value_tl}
                \tl_set:Nn \l_@@_animal_rate_tl {\dfgMouseHousingGnotobiotic}
              }
            {rat}
              {
                \fp_set:Nn \l_@@_custom_animal_rat_fp
                  {\l_@@_animal_rate_value_tl}
                \tl_set:Nn \l_@@_animal_rate_tl {\dfgRatHousing}
              }
          }
          {
            \tl_set:Ne \l_@@_animal_rate_tl
              {\fp_eval:n {\l_@@_animal_rate_value_tl}}
          }
        \prop_put:NeV \l_@@_animal_types_prop
          {\l_@@_animal_id_tl/label} \l_@@_animal_label_tl
        \prop_put:NeV \l_@@_animal_types_prop
          {\l_@@_animal_id_tl/label-plural} \l_@@_animal_plural_tl
        \prop_put:NeV \l_@@_animal_types_prop
          {\l_@@_animal_id_tl/total-group} \l_@@_animal_group_tl
        \prop_put:NeV \l_@@_animal_types_prop
          {\l_@@_animal_id_tl/housing-rate} \l_@@_animal_rate_tl
      }
  }
\DeclareAnimalType{mouse}
  {label=Mouse,label-plural=Mice,housing-rate=\dfgMouseHousing}
\DeclareAnimalType{mouse-gnotobiotic}
  {label={Mouse~{\footnotesize(gnotobiotic)}},
   label-plural={Mice~(gnotobiotic)},total-group=mouse,
   housing-rate=\dfgMouseHousingGnotobiotic}
\DeclareAnimalType{rat}
  {label=Rat,label-plural=Rats,housing-rate=\dfgRatHousing}
\bool_if:NF \l_@@_class_documentation_bool
{
\RequirePackage{dfg-timeline}
\RequirePackage{dfg-distribution}
\RequirePackage{dfg-icons}
\file_if_exist:nTF {preamble/dfg-customization.tex}
  { \ExplSyntaxOff \input{preamble/dfg-customization.tex} \ExplSyntaxOn }
  { \msg_warning:nnn { dfg } { file-not-found } {preamble/dfg-customization.tex} }
}
\bool_if:NT \l_@@_class_fastcompile_project_bool
{
  \bool_set_false:N \l_@@_custom_thumbindex_bool
  \bool_set_false:N \l_@@_custom_emphasize_authors_bool
}
%    \end{macrocode}
% \subsection{Colour binding at document start}
%
% The \cs{AtBeginDocument} hooks below transform the stored colour
% \emph{names} from the |dfg/custom| key family into live \cs{colorlet}
% aliases that the rest of the document uses.  Deferring this to
% \cs{AtBeginDocument} means the user's \cs{changeSettings} calls in
% |dfg-customization.tex| are already in force when the bindings run.
%
% The second \cs{AtBeginDocument} block handles |final|-mode side effects:
% it resets all drafting flags (both fast modes, tags, marginalia, skip-pubs)
% to |false|, enables project publications, forces the colour model to |cmyk|,
% and switches the |color@final@white-or-green| alias from green to white so
% that any placeholder boxes are invisible in the submitted PDF.
%
% Packages are loaded in an order that avoids common conflicts:
%  \pkg{xcolor} is loaded first (with the |table| option forwarded
%  beforehand) because almost every other package depends on it.
%  \pkg{tabularray} and its siunitx library are set up before
%  \pkg{hyperref}; reversing this order breaks tblr's PDF bookmark
%  integration.
%  \pkg{hyperref} and \pkg{cleveref} are always loaded last (standard
%  LaTeX best practice).
%
% The two-sided A4 layout uses a 20\,mm inner margin plus the KOMA-Script
% |BCOR| binding correction (initially 5\,mm), and a 20\,mm outer margin.
% Geometry applies |BCOR| as its binding offset, leaving a 165\,mm text block
% at the default setting.  The outer margin accommodates a 13\,mm note column
% and a 2\,mm separation from the text, with 5\,mm spare.  On verso pages,
% the binding and outer margins, notes, and thumb index all switch sides.
% The top margin is 20\,mm and the bottom margin 15\,mm, including the footer.
% A fixed 12\,mm distance from the last text baseline to the footer baseline
% leaves a 250\,mm text block.  Reserve 20\,pt for two-line project running
% heads.  The header remains outside the text block, so its height does not
% change the 20\,mm top margin or the text height.
%    \begin{macrocode}
\RequirePackage{multicol}
% Defensive definition against lineno/multicol conflict
\AtBeginDocument{%
  \@ifpackageloaded{lineno}{%
  	\providecommand*{\@LN@col}[1]{\relax}%
  }{}%
}
\RequirePackage{babel}
\RequirePackage{geometry}
\geometry{
  a4paper,
  includefoot,
  headheight     =20pt,
  footskip       =12mm,
  top            =20mm,
  bottom         =15mm,
  inner          =20mm,
  outer          =20mm,
  bindingoffset  =\ta@bcor,
  marginparsep   =2mm,
  marginparwidth =13mm,
  % showframe
}
%    \end{macrocode}
% We provide a color which is used during the writing process.
% Since there are several steps that are calculated on the fly we want to be
% able to see if they match any criteria or if there has been a wrongly inserted
% number.
% The following colors can be overwritten in the \dfgFile{dfg-customization}-file.
% Therefor we load them just before the document starts.
%    \begin{macrocode}
\AtBeginDocument{
  \selectcolormodel{\tl_use:N \l_@@_class_color_model_tl}
  \colorlet{color@item@i}{\l_@@_custom_color_item_i_tl}
  \colorlet{color@tags@font}{\l_@@_custom_colorTagsFont_tl}
  \colorlet{color@tags@line}{\l_@@_custom_colorTagsLine_tl}
  \colorlet{color@font@alternative}{\l_@@_custom_colorfontalternative_tl}
  \colorlet{color@reference@boldAuthor}{\l_@@_custom_referenceBoldAuthor_tl}
  \colorlet{tableHeadingsBG}{\l_@@_custom_tableHeadingsBG_tl}
  \colorlet{tableHeadingsBGalt}{\l_@@_custom_tableHeadingsBGalt_tl}
  \colorlet{tableHeadingsFont}{\l_@@_custom_tableHeadingsFont_tl}
  \colorlet{tableRows}{\l_@@_custom_tableRows_tl}
  \colorlet{tableLines}{\l_@@_custom_tableLines_tl}
  \colorlet{tableOuterLines}{\l_@@_custom_tableOuterLines_tl}
  \colorlet{tableNoValue}{\l_@@_custom_tableNoValue_tl}
  \colorlet{tableFirstColumn}{\l_@@_custom_tableFirstColumn_tl}
  \colorlet{tableLink}{\l_@@_custom_tableLink_tl}
  \colorlet{tableContFootHead}{\l_@@_custom_tableContFootHead_tl}
  \colorlet{tableCaption}{\l_@@_custom_tableCaption_tl}
  \colorlet{thumbIndexBG}{\l_@@_custom_thumbIndexBG_tl}
  \colorlet{thumbIndexFont}{\l_@@_custom_thumbIndexFont_tl}
  % all for the gantt chart 
  \colorlet{color@gantt@default}{\l_@@_custom_gantt_default_tl}
  \colorlet{color@gantt@alternative}{\l_@@_custom_gantt_alternative_tl}
  \colorlet{color@gantt@frame}{\l_@@_custom_gantt_frame_tl}
  \colorlet{color@gantt@crosshatch}{\l_@@_custom_gantt_crosshatch_tl}
  \colorlet{color@gantt@important}{\l_@@_custom_gantt_important_tl}
  \colorlet{color@gantt@stripe-one}{\l_@@_custom_gantt_stripe_one_tl}
  \colorlet{color@gantt@stripe-two}{\l_@@_custom_gantt_stripe_two_tl}

  % NOTE: The aliases below shadow LaTeX/xcolor standard colour names
  % (black, red, green). Any subsequently loaded package relying on the
  % standard red=RGB(255,0,0) will receive bordeaux-100 instead.
  % Consider using dfg-prefixed aliases if you load additional packages.
  \colorlet{black}{black-100}
  \colorlet{blue}{blue-100}
  \colorlet{blueLight}{blue-50}
  \colorlet{green}{green-100}
  \colorlet{greenLight}{green-50}
  \colorlet{red}{bordeaux-100}
  \colorlet{redLight}{bordeaux-50}
  \colorlet{grey}{black-50}
  \colorlet{greyLight}{black-10}

  \colorlet{projectA}{blue}
  \colorlet{projectB}{green}
  \colorlet{projectQ}{grey}
  \colorlet{error}{red}
  % Inherited reference colors are resolved at the call site. Keep the
  % concrete alias available for PI tables and other fixed-color layouts.
  \tl_if_eq:NnTF \l_@@_custom_referencePI_tl {current}
    { \colorlet{referencePI}{black} }
    { \colorlet{referencePI}{\l_@@_custom_referencePI_tl} }
  \colorlet{referenceWP}{\l_@@_custom_referenceWP_tl}
  \colorlet{referenceAim}{\l_@@_custom_referenceAim_tl}
  % Now closing the AtBeginDocument-part:
}
%    \end{macrocode}
% Once you set the flag |final| the color (green) is replaced by white so it is
% ready for submission without indicating the doublechecking aspect. If it stays
% red you should not proceed to submit the proposal.
%    \begin{macrocode}
\AtBeginDocument{
  \bool_if:NTF \l_@@_class_final_bool
  {
  	\colorlet{color@final@white-or-green}{white}
  	\bool_set_false:N \l_@@_class_showmarginalia_bool
  	\bool_set_false:N \l_@@_class_showtags_bool
    \bool_set_false:N \l_@@_class_fastcompile_bool
    \bool_set_false:N \l_@@_class_fastcompile_project_bool
    \bool_set_false:N \l_@@_class_fastcompile_project_show_images_bool
    \bool_set_true:N  \l_@@_class_fastcompile_project_show_funding_tables_bool
    \bool_set_false:N \l_@@_class_skipTENpublications_bool
    \bool_set_true:N \l_@@_class_fastcompile_project_show_publications_bool
  	\selectcolormodel{cmyk}
  }
  {
  	\colorlet{color@final@white-or-green}{green}
  }
}
%    \end{macrocode}
%    \begin{macrocode}
\RequirePackage{xspace}
\RequirePackage{etoolbox}

\RequirePackage{ragged2e}
\raggedbottom
%    \end{macrocode}
% We are getting rid of having the chapter number added to the figure number,
% same goes for tables.
%    \begin{macrocode}
\counterwithout{figure}{chapter}
\counterwithout{table}{chapter}
%    \end{macrocode}
%    \begin{macrocode}
\RequirePackage{qrcode}
\RequirePackage{graphicx}
\RequirePackage{mwe}% provides the default example-image-a/b logo placeholders
% Set the graphics mode after loading \pkg{graphicx}.  This explicitly clears
% a previously inherited draft setting when project images are requested and
% makes repeated false/true drafting builds deterministic.
\bool_if:NT \l_@@_class_fastcompile_project_bool
{
  \bool_if:NTF \l_@@_class_fastcompile_project_show_images_bool
    { \setkeys{Gin}{draft=false} }
    { \setkeys{Gin}{draft=true} }
}
\graphicspath{
  {figures/}
  {img/}
}
\RequirePackage{fontspec}
\AtBeginDocument{
  \setmainfont{\tl_use:N \l_@@_custom_font_tl}[
  	\tl_use:N \l_@@_custom_fontspec_tl
  ]
  \setsansfont{\tl_use:N \l_@@_custom_sansfont_tl}[
  	\tl_use:N \l_@@_custom_sansfontspec_tl
  ]
}

\RequirePackage{fontawesome5}
\RequirePackage{microtype}
\RequirePackage{enumitem}
% customizing bulletpoints
\providecommand{\dfgArrowHead}{\faCaretRight}
\providecommand{\dfgBulletPoint}{\faCaretRight}
\providecommand{\dfgTargetPoint}{\faBullseye}
\providecommand{\dfgDefaultPoint}{\faCaretRight}
\setlist[enumerate]{nosep}
\setlist[description]{
  %leftmargin=*,
  leftmargin=*
}
\setlist[itemize]{
  nosep,
  label={\textcolor{color@item@i}{\dfgDefaultPoint}},
}
\newlist{contractinformation}{itemize}{2}
\setlist[contractinformation,1]{
  nosep,
  leftmargin=*,
  label={\textcolor{color@item@i}{\dfgBulletPoint}},
}
\setlist[contractinformation,2]{
  nosep,
  leftmargin=*,
  label={\textcolor{color@item@i}{\dfgDefaultPoint}},
}
%    \end{macrocode}
% \subsection{Project-body list environments}
%
% \paragraph{workpackages}
% A custom enumitem list with |WP\,\arabic*:| labels at level 1 and
% |WP\,\meta{parent}\alph*:| at level 2.  The |resume| option at level 1
% means the work-package counter continues across multiple projects in the
% same document, giving each WP a globally unique number for cross-references.
% Labels are set via \pkg{cleveref} in |referenceWP| colour.  Bold face is
% scoped to the prefix and label itself so range connectors remain at the
% surrounding font weight.
%
% \paragraph{aims}
% A special |enumerate| list that automatically wraps its contents in a
% \cs{dfgBoxEnv} frame (the blue highlighted aims box).  The |before| hook
% also temporarily sets all reference colours to the table heading font
% colour so that PI/WP/Aim cross-references inside the aims box are
% visually consistent with the box style.  The |after| hook closes the box.
%    \begin{macrocode}
\newlist{workpackages}{enumerate}{3}
\setlist[workpackages,1]{
  % wide=\parindent,
  leftmargin=0cm,
  labelindent=*,
  % leftmargin=*,
  % labelindent=-3em,
  % font=\normalfont,
  % first=\bfseries,
  topsep=3pt,
  font=\bfseries,
  % nosep,
  label={WP\,\arabic*:},
  ref = {\arabic*},
  resume
}

\setlist[workpackages,2]{
  ref={\theworkpackagesi\alph*},
  %wide=\parindent,
  leftmargin=0cm,
  labelindent=*,
  % font=\normalfont,
  % first=\bfseries,
  topsep=0pt,
  font=\bfseries,
  % nosep,
  label={WP\,\theworkpackagesi\alph*:}
}
%    \end{macrocode}
% \paragraph{bylaws}
% A three-level enumitem list styled for the bylaws section of the CRC
% charter.  Level 1 uses |§\arabic*| paragraph signs; level 2 uses
% |\thebylawsi.\arabic*| for sub-paragraphs.  Both levels are set
% |nosep| to conserve vertical space.
%    \begin{macrocode}

\newlist{bylaws}{enumerate}{3}
\setlist[bylaws]{leftmargin=*}
\setlist[bylaws,1]{
  font=\bfseries,
  first=\bfseries,
  % after=\normalfont,
  label={§\arabic*},
  % itemsep=.5\baselineskip,
  nosep
}
\setlist[bylaws,2]{
  first=\normalfont,
  label={\thebylawsi.\arabic*},
  labelindent=0em,
}
%    \end{macrocode}
% A list for the aims within the projects
%    \begin{macrocode}
\newcommand{\addAim}[1]{\item\label{\l__tmp_current_project_tl-aim-#1}}
\newlist{aims}{enumerate}{1}
\setlist[aims,1]{
  before={\begin{dfgBoxEnv}%
  		[%watermark text={Aims in }
                left=0mm,right=0pt,
         colupper=blue,
  		]
  		\colorlet{referencePI}{tableHeadingsFont}
  		\colorlet{referenceWP}{tableHeadingsFont}
  		\colorlet{referenceAim}{tableHeadingsFont}},
  after={\end{dfgBoxEnv}},
  wide=\parindent,
  leftmargin=*,
  % font=\normalfont,
  % first=\bfseries,
  topsep=3pt,
  font=\bfseries,
  % nosep,
  label={Aim~ \arabic*:},
  ref = {\arabic*},
  %  resume
}
%    \end{macrocode}
% The public |label| option is a prefix, not enumitem's complete label
% format. Keep the original list and counter so existing list settings and
% numeric \cs{ref} values remain valid. A stable type per prefix prevents a
% later list from renaming earlier references. Store its name in the aux file
% so cleveref knows it before constructing formats and forward references on
% the next run. Other enumitem options pass through unchanged.
% Expand the label explicitly: older expl3 releases provide the hash
% function without its V variant.
%    \begin{macrocode}
\tl_new:N \l_@@_aim_label_tl
\tl_new:N \l_@@_aim_options_tl
\tl_new:N \l_@@_aim_type_tl
\keys_define:nn { dfg / aims }
{
  label .tl_set:N = \l_@@_aim_label_tl,
  label .value_required:n = true,
}
\NewCommandCopy\dfgOriginalAims\aims
\NewCommandCopy\dfgOriginalEndAims\endaims
\cs_new_protected:Npn \@@_aims_begin:n #1
  { \dfgOriginalAims[#1] }
\RenewDocumentEnvironment{aims}{ O{} }
{
  \tl_set:Nn \l_@@_aim_label_tl { \q_no_value }
  \keys_set_known:nnN { dfg / aims } {#1} \l_@@_aim_options_tl
  \quark_if_no_value:NF \l_@@_aim_label_tl
  {
    \tl_set:Ne \l_@@_aim_type_tl
      { dfg-aim-\exp_args:NV \str_mdfive_hash:n \l_@@_aim_label_tl }
    \exp_args:NnV \crefalias { aimsi } \l_@@_aim_type_tl
    \protected@write\@auxout{}
    {
      \string\dfgAimReferenceName
        {\l_@@_aim_type_tl}{\exp_not:V \l_@@_aim_label_tl}
    }
    \tl_put_left:Ne \l_@@_aim_options_tl
    {
      label={\exp_not:V \l_@@_aim_label_tl
        \exp_not:n {~\arabic*:}},
      \exp_not:n {ref={\arabic*},}
    }
  }
  \exp_args:NV \@@_aims_begin:n \l_@@_aim_options_tl
}
{ \dfgOriginalEndAims }
%    \end{macrocode}
% \subsection{Page style (headers and footers)}
%
% The page style uses \pkg{scrlayer-scrpage} with a minimal layout:
%  The outer footer shows the page number in bold sans-serif.
%   The inner footer shows the CRC logo (\cs{crcLogo}) at 0.5\,cm
%   height — this places the logo on every page of the proposal for
%   visual identification without cluttering the headers.
%   Both header and footer use \cs{markcase=noupper} so section
%   titles are not forced to uppercase in running heads.
% \cs{footheight} is set explicitly to suppress the \pkg{scrlayer-scrpage}
% warning about an undersized footer layer.
%    \begin{macrocode}
\RequirePackage[
  %headsepline=.5pt,
  markcase=noupper,
  %footsepline,
  autooneside=false, % use left and right marks with a onesided document
  %automark, % set \ leftmark and \ rightmark automatically by \ section and \ subsection
  draft=false,
]{scrlayer-scrpage}
%    \end{macrocode}
% First we clear any presettings so we can apply our own style.
%    \begin{macrocode}
\clearmainofpairofpagestyles
\pagestyle{scrheadings}
\setlength{\footheight}{17.5264pt}
\renewcommand{\chaptermarkformat}{}
\renewcommand{\sectionmarkformat}{}
\ofoot*{\pagemark}%Clear the outer foot
\ifoot*{\crcLogo[height=0.5cm]}%pagemark in the center only on plain pages
\addtokomafont{pagehead}{\normalfont\sffamily}
\addtokomafont{pagefoot}{\bfseries}
% Mark every shipped page of an aggressive project draft without adding a
% package-level watermark dependency.  The native background hook keeps the
% mark behind authored text and is registered only after final-mode precedence
% has been resolved.
\bool_if:NT \l_@@_class_fastcompile_project_bool
{
  \AddToHook{shipout/background}[dfg/fastcompile-project-watermark]
  {
    \put(0.5\paperwidth,-0.5\paperheight)
    {
      \makebox(0,0)
      {
        \rotatebox{45}
        {
          \textcolor{black!7}
          {
            \sffamily\bfseries\fontsize{100}{50}\selectfont
            FAST~COMPILE
          }
        }
      }
    }
  }
}
%    \end{macrocode}
% Remodelling the footnotes for more pleasant display
%    \begin{macrocode}
\deffootnote{0em}{0em}{\thefootnotemark\hskip .5em}
\renewcommand{\footnoterule}{%
  % \kern -4.5pt
  % \hrule width \textwidth height 0.5pt
  % \kern 4pt
}
%    \end{macrocode}
% \subsection{Heading fonts (KOMA-Script customisation)}
%
% All heading sizes and weights are re-declared here to achieve a compact,
% dense layout that conserves space on the tightly page-budgeted DFG forms:
%  |disposition| applies |\normalfont\sffamily\bfseries|, giving all
%  heading levels a shared bold sansserif base before selecting their size.
%  Chapter headings (section dividers) are set at 20\,pt bold to
%  stand out without the very large spacing of \cs{Huge}.
%  Sections use 12\,pt bold type; subsections and subsubsections use
%  11\,pt type for a compact hierarchy.
%  Section, subsection, and subsubsection headings have one baseline of
%  space above them. Body text starts on the next line with no additional
%  after-skip or first-line indent; zero after-skip does not make a run-in heading.
%  The first paragraph gap after a displayed heading is rigid. A paragraph hook
%  cancels the inserted skip and replaces it with its natural dimension while
%  KOMA's no-break flag still marks the heading context. This also covers starred
%  headings and chapters without changing subsequent paragraph gaps or the
%  paragraph settings inside table cells. The cancelling skip must retain the
%  complete glue components; using only its natural dimension would leave the
%  original stretch and shrink in place.
%  Numbered section and subsection titles use the same 12\,mm number column,
%  so the title text begins at one horizontal position throughout the project
%  information block.  This also gives wrapped titles a matching hang indent.
% The TOC is configured to omit chapter page numbers (they would be
% meaningless given the DFG form structure) and to show section entries
% with a dash-style page separator.  Project TOC entries deliberately use only
% their compact project number, so the fixed number column remains narrow and
% ordinary section titles are not pushed unnecessarily far to the right.
%    \begin{macrocode}
\setkomafont{title}{\Huge\bfseries}
% \setkomafont{disposition}{\normalfont}
\setkomafont{disposition}{\normalfont\sffamily\bfseries}
\setkomafont{descriptionlabel}{\normalfont\bfseries}
%\setkomafont{chapter}{\huge\bfseries}
%\setkomafont{section}{\normalsize\bfseries}
%\setkomafont{subsection}{\normalsize}
%\setkomafont{subsubsection}{\normalsize}
\setkomafont{chapter}{\fontsize{20}{10}\selectfont\bfseries}
\setkomafont{section}{\fontsize{12}{10}\selectfont\bfseries}
\setkomafont{subsection}{\fontsize{11}{11}\selectfont}
\setkomafont{subsubsection}{\fontsize{11}{11}\selectfont}
\renewcommand*{\chapterformat}{\makebox[12mm][l]{\thechapter\autodot}}
\renewcommand*{\sectionformat}{\makebox[12mm][l]{\thesection\autodot}}
\renewcommand*{\subsectionformat}{\makebox[12mm][l]{\thesubsection\autodot}}
\setkomafont{footnotenumber}{\normalfont\sffamily}
\setkomafont{pageheadfoot}{\normalfont\footnotesize\sffamily}
\skip_new:N \l_@@_heading_parskip_skip
\AddToHook{para/before}[dfg/fixed-heading-gap]
{
  \if@nobreak
    \skip_set:Nn \l_@@_heading_parskip_skip {\lastskip}
    \skip_vertical:n {-\l_@@_heading_parskip_skip}
    \skip_vertical:n {\dim_eval:n {\l_@@_heading_parskip_skip}}
  \fi
}
%    \end{macrocode}
% Adjusting the style for the table of contents.
% First we want to have the normalfont for the chapter entries
%    \begin{macrocode}
\addtokomafont{chapterentry}{\normalfont}
%    \end{macrocode}
%    \begin{macrocode}
\RedeclareSectionCommands[
  font=\usekomafont{subsection},
  % beforeskip=1pt,
  % afterskip=.5pt
]{subsubsection}

\RedeclareSectionCommands[
  tocraggedpagenumber,
  toclinefill=\tocpageseparator,
  tocindent=0em,
  tocnumwidth=4em,
  tocpagenumberbox=\tocpagenumberbox,% <- added
  % tocpagenumberformat=\textsf,
  beforeskip= 1\baselineskip,
  afterskip= 0pt,
  runin=false,
  afterindent=false
]{section,subsection,subsubsection}

\RedeclareSectionCommands[
  tocbeforeskip=2ex,
  tocentryformat=\bfseries\large,
]{section}

\newcommand\tocgobble[1]{}% <- added
\newcommand\tocpageseparator{\normalsize\bfseries\,\mbox{\color{\l_@@_custom_tableLines_tl}---}\,}
\newcommand\tocpagenumberbox[1]{\mbox{#1}}% <- added
% no page number for chapters in TOC
\RedeclareSectionCommands[
  tocraggedpagenumber,
  toclinefill           =\tocgobble,
  tocindent             =0em,
  tocnumwidth           =4em,
  tocpagenumberbox      =\tocgobble,% <- added
  % tocpagenumberformat =\textsf,
  beforeskip            = 0ex,
  afterskip             =0.1ex,
  tocentryformat        =\bfseries\Large\sffamily,
]{chapter}
%    \end{macrocode}
% the depth of chapter is configurable,
% so using this is instead of a absolute
% number is recommended
%    \begin{macrocode}
\setcounter{secnumdepth}{\subsectiontocdepth}
\setcounter{tocdepth}{\subsectiontocdepth}
%    \end{macrocode}
% \subsection{ORCiD display commands}
%
% Two commands render ORCiD identifiers:
% \begin{description}
%   \item[\cs{ORCiD}\marg{0000-0000-0000-0000}] Inline use: renders
%         the ORCiD icon followed by the ID as a hyperlink.
%         Intended for manual insertion in text.
%   \item[\cs{getORCiD}\oarg{db}\marg{id}] Database-driven use: looks up
%         the |orcid| field from the |person| database for the given person
%         ID and renders \cs{ORCiD} automatically.  If the field is missing,
%         a |missing-orcid| warning is raised instead of silently omitting
%         the identifier.  The warning is suppressed during the tabularray
%         measuring pass (\cs{lTblrMeasuringBool}) to avoid duplicates.
% \end{description}
% The ORCiD brand green (|orcid| colour) is defined in the colour palette
% section above.  The icon uses the \pkg{academicons} \cs{aiOrcid} glyph.
%    \begin{macrocode}
\RequirePackage{pifont}
\RequirePackage{academicons}
% =============================================================================
% ORCiD commands
% =============================================================================

% Store the ORCiD value pulled from the database.
\providecommand{\theORCiDValue}{}

% --- Icon ---------------------------------------------------------------------
\NewDocumentCommand{\orcidIcon}{}
{{\sffamily\textcolor{orcid}{\aiOrcid}}}

% --- Pure value-only lookup (no immediate output) ---------------------------
% Fetch the ORCiD value from the database into \theORCiDValue.
% Useful when the value has already been loaded by a previous multi-fetch step,
% or when formatting is needed later.
\NewDocumentCommand{\getORCiDvalue}{O{person} m}
{%
  % #1: Database (default is person)
  % #2: Person id
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \cs_set:Npn \theORCiDValue { } }
  { \DTLgetvalueforkey{\theORCiDValue}{orcid}{#1}{id}{#2} }%
}

% --- Formatting a preloaded ORCiD value ------------------------------------
% Expects \theORCiDValue to be set (for example via \getORCiDvalue or
% per \getEntry*[...]{id}{\theORCiDValue=orcid, ...}).
\NewDocumentCommand{\formatORCiD}{O{person} m}
{%
  % #1: Database (for warnings / tag overlay)
  % #2: Person id (for warnings / tag overlay)
  \DTLifnullorempty{\theORCiDValue}
  {%
  	\bool_if:NF \lTblrMeasuringBool
  	{ \msg_warning:nnee {dfg}{missing-orcid}{#1}{#2} }%
  	\mbox{~} % if no orcid present
  }
  {%
  	\orcidIcon\,%
  	\dfgShowTag{#2}{orcid}
  	{\href{https://orcid.org/\theORCiDValue}{\theORCiDValue}}[#1]%
  }%
}

% --- Convenience command: fetch + format in a single call -------------------
% Keep the same API as the original \getORCiD so existing calls continue
% to work.
\NewDocumentCommand{\getORCiD}{O{person} m}
{%
  % #1: Database (default is person)
  % #2: Person id
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \getORCiDvalue[#1]{#2}%
    \formatORCiD[#1]{#2}%
  }
}

% --- Inline variant for literal ORCiD values --------------------------------
% For direct values without database lookup.
\NewDocumentCommand{\ORCiD}{m}
{(\raisebox{-1pt}{\orcidIcon}\,\href{https://orcid.org/#1}{#1})}
%    \end{macrocode}
% \subsection{siunitx configuration}
%
% \pkg{siunitx} options must be forwarded with \cs{PassOptionsToPackage}
% \emph{before} the package is implicitly loaded by
% |\UseTblrLibrary{siunitx}|, otherwise they arrive too late.
%
% Key choices:
%  |group-minimum-digits=4|: numbers with 4+ digits get a thousands
%  separator (so |90600| formats as |90,600| EUR).
%  |group-separator={,}|: European style comma separator.
%  |table-auto-round=true|: silently rounds values to fit the
%  |table-format| without requiring \cs{num} wrappers everywhere.
%  |drop-zero-decimal=true|: suppresses redundant decimal zeros in numeric
%  and EUR cells while retaining genuinely fractional values such as explicit
%  animal-housing rates.
%  |mode=match|: inherits the surrounding text font, so numbers
%  in tables match the |\footnotesize| row font automatically.
%  |text-family-to-math=true|, |text-series-to-math=true|: pass
%  the current font family and series into math mode, keeping
%  bold/italic numbers consistent with their surrounding text.
%    \begin{macrocode}
\PassOptionsToPackage{
  mode =  match,
  propagate-math-font = true,
  % reset-math-version  = false,
  % reset-text-family   = false,
  % reset-text-series   = false,
  % reset-text-shape    = false,
  text-family-to-math = true,
  text-series-to-math = true,
  tight-spacing       = true,
  group-minimum-digits  = 4, % --> 1.234 instead of 1234
  group-separator        = {,},% for "12.345" instead of "12 345" %
  table-format          = 6,
  table-alignment-mode  = format,
  table-auto-round      = true,
  drop-zero-decimal     = true,
  locale                = UK,
  input-decimal-markers = {.},
  output-decimal-marker = {.},
  input-ignore          = {,},
  parse-numbers         = true
}{siunitx}
%    \end{macrocode}
% This is the package for our tables and we are using quite a bunch of
% additional libraries.
%    \begin{macrocode}
\RequirePackage{tabularray}
\UseTblrLibrary{booktabs}
\UseTblrLibrary{diagbox}
\UseTblrLibrary{siunitx}
\UseTblrLibrary{counter}
\UseTblrLibrary{functional}
%    \end{macrocode}
% \subsection{tabularray setup and table themes}
%
% \pkg{tabularray} renders each cell \emph{twice}: once in a hidden
% measuring pass to determine column widths, and once for final output.
% This means every database query, numeric calculation or warning inside
% a cell body would be executed twice.  The global boolean
% \cs{g\_@@\_tblr\_inside\_bool} (toggled via environment hooks) lets code
% detect the measuring pass so it can skip expensive side effects (e.g.\
% the \texttt{missing-key} warning is suppressed when
% \cs{lTblrMeasuringBool} is |true|).
%    \begin{macrocode}
\bool_new:N \g_@@_tblr_inside_bool
% -- Hook into the beginning and ending of the tblr environment ---------------
\AddToHook{env/tblr/begin}{\bool_set_true:N \g_@@_tblr_inside_bool}
\AddToHook{env/tblr/end}{\bool_set_false:N \g_@@_tblr_inside_bool}
%    \end{macrocode}
% \subsection{Custom table definition}
% \paragraph{Base Table Theme}
% Defines the shared templates and outer settings used by all table themes.
% The table font size is established as an ambient declaration here instead of
% through a |rows={font=...}| property.  A more specific cell property such as
% |font=\bfseries| replaces a row font property, but it inherits an ambient
% \cs{footnotesize}; an explicit size in the cell property can still override
% the default.
%    \begin{macrocode}
% Resolve the default after the final document fonts have been selected.
% Include a normal ascender when measuring the body line and a descender
% when measuring the subsection, matching their ordinary paragraph leading.
\AddToHook{begindocument/end}{
  \dim_compare:nNnT {\dfgTablePreSep} < {0pt}
  {
    \group_begin:
      \normalfont\normalsize
      \hbox_set:Nn \l_tmpa_box {Agl}
      \dim_set:Nn \l_tmpa_dim {\box_ht:N \l_tmpa_box}
      \hbox_set:Nn \l_tmpa_box
        {\usekomafont{disposition}\usekomafont{subsection}Ag}
      \skip_gset:Nn \dfgTablePreSep
        {\dim_max:nn {0pt}
          {\baselineskip + \parskip - \l_tmpa_dim - \box_dp:N \l_tmpa_box}}
    \group_end:
  }
}
% Long tables and short direct-cost blocks share one outer gap.
\SetTblrOuter[tblr]{label=none,entry=none,presep=\dfgTablePreSep,headsep=4pt}
\cs_new_protected:Npn \@@_table_start:
{
  \par
  % Commit a heading to the page without adding another baseline gap.
  \if@nobreak
    \hrule height 0pt width 0pt\relax\nobreak
  \fi
}
% Tabularray subtracts topskip after moving a table to a fresh page.  When
% a preceding heading moves with the table, that page already has content:
% subtracting topskip would shorten the heading-to-table gap by one line.
\cs_new_protected:Npn \@@_tblr_page_topskip:
{
  \dim_compare:nNnTF {\pagetotal} > {\topskip}
    {\kern-\lineskip}
    {\kern-\topskip}
  \nobreak
}
\msg_new:nnn {dfg} {table-spacing-compatibility}
  {Could~not~adjust~tabularray's~page-start~spacing;~its~internal~layout~has~changed.}
\tl_set:No \l_tmpa_tl {\__tblr_build_long_table:n {#1}}
\exp_args:NnV \regex_count:nnN
  {\c{kern} - \c{topskip} \c{nobreak}} \l_tmpa_tl \l_tmpa_int
\int_compare:nNnTF {\l_tmpa_int} = {3}
  {
    \regex_replace_all:nnN
      {\c{kern} - \c{topskip} \c{nobreak}}
      {\c{@@_tblr_page_topskip:}} \l_tmpa_tl
    \cs_set_protected:Npe \__tblr_build_long_table:n #1
      {\exp_not:V\l_tmpa_tl}
  }
  {\msg_warning:nn {dfg} {table-spacing-compatibility}}
% For long tables:
\cs_new_protected:Npn \mytblr_basecode: {
  \footnotesize
  % Continuous head/footer templates (use ~ for spaces)
  \DeclareTblrTemplate {conthead-text}{default}{%
  	\normalfont\color{tableContFootHead}%
  	\sffamily\footnotesize%
  	\ldots~continuing~from~previous~page.%
  }
  \DeclareTblrTemplate {contfoot-text}{default}{%
  	\normalfont\color{tableContFootHead}%
  	\sffamily\footnotesize%
  	Continue~on~the~following~page~\ldots%
  }
  % Caption continuation uses conthead
  \DeclareTblrTemplate {capcont}{default}{%
  	\UseTblrTemplate{conthead-text}{default}%
  }
  % Keep all text rendered below a table at least at footnote size.
  \SetTblrStyle{note-tag}{font=\footnotesize}
  \SetTblrStyle{note-sep}{font=\footnotesize}
  \SetTblrStyle{note-text}{font=\footnotesize}
  \SetTblrStyle{remark-tag}{font=\footnotesize}
  \SetTblrStyle{remark-sep}{font=\footnotesize}
  \SetTblrStyle{remark-text}{font=\footnotesize}
  % Use native raggedright consistently for all left-aligned table cells.
  \RenewDocumentCommand \TblrAlignLeft {} {\raggedright}%
  % Common outer settings
}
%    \end{macrocode}
% \paragraph{Table themes}
% Three named tblr themes are provided.  All inherit the shared
% \cs{mytblr\_basecode:} helper (continuous head/footer templates, left
% alignment) via a direct call at theme definition time.
%
% \textbf{plain}: minimal two-rule + alternating-row look used for
% simple supplementary tables (e.g.\ the direct-costs breakdown).
%    \begin{macrocode}
\NewTblrTheme{plain}{
  \mytblr_basecode:
  % plain-only inner tweaks:
  \SetTblrInner{
    % Keep row metrics independent of descenders such as p, q, f.
    stretch   = 1,
    rowsep    = .667pt,
  	row{even}={bg=tableRows},
  	width=\linewidth,
  	hline{1,Z}={1pt,fg=tableOuterLines},
  }
}
%    \end{macrocode}
% \textbf{main}: the full-featured style used by all DFG data tables.
% Adds a styled first-row header (blue background, bold sans-serif text),
% a midrule below row 1, caption fonts, and row continuation labels for
% long tables that span multiple pages.
% Header text uses |valign=m| (vertical centre), including multirow headings.
% Explicit row and cell options can override this default.
%    \begin{macrocode}
\NewTblrTheme{main}{
  \mytblr_basecode:
  % Keep wrapped remarks flush left, including printTable's appended notes.
  \SetTblrStyle{remark}{hang=0pt}
  % main-only styles & inner grid:
  \SetTblrStyle{caption-tag}{font=\bfseries\footnotesize\sffamily,tableCaption}
  \SetTblrStyle{caption-text}{
   tableCaption,
   font=\footnotesize,
   halign=l
  }
  \SetTblrStyle{caption}{halign=l}
  \SetTblrTemplate{caption}{simple}
  \SetTblrInner{%
  	row{odd}      ={bg=tableRows},
  	width         =\linewidth,
  	hline{1,Z}    ={1pt,fg=tableOuterLines},
  	rowhead       = 1,
  	width         = \textwidth,
  	hline{1,Z}    = {
  		1pt,
  		fg = tableOuterLines
  	},
  	hline{2} = {1pt, fg=tableOuterLines}, % midrule
    % Keep row metrics independent of descenders such as p, q, f.
    stretch   = .9,
    rowsep    = 1pt,
  	row{1}       = {
  		bg       = tableHeadingsBG,
  		fg       = tableHeadingsFont,
        font     = \bfseries,
  		halign   = {c},
        valign   = {m},
        abovesep = 3pt,
  		guard
  	},
  }%
  % \SetTblrInner{
  %   rows={ht=.5\baselineskip},
  %   rowsep       = 0pt,
  % }
}
%    \end{macrocode}
% \textbf{requestedFundingStaff}: caption styling for the staff roster without
% a table-wide row background.  This lets the roster mark individual
% non-applicable cells with the |tableNoValue| background.
%    \begin{macrocode}
\NewTblrTheme{requestedFundingStaff}{
  \mytblr_basecode:
  \SetTblrStyle{caption-tag}{font=\bfseries\footnotesize\sffamily,tableCaption}
  \SetTblrStyle{caption-text}{tableCaption,\footnotesize}
}
%    \end{macrocode}
% A generic long-table environment. The leading optional argument supplies
% outer tabularray options, including notes and remarks. The optional argument
% after the column specification supplies inner options; both default to empty.
% Let tabularray measure the caption normally; negative skips can pull it
% into the preceding paragraph or the top rule of the table.
%    \begin{macrocode}
\NewDocumentEnvironment{TableEnv}{ O{} m O{} m m }
{
  % #1: Outer specs
  % #2: colspec
  % #3: further options
  % #4: caption
  % #5: label
  \@@_table_start:
  \begin{tblr}[%
  	%  expand=\tblrbody,
    theme  =main,
    label  ={#5},
    entry  ={#4},
    caption={#4},
    long,
    #1
  ]{%
    % Set the body default first so explicit column alignments take precedence.
    row{2-Z}={halign=l},
    colspec ={#2},
  	rowhead = 1, %<- first row is head
    row{1}={valign=m},
    #3 %<- in case we need further adjustments
  }
}
{\end{tblr}\par}
%    \end{macrocode}
% At the final part of projects the costs must be listed more granularly.
% Use a long table that may break between rows. Its optional unnumbered
% heading is the first caption, keeping it with the first row at page breaks.
% Measure the currency column at its natural width: a fixed 0.5cm column
% is too narrow for EUR in some document fonts.  The X description column
% absorbs the width difference while the amount column stays rightmost.
%    \begin{macrocode}
\NewDocumentEnvironment{FundingDirectCostsTable}{O{}}
{
  \@@_table_start:
  \setlength{\parskip}{0pt}
  % Keep an unnumbered heading in the first table head, so it cannot be
  % stranded above a page break. Empty headings add no first-head space.
  \SetTblrTemplate{caption}{simple}
  \SetTblrStyle{caption}{halign=l}
  \SetTblrStyle{caption-text}{font=\footnotesize\bfseries\sffamily}
  \tl_if_blank:nT {#1}{\SetTblrTemplate{firsthead}{empty}}
  \begin{tblr}[%
    theme=plain, long, label=none, entry=none, caption={#1}, postsep=0pt]{
    colspec={
      X[t]
      Q[t,r]
      Q[t,si={table-format=9}]
    },
    rowhead=0,
  }
}
{\end{tblr}\par}

%    \end{macrocode}
%    \begin{macrocode}
\RequirePackage{caption}
\captionsetup{%
  % format=llapx,
  hypcap=false,
  format=plain,
  singlelinecheck=off,
  labelsep={colon}, % saving space
  %justification=RaggedRight,
  font={footnotesize,sf},
  labelfont={
  		sf,
  		bf, % bold face
  	}
}
% KOMA's caption name also applies to figures boxed by hvFloat.
\renewcaptionname{english}{\figurename}{Fig.}
\RequirePackage{pgfgantt}
\RequirePackage{placeins}
% hvfloat loads picture; its calc mode remains supported by picture v2.
\PassOptionsToPackage{calc}{picture}
\RequirePackage{hvfloat} % load after tabularray!!
% Built-in named plot style. Define it here so customization can select it
% without deferring a package command; selection is applied when printing.
\hvFloatSet{capPos=bottom,capVPos=top,floatPos=!hb}% this are the default values.
\RequirePackage{marginalia}
\marginaliasetup{
  xsep=0pt,
  width=13mm,
  style=\raggedleft\footnotesize,
  pos=auto,
}
\bool_if:NTF \l_@@_class_cv_bool
  {
    \tl_set_eq:NN \l_@@_custom_biblatexstyle_active_tl
      \l_@@_custom_biblatexstyle_cv_tl
    \tl_set_eq:NN \l_@@_custom_biblatexfeatures_active_tl
      \l_@@_custom_biblatexfeatures_cv_tl
  }
  {
    \tl_set_eq:NN \l_@@_custom_biblatexstyle_active_tl
      \l_@@_custom_biblatexstyle_proposal_tl
    \tl_set_eq:NN \l_@@_custom_biblatexfeatures_active_tl
      \l_@@_custom_biblatexfeatures_proposal_tl
  }
\RequirePackage[
  backend=biber,
  % using the most common style and also saving space.
  % style=ext-numeric, % taken from biblatex-ext
  % just in case we want to switch the style.
  % style=ext-alphabetic,
  %style=ext-authornumber-ecomp,
  style=\l_@@_custom_biblatexstyle_active_tl,
  %introcite=label,
  autocite=inline,
  defernumbers=true, % reset numbered bibliography for each chapter
  giveninits=true, % abbreviate the first names
  maxcitenames=1,
  mincitenames=1,
  maxbibnames=99, % show up to 6 authors of an bib entry (et al. thereafter)
  %nohashothers=true,
  %uniquelist=true,
  %uniquename=allfull,
  %labeldatepartes=true
  \l_@@_custom_biblatexfeatures_active_tl
]{biblatex}
%    \end{macrocode}
% Select the title locally, after loading an entry. The standard field keeps
% Biber imports and external bibliography tools compatible. Both bibliography
% items and full citations through \cs{usedriver} need the same selection.
% Using starred \cs{savefield} avoids a global scratch assignment; restoring
% only the current entry preserves full titles for later lists and groups.
%    \begin{macrocode}
\tl_new:N \l_@@_journal_short_title_tl
\cs_new_protected:Npn \@@_select_journal_title:
  {
    \str_if_eq:VnT \l_@@_custom_journal_title_tl {shortjournal}
      {
        \iffieldundef{shortjournal}
          {}
          {
            \savefield*{shortjournal}{\l_@@_journal_short_title_tl}
            \restorefield{journaltitle}{\l_@@_journal_short_title_tl}
            \clearfield{journalsubtitle}
          }
      }
  }
\AtEveryBibitem{\@@_select_journal_title:}
\AtUsedriver{\@@_select_journal_title:}
%    \end{macrocode}
% In final documents, \pkg{biblatex-ext-oa} can mark open-access publications
% directly in the bibliography.  Draft documents do not load the package, so
% they avoid DOI API checks and related warnings.  The DOI API backend is useful,
% but \pkg{biblatex-ext-oa-doiapi} and the |doiapi| option can only be used with
% LuaLaTeX.  With LuaTeX binaries from version 1.17.0 onwards, the LuaSocket
% module |socket.http| is exposed only when LuaTeX is started with the
% command-line option |--socket|.  If we always passed |doiapi=true| in final
% mode, a normal final compile without |--socket| would abort while loading
% \pkg{biblatex-ext-oa-doiapi}.
%
% After a user opts in with a contact address, the guard asks LuaTeX whether
% |require("socket.http")| succeeds.  The result is written back into the
% temporary expl3 string |\l_tmpa_str| as the literal text |true| or |false|.
% The Lua code is written without TeX-relevant whitespace, because expl3
% ignores spaces while tokenising this part of the class source; semicolons
% keep the Lua syntax unambiguous after docstrip has generated the |.cls| file.
%
% Automatic lookup is enabled only when LuaSocket is available and the user has
% supplied a non-empty \refKey{doiAPIMail}.  The address is passed to
% \cs{SetDOIAPIMail}; the class never sends a placeholder or maintainer address
% on behalf of its users.  If either prerequisite is missing, the class emits a
% specific warning and loads \pkg{biblatex-ext-oa} with |doiapi=false| so manual
% BibTeX annotations such as |doi+an:default = {=openaccess}| continue to work.
%
% API-based markers keep their linked symbols, but the additional
% ``open access version at'' text and URL are suppressed.
%
% The TikZ symbol package draws the open-access symbols.  The |oanet| symbol is
% the open-access symbol from open-access.net (https://open-access.net/), logo
% by Medien + Design, Center for Digital Systems, Competence Center for
% E-Learning and Multimedia, Freie Universität Berlin, CC BY 4.0
% (https://creativecommons.org/licenses/by/4.0/).
%    \begin{macrocode}
\cs_new_protected:Npn \@@_biblatex_oa_load_without_api:
  {
    \RequirePackage[
      doiapi=false,
      symbolpackage=tikz,
      symbol=oanet]{biblatex-ext-oa}
  }

\bool_if:NT \l_@@_class_final_bool
  {
    \tl_if_blank:VTF \l_@@_custom_doi_api_mail_tl
      {
        \msg_info:nn { dfg } { biblatex-ext-oa-doiapi-email-missing }
        \@@_biblatex_oa_load_without_api:
      }
      {
        \str_set:Nx \l_tmpa_str
          {
            \directlua
              {if(pcall(require,"socket.http"))then;tex.sprint("true");else;tex.sprint("false");end}
          }
        \str_if_eq:VnTF \l_tmpa_str { true }
          {
            \RequirePackage[
              doiapi=true,
              symbolpackage=tikz,
              symbol=oanet]{biblatex-ext-oa}
            \ExecuteBibliographyOptions{openaccess=doiapi}
            \renewbibmacro*{api:bestoaurl}{}
            \exp_args:NV \SetDOIAPIMail \l_@@_custom_doi_api_mail_tl
          }
          {
            \msg_warning:nn { dfg } { biblatex-ext-oa-doiapi-unavailable }
            \@@_biblatex_oa_load_without_api:
          }
      }
  }
% A project-text build with publication processing disabled must not require a
% matching biber run merely to keep inline source references readable.  Replace
% the common single-citation commands with quiet key markers; enabling
% |fastcompile-project-show-publications| restores biblatex's normal commands unchanged.
\bool_if:nTF
  {
    \l_@@_class_fastcompile_project_bool
    && ! \l_@@_class_fastcompile_project_show_publications_bool
  }
  {
    % Do not register bibliography data sources or parse a stale full-build
    % .bbl.  Keep biblatex's ordinary initialisation and refsection setup, but
    % replace its data-file stage with the minimum empty-section state.
    \cs_set_protected:Npn \blx@bblfile
      {
        \blx@secinit
        \blx@generate@bbl@mdfivesum@notfound
        \global\togglefalse{blx@bbldone}
        \csnumgdef{blx@labelnumber@\the\c@refsection}{0}
      }
    \NewDocumentCommand{\dfgFastCitation}{m}
      { {\color{black-50}\scriptsize\ttfamily [#1]} }
    \RenewDocumentCommand{\autocite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\cite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\parencite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\textcite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\footcite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\smartcite}{s o o m}
      { \dfgFastCitation{#4} }
    \RenewDocumentCommand{\nocite}{m} { }
    % Ignore citation requests restored from auxiliary files produced by a full
    % proposal build.  The fast source commands above do not write replacements.
    \cs_set_protected:Npn \abx@aux@cite   #1#2   { }
    \cs_set_protected:Npn \abx@aux@segm   #1#2#3 { }
    \cs_set_protected:Npn \abx@aux@nocite #1#2   { }
    % This mode deliberately has no bibliography work, so do not advertise a
    % biber rerun in the end-of-document logreq record.
    \AtEndDocument
    {
      \global\let\blx@rerun@biber\relax
      \global\togglefalse{blx@runbiber}
    }
  }
  {
    \bool_if:NF \l_@@_class_documentation_bool
    {
    \addbibresource{bib/dfg-base.bib}
    % The conversion workflow stores bibliography entries that still need
    % review separately.  Load that file when present without requiring it for
    % normal template installations.
    \IfFileExists{bib/conversion-missing.bib}
      {\addbibresource{bib/conversion-missing.bib}}
      {}
    \addbibresource{bib/dfg-strings.bib}
    }
  }
%    \end{macrocode}
% The \cs{AtEveryBibitem} hook strips fields that are irrelevant for a
% funding proposal (URL, month, note, ISSN/ISBN, language) from every
% entry, keeping the reference list compact.  These fields are cleared
% during output only; the |.bib| source files are unchanged.
% A second part of the hook selects the full-entry bold face. The frame and
% project bibliography wrappers set a local keyword only while printing
% their list; biblatex groups each item, so the font change does not leak into the
% following entry.  The hook runs after \cs{bibfont} and before the entry's
% fields are printed.
%    \begin{macrocode}
\bool_if:NTF \l_@@_class_documentation_bool
  {\newcommand\DFGBoldNamesFile{\jobname-boldAuthors.bib}}
  {\newcommand\DFGBoldNamesFile{bib/\jobname-boldAuthors.bib}}
\bool_if:NF \l_@@_class_fastcompile_project_show_publications_bool
  {\PassOptionsToPackage{noauthors}{dfg-bib-highlights}}
\RequirePackage{dfg-bib-highlights}
\RenewDocumentCommand \DFGBibIfAuthorsTF {mm}
  {\bool_if:NTF\l_@@_custom_emphasize_authors_bool{#1}{#2}}
\RenewDocumentCommand \DFGBibIfEntriesTF {mm}
  {\bool_if:NTF\l_@@_custom_emphasize_entries_bool{#1}{#2}}
\cs_set:Npn \DFGBibNameColor {color@reference@boldAuthor}
\keys_define:nn {dfgbib/setup}
  {emphasizeAuthors .meta:nn = {dfg/custom}{emphasizeAuthors=#1},
   emphasizeEntries .meta:nn = {dfg/custom}{emphasizeEntries=#1},
   color .code:n =
     {\changeSettings{color@reference@boldAuthor={#1}}
      \colorlet{color@reference@boldAuthor}{#1}}}
\AtEveryBibitem{
  \clearfield{url}
  \clearfield{month}
  \clearfield{note}
  \clearfield{issn}
  \clearfield{isbn}
  \clearlist{language}
}
%    \end{macrocode}
% \subsection{Shared authorship annotations}
%
% The |annote| field in |.bib| entries supports two special values:
% |equal| (for equal-first-author contributions) and |sharedlast| (for
% shared last authorship).  When present, \cs{mkbibnamefamily} appends
% an asterisk |*| after the family name via \cs{addendumasterisk}.
% The asterisk is only printed inside bibliography environments
% (\cs{ifbibliography}), not in inline citations.
%
% Use in |.bib|: add |addendum = equal| or |addendum = sharedlast| (no |{}|) to the affected author's annotation field.
%    \begin{macrocode}
\newcommand{\addendumasterisk}{\ifbibliography{*}{}}
\newcommand{\addendumhashtag}{\ifbibliography{\textsuperscript{\#}{}}}
% There is also the possibility that authors share the last authorship.
% with the bib-string `lastShared` we can get it work.
\renewcommand*{\mkbibnamefamily}[1]{%
  \ifitemannotation{equal} % first check for equal contribution
  {#1\addendumasterisk}% add a * for those authors
  {
  	% Then we check for "shared last authorship"
  	\ifitemannotation{sharedlast}%
  	{#1\addendumhashtag}% adding a symbol
  	{#1}% do nothing for any one else.
  }}
%    \end{macrocode}
%
%  \begin{macrocode}
% \subsection{datatool: database backend}
%
% \pkg{datatool} provides the |DTL*| commands that are the actual in-memory
% database engine behind the keyset-based metadata system.  \pkg{csquotes}
% is loaded just before it because \cs{blockcquote} is used in the
% documentation abstract and the class patches \cs{mkccitation} to suppress
% the extra parentheses that csquotes adds around \cs{autocite} results.
\RequirePackage{csquotes}
\renewcommand{\mkccitation}[1]{ (#1)}
\RequirePackage{datatool}
%    \end{macrocode}
% loading |tikz| at least for the thumb index.
%    \begin{macrocode}
\RequirePackage{tikz}
\ExplSyntaxOff
\usetikzlibrary{calc}
\usetikzlibrary{shapes.misc}
\usetikzlibrary{patterns,patterns.meta}
\ExplSyntaxOn
%    \end{macrocode}
% loading these two packages last
%    \begin{macrocode}
\RequirePackage{hyperref}
\RequirePackage{footnotehyper}
\RequirePackage{cleveref}
% enumitem creates a dedicated counter for each custom-list level but does not
% expose the parent relation to cleveref.  Register that relation so nested
% work-package references sort by parent first and ranges never cross parents.
\apptocmd{\cref@resetby}
  {\cref@ifstreq{#1}{workpackagesii}{\def#2{workpackagesi}}{}}
  {}
  {\PackageError{dfg}
    {Unable~to~register~the~nested~work-package~counter}
    {Nested~work-package~references~may~be~sorted~incorrectly.}}
% labelcref requires one reference type for mixed parent/child lists.
% Keep the parent-counter registration above for sorting and range boundaries.
\crefalias{workpackagesii}{workpackagesi}
\crefname{workpackagesi}{\color{referenceWP}\textbf{WP}}{\color{referenceWP}\textbf{WPs}}
\creflabelformat{workpackagesi}{\color{referenceWP}#2\textbf{#1}#3}
\crefname{workpackagesii}{\color{referenceWP}\textbf{WP}}{\color{referenceWP}\textbf{WPs}}
\creflabelformat{workpackagesii}{\color{referenceWP}#2\textbf{#1}#3}

\crefname{aimsi}{\bfseries\color{referenceAim}Aim}{\bfseries\color{referenceAim}Aims}
\creflabelformat{aimsi}{\color{referenceAim}#2\color{referenceAim}\bfseries#1\color{referenceAim}#3}
% Aux-file entry point: use the authored spelling for both reference forms.
\NewDocumentCommand{\dfgAimReferenceName}{m m}
{
  \crefname{#1}{\bfseries\color{referenceAim}#2}
    {\bfseries\color{referenceAim}#2}
  \Crefname{#1}{\bfseries\color{referenceAim}#2}
    {\bfseries\color{referenceAim}#2}
  \creflabelformat{#1}
    {\color{referenceAim}##2\bfseries##1##3}
  % The kernel reads aux files in a group, after cleveref's format setup.
  % Preserve only the names globally; cleveref's format builders already
  % make global definitions without leaking their temporary variables.
  \clist_map_inline:nn { cref,Cref }
  {
    \cs_gset_eq:cc {##1@#1@name} {##1@#1@name}
    \cs_gset_eq:cc {##1@#1@name@plural} {##1@#1@name@plural}
  }
  \@crefdefineallformats{#1}
}


% \subsection{Preamble end: global metadata extraction and hyperref}
%
% The \cs{AfterEndPreamble} hook fires after all user preamble code
% (including |dfg-customization.tex| and all \cs{addEntry} calls) but
% before \cs{begin}|{document}|.  This is the earliest point at which
% the |meta| database is guaranteed to be fully populated.
%
% The block extracts the five core CRC fields into named macros
% (\cs{theCRCname}, \cs{theCRCnumber}, \cs{theCRCaffiliation}, etc.)
% that are used in headers, footers, and the hyperref PDF metadata.  It
% treats |meta.ref-affiliation-id| as a comma-separated list: the public
% affiliation macros contain human-readable name and location lists, while
% \cs{theApplicantID} retains the normalized id list for database filters.  It
% also derives \cs{theFundingPeriodNumeralPrevious} by subtracting 1 from
% \cs{theFundingPeriodNumeral}, which is used in the gender equality tables
% to reference the previous funding period.
%
% The \cs{hypersetup} call here (rather than in the preamble) avoids
% needing the user to duplicate CRC metadata in a separate hypersetup block.
\clist_new:N \l_@@_applicant_affiliation_id_clist
\seq_new:N \l_@@_applicant_affiliation_name_seq
\seq_new:N \l_@@_applicant_affiliation_location_seq
\seq_new:N \l_@@_other_applicant_affiliation_name_seq
\tl_new:N \l_@@_applicant_affiliation_name_tl
\tl_new:N \l_@@_applicant_affiliation_location_tl

\cs_new_protected:Npn \@@_set_applicant_affiliation_metadata:
{
  \DTLifnullorempty{\theApplicantID}
    { \clist_clear:N \l_@@_applicant_affiliation_id_clist }
    {
      \clist_set:Nx \l_@@_applicant_affiliation_id_clist
        { \theApplicantID }
      \clist_remove_duplicates:N \l_@@_applicant_affiliation_id_clist
    }
  \tl_set:Nx \l_tmpa_tl
    { \clist_use:Nn \l_@@_applicant_affiliation_id_clist {,} }
  \cs_set:Npx \theApplicantID { \exp_not:V \l_tmpa_tl }
  \cs_set_eq:NN \theAffiliationValue \theApplicantID
  \seq_clear:N \l_@@_applicant_affiliation_name_seq
  \seq_clear:N \l_@@_applicant_affiliation_location_seq
  \clist_map_inline:Nn \l_@@_applicant_affiliation_id_clist
  {
    \DTLifdbexists{affiliation}
    {
      \DTLgetvalueforkey{\l_@@_applicant_affiliation_name_tl}
        {name}{affiliation}{id}{##1}
      \DTLgetvalueforkey{\l_@@_applicant_affiliation_location_tl}
        {location}{affiliation}{id}{##1}
    }
    {
      \tl_set:Nn \l_@@_applicant_affiliation_name_tl {##1}
      \tl_clear:N \l_@@_applicant_affiliation_location_tl
    }
    \DTLifnullorempty{\l_@@_applicant_affiliation_name_tl}
      { \tl_set:Nn \l_@@_applicant_affiliation_name_tl {##1} }
      { }
    \tl_set:Ne \l_tmpb_tl
    {
      \exp_not:N \dfgShowTag{##1}{name}
        {\exp_not:V \l_@@_applicant_affiliation_name_tl}[affiliation]
    }
    \seq_put_right:NV \l_@@_applicant_affiliation_name_seq \l_tmpb_tl
    \DTLifnullorempty{\l_@@_applicant_affiliation_location_tl}
      { }
      {
        \seq_if_in:NVF \l_@@_applicant_affiliation_location_seq
          \l_@@_applicant_affiliation_location_tl
        {
          \tl_set:Ne \l_tmpb_tl
          {
            \exp_not:N \dfgShowTag{##1}{location}
              {\exp_not:V \l_@@_applicant_affiliation_location_tl}
              [affiliation]
          }
          \seq_put_right:NV \l_@@_applicant_affiliation_location_seq
            \l_tmpb_tl
        }
      }
  }
  \cs_set:Npn \theCRCaffiliation
  {
    \seq_use:Nnnn \l_@@_applicant_affiliation_name_seq
      {~and~} {,~} {,~and~}
  }
  \cs_set:Npn \theCRCaffiliationLocation
  {
    \seq_use:Nnnn \l_@@_applicant_affiliation_location_seq
      {~and~} {,~} {,~and~}
  }
  \seq_set_eq:NN \l_@@_other_applicant_affiliation_name_seq
    \l_@@_applicant_affiliation_name_seq
  \seq_pop_left:NNF \l_@@_other_applicant_affiliation_name_seq \l_tmpa_tl
    { \tl_clear:N \l_tmpa_tl }
  \cs_set:Npn \theCRCCoordinatingAffiliation
    { \seq_item:Nn \l_@@_applicant_affiliation_name_seq {1} }
  \cs_set:Npn \theCRCOtherApplicantAffiliations
  {
    \seq_use:Nnnn \l_@@_other_applicant_affiliation_name_seq
      {~and~} {,~} {,~and~}
  }
}

\NewExpandableDocumentCommand{\dfgApplicantAffiliationsTF}{m m}
{
  \int_compare:nNnTF
    { \clist_count:N \l_@@_applicant_affiliation_id_clist } > {1}
    {#2}
    {#1}
}

\NewExpandableDocumentCommand{\dfgOtherApplicantAffiliationsTF}{m m}
{
  \int_compare:nNnTF
    { \clist_count:N \l_@@_applicant_affiliation_id_clist } > {2}
    {#2}
    {#1}
}

\NewDocumentCommand{\dfgCRCName}{}
  { \dfgShowTag{crc}{name}{\theCRCname}[meta] }
\NewDocumentCommand{\dfgCRCNameAddon}{}
  { \dfgShowTag{crc}{nameAddon}{\theCRCnameAddon}[meta] }
\NewDocumentCommand{\dfgCRCNumber}{}
  { \dfgShowTag{crc}{number}{\theCRCnumber}[meta] }
\NewDocumentCommand{\dfgFundingPeriodText}{}
  { \dfgShowTag{crc}{fundingPeriodText}{\theFundingPeriodText}[meta] }
\NewDocumentCommand{\dfgFundingPeriodNumeral}{}
  { \dfgShowTag{crc}{fundingPeriodNumeral}{\theFundingPeriodNumeral}[meta] }
\NewDocumentCommand{\dfgFundingYear}{m}
{
  \dfgShowTag{crc}{fundingYear#1}
  {
    \int_case:nnF {#1}
    {
      {1}{\tmpYearOne}
      {2}{\tmpYearTwo}
      {3}{\tmpYearThree}
      {4}{\tmpYearFour}
      {5}{\tmpYearFive}
    }
    {#1}
  }[meta]
}
\NewDocumentCommand{\dfgFundingYearPrevious}{m}
{
  \dfgShowTag{crc}{fundingYearPrevious#1}
  {
    \int_case:nnF {#1}
    {
      {1}{\tmpYearPreviousOne}
      {2}{\tmpYearPreviousTwo}
      {3}{\tmpYearPreviousThree}
      {4}{\tmpYearPreviousFour}
      {5}{\tmpYearPreviousFive}
    }
    {#1}
  }[meta]
}

\AfterEndPreamble{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \clist_clear:N \l_@@_applicant_affiliation_id_clist
    \cs_set:Npn \theApplicantID                  { }
    \cs_set:Npn \theCRCname                      { CRC~project~draft }
    \cs_set:Npn \theCRCnameAddon                 { }
    \cs_set:Npn \theCRCnumber                    { draft }
    \cs_set:Npn \theFundingPeriodNumeral         { 1 }
    \cs_set:Npn \theFundingPeriodText            { draft }
    \cs_set:Npn \theAffiliationValue             { }
    \cs_set:Npn \theCRCaffiliation               { }
    \cs_set:Npn \theCRCaffiliationLocation       { }
    \cs_set:Npn \theCRCCoordinatingAffiliation   { }
    \cs_set:Npn \theCRCOtherApplicantAffiliations{ }
    \cs_set:Npn \tmpYearOne                      { Year~1 }
    \cs_set:Npn \tmpYearTwo                      { Year~2 }
    \cs_set:Npn \tmpYearThree                    { Year~3 }
    \cs_set:Npn \tmpYearFour                     { Year~4 }
    \cs_set:Npn \tmpYearFive                     { Year~5 }
    \cs_set:Npn \tmpYearPreviousOne              { Previous~year~1 }
    \cs_set:Npn \tmpYearPreviousTwo              { Previous~year~2 }
    \cs_set:Npn \tmpYearPreviousThree            { Previous~year~3 }
    \cs_set:Npn \tmpYearPreviousFour             { Previous~year~4 }
    \cs_set:Npn \tmpYearPreviousFive             { Previous~year~5 }
  }
  {
  \DTLgetvalueforkey{\theApplicantID}{ref-affiliation-id}{meta}{id}{crc}
  \DTLgetvalueforkey{\theCRCname}{name}{meta}{id}{crc}% getting Title of CRC
  \DTLgetvalueforkey{\theCRCnameAddon}{nameAddon}{meta}{id}{crc}% getting name addon of CRC
  \DTLgetvalueforkey{\theCRCnumber}{number}{meta}{id}{crc}% getting number of CRC
  \DTLgetvalueforkey{\theFundingPeriodNumeral}{fundingPeriodNumeral}{meta}{id}{crc}% getting period of CRC
  \DTLgetvalueforkey{\theFundingPeriodText}{fundingPeriodText}{meta}{id}{crc}% getting period of CRC
  \@@_set_applicant_affiliation_metadata:
  \DTLgetvalueforkey{\tmpYearOne}  {fundingYear1}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearTwo}  {fundingYear2}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearThree}{fundingYear3}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearFour} {fundingYear4}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearFive} {fundingYear5}{meta}{id}{crc}%

  \DTLgetvalueforkey{\tmpYearPreviousOne}  {fundingYearPrevious1}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearPreviousTwo}  {fundingYearPrevious2}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearPreviousThree}{fundingYearPrevious3}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearPreviousFour} {fundingYearPrevious4}{meta}{id}{crc}%
  \DTLgetvalueforkey{\tmpYearPreviousFive} {fundingYearPrevious5}{meta}{id}{crc}%
  }


  \providecommand{\thisCRC}
    {CRC\,\texorpdfstring
      {\dfgShowTag{crc}{number}{\theCRCnumber}[meta]}
      {\theCRCnumber}\xspace}
  % Shared implementation for the user-level \CRC and \TRR commands.
  % #1 is the star boolean, #2 the optional title, #3 the printed programme
  % type, and #4 the CRC/TRR number to print and compare with the current CRC.
  % Current CRCs use \thisCRC in the unstarred form; starred current references
  % include the CRC title from the metadata unless an explicit title is given.
  % External CRCs/TRRs always print the requested number and add the optional
  % title when one is supplied.
\cs_new_protected:Npn \@@_crc_print:nnnn #1 #2 #3 #4
  {
    \tl_if_eq:VnTF \theCRCnumber {#4}
      {
        \IfBooleanTF{#1}
          {
            #3\,#4
            \IfValueTF{#2}
              { \ \textit{#2} }
              { \ \textit{\dfgShowTag{crc}{name}{\theCRCname}[meta]} }
          }
          {
            \thisCRC
            \IfValueT{#2}
              { \ \textit{#2} }
          }
      }
      {
        #3\,#4
        \IfValueT{#2}
          { \ \textit{#2} }
      }
  }

  % User-level wrappers around \@@_crc_print:nnnn. They differ only in the
  % printed programme type.
\NewDocumentCommand{\CRC}{s o m}
  {
    \@@_crc_print:nnnn {#1} {#2} {CRC} {#3}
  }

\NewDocumentCommand{\TRR}{s o m}
  {
    \@@_crc_print:nnnn {#1} {#2} {CRC/\allowbreak TRR} {#3}
  }
  % Bookmark text must consume the same stars/options without running the
  % protected typesetting commands or metadata tags.
\cs_new:Npn \@@_crc_pdf:nnnn #1#2#3#4
  {
    \str_if_eq:eeTF {\theCRCnumber} {#4}
      {
        \IfBooleanTF{#1}
          {#3~#4~\IfValueTF{#2}{#2}{\theCRCname}}
          {CRC~\theCRCnumber\IfValueT{#2}{~#2}}
      }
      {#3~#4\IfValueT{#2}{~#2}}
  }
\NewExpandableDocumentCommand{\@@_crc_pdf:}{s o m}
  { \@@_crc_pdf:nnnn {#1}{#2}{CRC}{#3} }
\NewExpandableDocumentCommand{\@@_trr_pdf:}{s o m}
  { \@@_crc_pdf:nnnn {#1}{#2}{CRC/TRR}{#3} }
\pdfstringdefDisableCommands
  {
    \let\CRC\@@_crc_pdf:
    \let\TRR\@@_trr_pdf:
    \def\thisCRC{CRC~\theCRCnumber}
  }
 %\DTLgetvalueforkey{\theNameSpokespersonPosition}{position}{VIP}{specialRole}{spokesperson}% getting Title of Spokesperson
  %\DTLgetvalueforkey{\theNameSpokespersonName}{name}{VIP}{specialRole}{spokesperson}% getting Title of CRC
  %\DTLgetvalueforkey{\theNameSpokespersonNameFirst}{nameFirst}{VIP}{specialRole}{spokesperson}% getting Title of CRC
  \newcommand{\theFundingPeriodNumeralPrevious}{%
  	\number\numexpr\theFundingPeriodNumeral-1\relax%
  }
  % hyperref options
  \hypersetup{          % setup the hyperref-package options
  	% unicode      = true,
  	pdftitle     = {\theCRCname.\space\theCRCnameAddon},  %   - title (PDF meta)
  	pdfsubject   = {\crc},%   - subject (PDF meta)
    pdfauthor    = {CRC~\theCRCnumber~\theCRCname},  %   - author (PDF meta)
  	%   pdfauthortitle = {\theNameSpokespersonPosition},
  	%   pdfcopyright = {Copyright (c) \thisCRC All rights reserved.},
  	pdfhighlight = /N,
  	pdfdisplaydoctitle = true,
  	pdflang     = {en},
  	%   pdfcaptionwriter = {\theNameSpokespersonNameFirst \theNameSpokespersonName},
  	% pdfencoding = auto,
  	pdfproducer = {LuaLaTeX},
  	% pdflicenseurl = {http://creativecommons.org/licenses/by-nc-nd/4.0/},
  	% plainpages  = false,      %   -
  	colorlinks  = true, % -Colours links instead of ugly boxes
  	urlcolor    = blue, %Colour for external hyperlinks
  	linkcolor   = black,%rwthBlue, %Colour of internal links
  	citecolor   = black, %Colour of citations
  	% linkbordercolor=rwthRed,
  	linktoc     = page,
    pdfborder   = {0~0~0},      % Explicit spaces are required under ExplSyntaxOn.
  	breaklinks  = true,      %   - allow line break inside links
  	bookmarksnumbered  = true,    %
  	bookmarksopenlevel = 1,
  	bookmarksopen      = true,    %
  	bookmarksdepth     = 3,
	  %  final       = true,  % = true, only for web documents.
  	%  hypertexnames = false,
  	%  pageanchor=false,
  	%https://tex.stackexchange.com/questions/623377/how-to-increase-the-setting-dest-names-size-using-lualatex-on-tl-2021
  }
}
%    \end{macrocode}
% \subsection{\cs{changeSettings}}
%
% \cs{changeSettings}\marg{key=value,...} is the public command used
% to customise the document class beyond its defaults.  It delegates
% directly to \cs{keys\_set:nn}|{dfg/custom}{\meta{key=value,...}}|.
%
% It should be called inside |preamble/dfg-customization.tex| so that all
% customisations are centralised.  Examples:
% \begin{dispListing*}{title={Typical changeSettings call}}
%   \changeSettings{
%     font                        = Arial,
%     crcLogoPath                 = img/logo-crc,
%     affiliationLogoPath         = img/logo-affiliation,
%     doiAPIMail                  = researcher@example.org,
%     projectPIOncePerSection     = true,
%     collaborationAreaColors     = {A=projectA,B=projectB,Q=projectQ},
%     collaborationAreaPalette    = {orange,violet,teal,brown},
%     salary@postDoc              = 90000,
%     animalHousing@mouse         = 0.80,
%     thumbindex                  = false,
%     biblatexstyleCV             = ext-numeric-comp,
%     biblatexstyleFeatureCV      = {sorting=none},
%     biblatexstyleProposal       = ext-authoryear-ecomp,
%     biblatexstyleFeatureProposal= {},
%     color@table@rows            = blue-10,
%   }
% \end{dispListing*}
% The command is defined before \pkg{biblatex} is loaded so bibliography
% package options from the customization file take effect in time.
% \subsection{Thumb index implementation}
%
% The thumb index is a series of colour tabs printed on the outer margin
% of each page to help readers navigate between chapters or project sections.
% Each tab occupies one slot in a vertical grid that repeats with a period
% equal to \texttt{thumbindex@pattern} (default: 10).
%
% \textbf{Geometry calculation:}
% \cs{thumb\_compute\_height:} calculates the slot height as
% |(\cs{paperheight} - topmargin - bottommargin) / pattern|.  In the default
% |auto| mode, the margins are derived from the current text-block position and
% \cs{textheight}, so the slot height is \cs{textheight}| / pattern|.  The
% calculation runs when the tab is drawn, allowing later layout changes to
% affect the thumb-index grid.
%
% \textbf{Placement:}
% \cs{thumb\_place\_node:nnnn} builds the tab in the active running head,
% preserving its font and colour, and queues the finished zero-size box for
% |shipout/background|, beneath the page text and graphics (including the
% tab label). The frozen page-edge coordinates centre the tab at
% |topmargin + height*(index-1/2)|. Page offsets are compensated in the hook,
% so explicit \cs{hoffset} and \cs{voffset} keep the tab on the physical edge.
% No saved picture origin or second LaTeX pass is needed for tab placement.
% The rectangular tab has 7pt rounded corners and is shifted 7pt past the
% page boundary, clipping the outer corners while retaining the configured
% visible depth.  Its label is rotated 90 degrees in opposite directions on
% facing pages so the tab stays within the marginal column. The default
% |thumbindex@orientation=outwards| points the tops of the letters towards the
% outer edge. Choosing |inwards| adds 180 degrees to the label rotation on
% both sides, without changing the tab geometry.
% The label is inset 2\,mm towards the text block on either side; paired
% horizontal kerns leave the tab dimensions and placement unchanged.
%
% \textbf{Call pattern:}
% \cs{printThumbIndex}\oarg{options}\marg{label} resets the two active colour
% aliases from the configured defaults, then applies the call's |bg|/|fg|
% keys. A bare colour is shorthand for |bg|; a token-list expansion also accepts
% option lists or colours supplied by macros. The aliases and head assignments
% persist for following pages within the surrounding TeX scope; the configured
% defaults are never rewritten. Each next call starts from those defaults.
% The command increments the slot counter, wrapping at \texttt{pattern},
% then installs the callbacks in the outer
% running heads via \cs{lehead}/\cs{lohead}, including their plain-page forms.
% The foreground callback is scheduled only when that page's head is built,
% including plain pages; empty page styles schedule no tab. The
% options allow project-specific hues (typically the |projectA|, |projectB|,
% |projectQ| aliases). With thumb indexing disabled, neither options nor colours
% are evaluated and the slot counter remains unchanged.
%
% \cs{printThumbIndexOff} clears the outer running-head fields to suppress the
% tab on pages where no thumb index is desired (e.g.\ the bibliography).
% \cs{resetThumbIndex} resets the slot counter so that the next
% \cs{printThumbIndex} call starts at the first slot again.  This is useful
% when a manually inserted section should begin a new thumb-index sequence.
%    \begin{macrocode}
\RequirePackage{dfg-thumbindex}
%    \end{macrocode}
% \subsection{Bold-author mechanism}
%
% The DFG requires that the names of all CRC project leaders are printed in
% bold in every bibliography list so reviewers can immediately identify the
% investigators' output.  This is technically non-trivial because biblatex
% does not natively support singling out individual author names.
%
% The implementation uses a hash-based approach:
% \begin{enumerate}
%   \item For each PI, \refCom{addboldnames} is called with their name as it
%         appears in the |.bib| file (and all common aliases via
%         \refKey{name-alias}).  Each name is written as a |\@misc|
%         |dataonly| entry to an auxiliary |.bib| file.
%   \item During the |\AfterPreamble| pass, the cite command
%         |\nhblx@getmethehash| processes each entry and extracts its
%         biblatex internal hash (a fingerprint stable across style changes)
%         into the list |\nhblx@boldhashes|.
%   \item The name wrapper |boldifhashinlist| applies
%         \cs{mkboldifhashinlist} to every printed author name; if the
%         author's hash appears in the list, the name is wrapped in
%         \cs{mkbibbold} and coloured with |color@reference@boldAuthor|.
% \end{enumerate}
% The backend is initialized whenever publications are enabled, so a project
% can turn author emphasis on even if it was disabled in the customization
% file. The name wrapper checks |emphasizeAuthors| at rendering time.
% Fallback no-op definitions of \refCom{addboldnames} and \refCom{resetboldnames}
% are provided via \cs{providecommand} so that content files compile
% correctly when fast project mode disables publications entirely.
%
% \refCom{addboldnames} should be called in the preamble of both the proposal
% document and the standalone CV document, typically inside
% |preamble/dfg-customization.tex|.
% For displaying certain authors in bold letters, \refKey{emphasizeAuthors}
% (for the switch) and \refCom{addboldnames} (for the addition of authors).
%    \begin{macrocode}
% Implemented by dfg-bib-highlights.sty.
%    \end{macrocode}
% \subsection{Database infrastructure and key families}
%
% All structured data in the proposal (people, projects, institutions,
% funding entries, \ldots) is stored in \pkg{datatool} databases at
% compile time.  Each database is created lazily: \refCom{addEntry} checks
% whether the named database already exists and creates it if not,
% eliminating the need for explicit initialisation calls.
%
% The central mechanism relies on the L3 variable
% \cs{l\_@@\_database\_name\_tl}, which holds the name of the
% currently-active database while a \cs{keys\_set:nn} call is in
% progress.  Every |.code:n| handler in a keyset calls
% \cs{DTLnewdbentry} with that variable as the database name, so no
% explicit database name is needed inside the keyset definition itself.
%
% The token list is reset in each call to \refCom{addEntry} and is wrapped
% in a |\group_begin:/end:| pair to prevent it from leaking across
% independent \refCom{addEntry} calls.
%
% \paragraph{Input validation strategy}
% Choice-valued keys (e.g.\ \refKey{gender}, \refKey{project-type}) use
% |.choices:nn| with an |unknown .code:n| handler wired to the
% |dfg/invalid-value| message.  Free-text keys accept any input.
% Required keys are marked with |.value\_required:n = true| so that
% omitting them produces an immediate error rather than a silent empty
% database field.
%    \begin{macrocode}
\tl_new:N \l_@@_database_name_tl
%    \end{macrocode}
% \paragraph{Keyset \textbf{meta}}
% The |meta| database holds exactly one row with |id=crc| that describes
% the CRC itself.  Its fields are read in \cs{AfterEndPreamble} to populate
% the global macros used in headers, footers, and PDF metadata
% (\cs{theCRCname}, \cs{theCRCnumber}, \cs{theCRCaffiliation}, etc.).
%
% The \refKey{fundingYears} and \refKey{fundingYearsPrevious} keys accept a
% comma-separated list of calendar years (one per funding year) and expand
% them into individually named fields |fundingYear1| \ldots |fundingYear5|,
% which are used e.g. as column headers in the Gantt chart title row.
%
% \refKey{fundingPeriodNumeral} (1, 2 or 3) drives all period-filtered queries:
% only personnel with a matching |period| entry are included in the project
% leader table and the gender equality analysis.
%    \begin{macrocode}
\keys_define:nn { meta }{
  id              .code:n     =  \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id              .value_required:n = true,
  name      .code:n  = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  nameAddon .code:n  = \DTLnewdbentry{\l_@@_database_name_tl}{nameAddon}{#1},
  number    .code:n  = \DTLnewdbentry{\l_@@_database_name_tl}{number}{#1},
  fundingPeriodNumeral .choices:nn = { 1 , 2 , 3 }
  	{
  		% store the numeral itself
  		\DTLnewdbentry{\l_@@_database_name_tl}{fundingPeriodNumeral}{#1}
  		% map numeral → text without a property list
  		\int_case:nnF {#1}
  		{
  			{ 1 } { \DTLnewdbentry{\l_@@_database_name_tl}{fundingPeriodText}{first} }
  			{ 2 } { \DTLnewdbentry{\l_@@_database_name_tl}{fundingPeriodText}{second} }
            { 3 } { \DTLnewdbentry{\l_@@_database_name_tl}{fundingPeriodText}{third} }
  		}
  		{
  			% fallback (should not happen because of the .choices clause)
        \msg_warning:nnnn { dfg } { invalid-value }
  			{ #1 } { 1 , 2 , 3 }
  		}
  	} ,
  fundingPeriodNumeral / unknown .code:n =
  	{
      \msg_warning:nnnn { dfg } { invalid-value }
  		{ #1 } { 1 , 2 , 3 }
  	} ,
  fundedSince          .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{fundedSince}{#1},
  fundingYears .code:n =
  	{
  		\seq_set_from_clist:Nn \l_meta_funding_years_seq {#1}
  		%--- create the individual entries -----------------
  		\int_zero_new:N \l_tmpa_int
  		\seq_map_inline:Nn \l_meta_funding_years_seq
  		{
  			\int_incr:N \l_tmpa_int
  			\DTLnewdbentry
  			{\l_@@_database_name_tl}
  			{fundingYear\int_use:N \l_tmpa_int}
  			{##1}
  		}
  	},
  fundingYearsPrevious .code:n =
  	{
  		\seq_set_from_clist:Nn \l_meta_funding_years_previous_seq {#1}

  		%--- create the individual entries -----------------
  		\int_zero_new:N \l_tmpa_int
  		\seq_map_inline:Nn \l_meta_funding_years_previous_seq
  		{
  			\int_incr:N \l_tmpa_int
  			\DTLnewdbentry
  			{\l_@@_database_name_tl}
  			{fundingYearPrevious\int_use:N \l_tmpa_int}
  			{##1}
  		}
  	},
  ref-affiliation-id  .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-affiliation-id}{#1},
}
%    \end{macrocode}
% \paragraph{Keyset \textbf{GenderEquality}}
% This keyset is used to populate the \cs{GenderEqualityStaffTable} and
% \cs{GenderEqualityProjectLeadersTable}.  Each row stores one
% position-level target for the upcoming funding period alongside the
% previous period's objective for comparison.
%
% The live counts (current numbers of female/male/diverse staff per
% position and period) are \emph{computed} at render time from the |person|
% database — they are not entered manually.  Only the
% percentage-female objective values need to be provided here.
%    \begin{macrocode}
\keys_define:nn { GenderEquality }{
  position                             .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{position}{#1},
  previous-objective-percentage-female .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{previous-objective-percentage-female}{#1},
  status-quo-number-female             .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{status-quo-number-female}{#1},
  status-quo-percentage-female         .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{status-quo-percentage-female }{#1},
  future-objective-percentage-female   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{future-objective-percentage-female}{#1},
}
%    \end{macrocode}
% \paragraph{Multi-value helper: \cs{\_\_dfg\_set\_filtered\_clist:Nnn}}
% Several keys (|role|, |period|) accept comma-separated lists rather than
% a single choice.  The private helper
% \cs{\_\_dfg\_set\_filtered\_clist:Nnn}|{\meta{result}}{\meta{valid}}{\meta{input}}|
% iterates over the input list, drops any item that is not in the valid list
% (and emits an |invalid-value| warning for it), and stores the cleaned
% result in a clist variable.  This is used instead of |.choices:nn| because
% the standard choices handler only accepts a single value.
%    \begin{macrocode}
\clist_new:N \l_@@_person_tmp_period_clist
\clist_new:N \l_@@_person_tmp_role_clist
\clist_new:N \l_@@_keys_tmp_clist
\cs_new_protected:Npn \_@@_set_filtered_clist:Nnn #1#2#3
{
  % #1: clist variable in which valid values are stored
  % #2: clist of valid values
  % #3: clist of given values
  % function assumes none of the values contain braces or `#` tokens
  \clist_set:Nn \l_@@_keys_tmp_clist {#2}
  \clist_clear:N #1
  \clist_map_inline:nn {#3}
  {
  	\clist_if_in:NnTF \l_@@_keys_tmp_clist {##1}
  	{ \clist_put_right:Nn #1 {##1} }
    { \msg_warning:nnne { dfg } { invalid-value } {##1}
      { \clist_use:Nn \l_@@_keys_tmp_clist {,~} } }
  }
}
%    \end{macrocode}
%
% \paragraph{Keyset \textbf{project}}
% One row per CRC sub-project.  The \refKey{id} is the short project letter (e.g.\
% |A01|); \refKey{number} is the DFG-assigned project number; \refKey{name} is the full
% project title; optional |short-title| supplies its concise alternative.
% |projectTitle| settings choose full or short separately for TOC, running
% head and project-start title, without altering stored |name| values.
% \refKey{project-type} and \refKey{project-status} control how the project
% appears in tables and are choice-validated.
%
% The \refKey{research-area} key is a tick-list of DFG classification codes in
% the form |1.11-01| (see the property list in Section~\ref{sec:research-areas}).
% Multiple codes are passed as a brace-grouped comma list.
%
% The \refKey{ref-person-id} and \refKey{collaboration} values are comma
% lists.  Whitespace surrounding individual IDs is ignored and the canonical,
% space-free list is stored in the database.  Thus
% |{person-a,person-b,person-c}| and |{person-a, person-b, person-c}| are equivalent for
% every later consumer.
% The optional project |period={1,2,3}| list records funding-period membership
% independently of PI histories. Empty lists represent unfunded projects.
% The publication-network preprocessor uses these explicit memberships; current
% proposal periods may also describe projects proposed for the next phase.
% The optional |project-area| key controls the area row in collaboration plots.
% When omitted, the first character of the project ID is used as a fallback.
%
% The \refKey{legal-issues} sub-keyset mirrors the questions from the DFG online
% portal's project-information form (\refKey{L1}--\refKey{L7}).  Nested key-value parsing
% is triggered via a single |legal-issues={...}| block.
%
%    \begin{macrocode}
\cs_new_protected:Npn \@@_new_clist_dbentry:nnn #1#2#3
{
  \clist_set:Nn \l_tmpa_clist {#3}
  \exp_args:NnnV \DTLnewdbentry {#1} {#2} \l_tmpa_clist
}

\bool_new:N \l_@@_project_consider_for_lists_bool
\bool_new:N \l_@@_project_reference_only_bool
\bool_new:N \g_@@_project_count_ready_bool

\keys_define:nn { project }{
  id                       .code:n           =   \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id                       .value_required:n = true,
  number                   .code:n           = \DTLnewdbentry{\l_@@_database_name_tl}{number}{#1},
  number                   .value_required:n = true,
  name                     .code:n           = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  short-title              .code:n           = \DTLnewdbentry{\l_@@_database_name_tl}{short-title}{#1},
  short-title              .value_required:n = true,
  project-type             .choices:nn       =  { research,service,mgk,admin} {\DTLnewdbentry{\l_@@_database_name_tl}{project-type}{#1}},
  project-type / unknown   .code:n           = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{research,service,mgk,admin}},
  project-type             .value_required:n = true,
  project-status           .choices:nn       =  { N,E,C} {\DTLnewdbentry{\l_@@_database_name_tl}{project-status}{#1}},
  project-status / unknown .code:n           = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{N,E,C}},
  project-status           .value_required:n = true,
  consider-for-lists           .choices:nn       = { true,false }
    { \str_if_eq:nnTF {#1} {true}
        { \bool_set_true:N \l_@@_project_consider_for_lists_bool }
        { \bool_set_false:N \l_@@_project_consider_for_lists_bool } },
  consider-for-lists / unknown .code:n           =
    { \msg_warning:nnnn { dfg } { invalid-value } {#1} {true,false} },
  consider-for-lists           .value_required:n = true,
  reference-only           .choices:nn       = { true,false }
    { \str_if_eq:nnTF {#1} {true}
        { \bool_set_true:N \l_@@_project_reference_only_bool }
        { \bool_set_false:N \l_@@_project_reference_only_bool } },
  reference-only / unknown .code:n           =
    { \msg_warning:nnnn { dfg } { invalid-value } {#1} {true,false} },
  reference-only           .value_required:n = true,
  research-area            .code:n           = \DTLnewdbentry{\l_@@_database_name_tl}{research-area}{#1},
  project-area             .code:n           = \DTLnewdbentry{\l_@@_database_name_tl}{project-area}{#1},
  period                   .code:n           =
    {
      \@@_set_filtered_clist:Nnn \l_tmpa_clist {1,2,3} {#1}
      \exp_args:NnnV \DTLnewdbentry{\l_@@_database_name_tl}{period}\l_tmpa_clist
    },
  period                   .value_required:n = true,
  ref-person-id            .code:n           =
  \@@_new_clist_dbentry:nnn {\l_@@_database_name_tl} {ref-person-id} {#1},
  collaboration            .code:n           =
  \@@_new_clist_dbentry:nnn {\l_@@_database_name_tl} {collaborations} {#1},
  collaborations           .meta:n           = {collaboration={#1}},
  legal-issues             .code:n           = { \keys_set:nn { project / legal-issues  } { #1 } }
}
%    \end{macrocode}
% The |legal-issues| key in a |project| entry accepts a sub-keyset that
% maps each legal-issue question to a value.  The questions fall into two
% groups, which are handled differently:
%
% \begin{description}
%   \item[Main questions (\refKey{L1}, \refKey{L2}, \refKey{L3},
%     \refKey{L4}, \refKey{L5}, \refKey{L6}, \refKey{L7})] Each must be
%     answered with exactly \texttt{yes} or \texttt{no}.  Any other
%     value triggers a warning via \cs{person\_questions\_invalid:n}, and
%     no database entry is created.
%
%   \item[Sub-questions (\refKey{L1a}, \refKey{L2a}, \refKey{L5a},
%     \refKey{L7a})] These are conditional follow-ups whose answer only
%     matters when the corresponding main question was answered with
%     \texttt{yes}.  Sub-questions accept \texttt{yes}, \texttt{no},
%     or an empty value.  An empty value records an empty cell in the
%     database, which the typesetting code treats as ``not answered''
%     and consequently does not render in the legal-issues table.
% \end{description}
%
% The asymmetry exists because forcing every sub-question to be answered
% would require authors to fill in irrelevant follow-ups whenever the
% parent question is \texttt{no} -- for example, providing an answer
% to ``has legal authorization been obtained'' for a project that does
% not involve human embryonic stem cells in the first place.  Allowing
% an empty value lets the data file mirror the structure of the
% questionnaire: only the relevant cells need to be filled in.
%
% \medskip
%
% Internally, the main questions use the \refPkg{l3keys} \texttt{.choices:nn}
% property, which natively rejects values outside the allowed set.  The
% sub-questions cannot use \texttt{.choices:nn} directly because that
% property does not accept the empty string as a choice; they instead
% dispatch through the helper \cs{dfg\_legal\_subq:nn}, which inspects
% the supplied value and creates a database entry when the value is
% \texttt{yes}, \texttt{no}, or empty, and warns otherwise.
%
% \medskip
%
% Example of a complete |legal-issues| block in a project entry:
%
% \begin{dispListing*}{title={Example entries for |legal-issues|}}
% legal-issues = {
%   L1  = {yes},
%   L1a = {yes},      % L1 was true, follow-up answered
%   L2  = {no},
%   L2a = {},          % L2 was false, follow-up irrelevant
%   L3  = {yes},
%   L4  = {no},
%   L5  = {no},
%   L5a = {},
%   L6  = {yes},
%   L7  = {yes},
%   L7a = {yes}
% }
% \end{dispListing*}
%
% The empty values for \refKey{L2a} and \refKey{L5a} are valid: they correspond to
% follow-ups whose parent question was answered \texttt{no}, so no
% follow-up information is required or rendered.
%    \begin{macrocode}
\keys_define:nn { project / legal-issues }
{
  % main questions: must be yes/no
  L1  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L1} {#1} },
  L2  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L2} {#1} },
  L3  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L3} {#1} },
  L4  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L4} {#1} },
  L5  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L5} {#1} },
  L6  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L6} {#1} },
  L7  .choices:nn = { yes, no } { \DTLnewdbentry{\l_@@_database_name_tl}{L7} {#1} },
  %
  % sub-questions: yes / no / empty all allowed
  L1a .code:n = { \dfg_legal_subq:nn {L1a} {#1} },
  L2a .code:n = { \dfg_legal_subq:nn {L2a} {#1} },
  L5a .code:n = { \dfg_legal_subq:nn {L5a} {#1} },
  L7a .code:n = { \dfg_legal_subq:nn {L7a} {#1} },
  %
  % unknown handlers (only need them for the binary keys)
  L1  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L2  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L3  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L4  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L5  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L6  / unknown .code:n = { \person_questions_invalid:n {#1} },
  L7  / unknown .code:n = { \person_questions_invalid:n {#1} },
}

% Sub-question handler: accepts yes, no, or empty.
\cs_new_protected:Npn \dfg_legal_subq:nn #1#2
{
  \tl_if_blank:nTF {#2}
  { \DTLnewdbentry{\l_@@_database_name_tl}{#1}{} }
  {
  	\str_case:nnF {#2}
  	{
  		{ yes  } { \DTLnewdbentry{\l_@@_database_name_tl}{#1}{yes}  }
  		{ no } { \DTLnewdbentry{\l_@@_database_name_tl}{#1}{no} }
  	}
    { \msg_warning:nnnn { dfg } { invalid-value } {#2}
      { yes,~no,~or~an~empty~value } }
  }
}
%    \end{macrocode}
% \paragraph{Keyset \textbf{person}}
% The |person| database is the central personnel registry for the proposal.
% Every PI, manager, steering committee member and early-career researcher
% who appears in any table must have a row here.
%
% \textbf{Key semantics:}
%   \refKey{role}: A filterable comma list of roles.  The supported values
%     (|PI|, |spokesperson|, |manager|, |steering-committee-member|,
%     |rector|) are validated against a fixed list using the multi-value
%     helper so that multiple roles per person are permitted.
%   \refKey{position}: A single choice describing the employment category
%     (|prof-W2|, |prof-W3|, |postDoc|, |PhD|, etc.).  Used in the gender
%     equality and staff cost tables.
%   \refKey{period}: Comma list of funding periods (|1|, |2|, |3|) in which
%     this person is active.  All period-filtered queries
%     (e.g.\ the project-leaders table) use this field.
%   \refKey{name-alias}: Brace-grouped list of name variants as the author
%     name appears in |.bib| files.  These are passed to \cs{addboldnames}
%     so all spelling variants are highlighted consistently.
%   \refKey{contract-information}: Sub-keyset (\refKey{C1}--\refKey{C4a}) for the four
%     employment-contract questions required in the DFG project header.
%     Internally stored as fields |Q1|--|Q4a|.
%    \begin{macrocode}
\keys_define:nn { person }{
  unknown .code:n = { \msg_warning:nnn  { dfg } { unknown-key } {#1}},
  unknown .default:V = \c_novalue_tl,
  id                .code:n =   \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id                .value_required:n = true,
  firstname        .code:n =	\DTLnewdbentry{\l_@@_database_name_tl}{firstname}{#1},
  firstname .value_required:n = true,
  lastname         .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{lastname}{#1},
  lastname .value_required:n = true,
  academicdegree   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{academicdegree}{#1},
  gender .choices:nn =  { m , f , d } {\DTLnewdbentry{\l_@@_database_name_tl}{gender}{#1}},
  gender / unknown .code:n = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{ m,f,d }},
  gender .value_required:n = true,
  ref-affiliation-id   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-affiliation-id}{#1},
  ref-institution-id   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-institution-id}{#1},
  ref-project-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-project-id}{#1},
%    \end{macrocode}
% With \refKey{role} we want to differentiate between various people so we easily can
% get the necessary person into the right table. Roles can be e.g. |PI|,
% |service| etc.
%    \begin{macrocode}
  role .code:n = {\_@@_set_filtered_clist:Nnn \l_@@_person_tmp_role_clist {
  			PI,~ spokesperson,~ manager,~ steering-committee-member,~rector
  		} {#1}
  		\exp_args:Nnne \DTLnewdbentry{\l_@@_database_name_tl}{role}
                 { \clist_use:N  \l_@@_person_tmp_role_clist}},
%    \end{macrocode}
% position is also bound to a value list
%    \begin{macrocode}
  position .choices:nn =  {
  		PhD, postDoc, groupLeader, research,
  		nonResearch, student, prof,
  		prof-W2, prof-W3 }
  	{\DTLnewdbentry{\l_@@_database_name_tl}{position}{#1}},
  position / unknown .code:n = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{
  			PhD,~ postDoc,~ groupLeader,~ research,~
  			nonResearch,~ student,~ prof,~ prof-W2,~ prof-W3 }},
  positionText .code:n =  \DTLnewdbentry{\l_@@_database_name_tl}{positionText}{#1},
%    \end{macrocode}
% we need to figure out in which funding period the person was active. 
%    \begin{macrocode}
  period .code:n = {
  		\_@@_set_filtered_clist:Nnn \l_@@_person_tmp_period_clist { 1, 2, 3 } {#1}
  		\exp_args:Nnne \DTLnewdbentry{\l_@@_database_name_tl}{period}
                 { \clist_use:N  \l_@@_person_tmp_period_clist }
  	},
%    \end{macrocode}
% The following keys are used for the CV section (additionally |position|).
% We start with |name-alias| which is used to get the author’s name in bold
% letters into the publications list. Write all aliases of the author according
% to their appearence in the |.bib|-file. Encapsulate each with one pair of |{}|.
%    \begin{macrocode}
  name-alias   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{name-alias}{{#1}},
  orcid        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{orcid}{#1},
  email        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{email}{#1},
  phone        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{phone}{#1},
  url          .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{url}{#1},
  doctorateYear .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{doctorateYear}{#1},
  doctorate    .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{doctorate}{#1},
  degree-programme   .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{degree-programme}{#1},
%    \end{macrocode}
% Following part is for the early career researchers
%    \begin{macrocode}
  financed-by .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{financed-by}{#1},
  topic       .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{topic}{#1},
  category    .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{category}{#1},
  dateDefense .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{dateDefense}{#1},
  periodStart .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodStart}{#1},
  periodEnd .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodEnd}{#1},
%    \end{macrocode}
% For the PI we need to have information regarding their contract situation.
% Those questions are asked in the Header section of each project.
%    \begin{macrocode}
  contract-information .code:n = { \keys_set:nn { person / contract-information } { #1 } }
}
%    \end{macrocode}
%
% \paragraph{Helper: \cs{person\_questions\_invalid:n}}
% Small private helper used as the |unknown .code:n| handler for every
% boolean choice key in the |contract-information| and
% |project/legal-issues| key families.  It fires |dfg/invalid-value| with
% the allowed set hard-coded to |yes,no|.
%    \begin{macrocode}
\cs_new_protected:Npn \person_questions_invalid:n #1
{ \msg_warning:nnnn { dfg } { invalid-value } {#1} { yes , no } }


\keys_define:nn { person / contract-information }
{
  %--- yes/no questions -----------------------------------------------
  C1 .choices:nn = { yes , no }
  	{ \DTLnewdbentry{\l_@@_database_name_tl}{C1}{#1} },
  C1 / unknown .code:n = { \person_questions_invalid:n {#1} },

  C2 .choices:nn = { yes , no  }
  	{ \DTLnewdbentry{\l_@@_database_name_tl}{C2}{#1} },
  C2 / unknown .code:n = { \person_questions_invalid:n {#1} },

  C3 .choices:nn = { yes , no  }
  	{ \DTLnewdbentry{\l_@@_database_name_tl}{C3}{#1} },
  C3 / unknown .code:n = { \person_questions_invalid:n {#1} },

  C4 .choices:nn = {  yes , no  }
  	{ \DTLnewdbentry{\l_@@_database_name_tl}{C4}{#1} },
  C4 / unknown .code:n = { \person_questions_invalid:n {#1} },

  %--- free-form follow-ups (may be empty) ----------------------------
  C2a .code:n = { \dfg_contract_date:nn {C2a} {#1} },
  C2b .code:n = { \dfg_contract_date:nn {C2b} {#1} },
  C3a .code:n = { \dfg_contract_date:nn {C3a} {#1} },
  C4a .code:n = { \dfg_contract_text:nn {C4a} {#1} },
}

% Date follow-up: allows empty or ISO-8601 (YYYY-MM-DD).
\cs_new_protected:Npn \dfg_contract_date:nn #1#2
{
  \tl_if_blank:nTF {#2}
  { \DTLnewdbentry{\l_@@_database_name_tl}{#1}{} }
  {
  	\dfg_is_iso_date:nTF {#2}
  	{ \DTLnewdbentry{\l_@@_database_name_tl}{#1}{#2} }
  	{
  		\msg_warning:nnnn { dfg } { invalid-date } {#1} {#2}
  		\DTLnewdbentry{\l_@@_database_name_tl}{#1}{#2}
  	}
  }
}

% Plain-text follow-up: allows empty or any string.
\cs_new_protected:Npn \dfg_contract_text:nn #1#2
{
  \DTLnewdbentry{\l_@@_database_name_tl}{#1}{#2}
}

% Format check: YYYY-MM-DD where Y/M/D are digits.
% Doesn't validate calendar correctness (e.g. Feb 30) -- just shape.
\prg_new_protected_conditional:Npnn \dfg_is_iso_date:n #1 { TF , T , F }
{
  \regex_match:nnTF { \A \d{4} - \d{2} - \d{2} \Z } {#1}
  { \prg_return_true: }
  { \prg_return_false: }
}
%    \end{macrocode}
% \paragraph{Keyset \textbf{cv}}
% The |cv| database holds supplementary career information for each PI
% beyond what is already stored in the |person| row.  Multiple entries
% per person are permitted; each entry is identified by |ref-person-id|
% and a \refKey{cv-type} that governs where in the printed CV the item appears.
%
%    \begin{macrocode}
\keys_define:nn { cv }{
  id           .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  ref-person-id.code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-person-id}{#1},
  cv-type .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{type}{#1},
  cv-type .choices:nn =  {mandatory, supplement,
  		activities, supervision,
  		distinction, other }
  	{\DTLnewdbentry{\l_@@_database_name_tl}{type}{#1}},
  % Backward-compatibility alias for the former misspelling.
  cv-type / distinction .code:n = {			\DTLnewdbentry{\l_@@_database_name_tl}{type}{distinction}},
  cv-type / unknown .code:n = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{
  			mandatory,~ supplement,~
  			activities,~  supervision,~
  			distinction,~ other }},
  positionText .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{positionText}{#1},
  position .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{position}{#1},
  ref-institution-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-institution-id}{#1},
  description .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{description}{#1},
  periodStart .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodStart}{#1},
  periodEnd .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodEnd}{#1},
}
%    \end{macrocode}
% \paragraph{Keysets \textbf{affiliation} and \textbf{institution}}
% The template distinguishes between two levels of organisational unit:
%   affiliation: A \emph{university} or equivalent top-level
%     organisation, described by its full name, abbreviation, and postal
%     address.  Referenced from |person| rows via |ref-affiliation-id|.
%   institution: A \emph{department, institute or centre} within an
%     affiliation (e.g.\ |IT Center RWTH Aachen|).  Referenced from |person|
%     rows via |ref-institution-id| and from |affiliation| via
%     |ref-affiliation-id|.
%
% This two-level model allows the same address block to be reused across
% multiple people without duplicating data, and the same university to
% appear under different institute names for different projects.
%    \begin{macrocode}
\keys_define:nn { affiliation }
{
  id               .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id               .value_required:n = true,
  name             .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  abbreviation  .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{abbreviation}{#1},
  addressStreet    .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{addressStreet}{#1},
  addressZIP   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{addressZIP}{#1},
  location         .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{location}{#1},
  country          .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{country}{#1},
}
%    \end{macrocode}
%    \begin{macrocode}
\keys_define:nn { institution }
{
  id        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id        .value_required:n = true,
  name      .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  abbreviation .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{abbreviation}{#1},
  ref-affiliation-id  .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{ref-affiliation-id}{#1},
}

% Resolve the compact reader-facing institution label once.  Older metadata
% without an abbreviation remains usable by falling back to the full name.
\tl_new:N \l_@@_institution_label_field_tl
\cs_new_protected:Npn \@@_institution_abbreviation_or_name:nN #1#2
{
  \tl_clear:N #2
  \tl_set:Nn \l_@@_institution_label_field_tl { abbreviation }
  \datatool_if_has_key:nnTF { institution } { abbreviation }
  {
    \DTLgetvalueforkey{#2}{abbreviation}{institution}{id}{#1}
  }
  { }
  \DTLifnullorempty{#2}
  {
    \tl_set:Nn \l_@@_institution_label_field_tl { name }
    \DTLgetvalueforkey{#2}{name}{institution}{id}{#1}
  }
  { }
}
%    \end{macrocode}
% \paragraph{Keyset \textbf{funding}}
% One |funding| row represents a single requested-funding line item, such
% as one FTE of PhD salary across five years, or a one-off equipment
% purchase.  The same keyset is also used for\emph{existing} and
% \emph{previous} funding entries in the relevant tables.
%
% \textbf{|funding-type|}:
%   \refKey{staff}: Personnel costs.  Activates the restricted |category|
%     validation (only staff-position names are accepted).
%   \refKey{costs}: Direct project costs (consumables, travel, etc.).
%   \refKey{fellowships}: Stipend payments.
%   \refKey{globalfunds}: Funds requested at the CRC level (coordination).
%   \refKey{instrumentation}: Equipment purchases.
%
% \textbf{\refKey{quantity} and \refKey{sum}}: both accept a |funding/year| sub-keyset
% |{year1={n},year2={n},...}|.  The token-list variable
% \cs{l\_funding\_sum\_quantity\_tl} is set to the key name (|quantity| or
% |sum|) before the sub-parse so the |year\meta{n}| handlers can construct
% the correct database field name (|quantity-year1|, |sum-year2|, etc.)
% without extra parameters.
%    \begin{macrocode}
\str_new:N \l_@@_funding_tmp_type_str
\tl_new:N \l_funding_sum_quantity_tl
\clist_const:Nn \c_@@_funding_staff_categories_clist
  { prof, groupLeader, postDoc, medDoc, PhD, research,
    nonResearch, student, assistant }
\keys_define:nn { funding / year }
{
  year1 .code:n =
  	{\DTLnewdbentry{\l_@@_database_name_tl}{\tl_use:N \l_funding_sum_quantity_tl-year1}{#1}},
  year2 .code:n =
  	{\DTLnewdbentry{\l_@@_database_name_tl}{\tl_use:N \l_funding_sum_quantity_tl-year2}{#1}},
  year3 .code:n =
  	{\DTLnewdbentry{\l_@@_database_name_tl}{\tl_use:N \l_funding_sum_quantity_tl-year3}{#1}},
  year4 .code:n =
  	{\DTLnewdbentry{\l_@@_database_name_tl}{\tl_use:N \l_funding_sum_quantity_tl-year4}{#1}},
  year5 .code:n =
  	{\DTLnewdbentry{\l_@@_database_name_tl}{\tl_use:N \l_funding_sum_quantity_tl-year5}{#1}},
}

\keys_define:nn { funding }
{
  id        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id        .value_required:n = true,
  ref-project-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-project-id}{#1},
  ref-affiliation-id .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{ref-affiliation-id}{#1},
  financed-by .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{financed-by}{#1},
  funding-type .choices:nn =  {
  		staff,~ costs,~ fellowships,~ globalfunds,~ instrumentation }
  	{
  		\str_set:Nn \l_@@_funding_tmp_type_str {#1}
  		\DTLnewdbentry{\l_@@_database_name_tl}{type}{#1}
  	},
  funding-type / unknown .code:n = {\msg_warning:nnnn { dfg } { invalid-value }{ #1 }{
  			staff,~ costs,~ fellowships,~ globalfunds,~ instrumentation }},
  funding-type        .value_required:n = true,
  percentage .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{percentage}{#1},
  positionText .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{positionText}{#1},
  quantity .code:n = {
  		\tl_set:Nn \l_funding_sum_quantity_tl {quantity}
  		\keys_set:nn { funding / year  } { #1 }
  	},
  sum .code:n = {
  		\tl_set:Nn \l_funding_sum_quantity_tl {sum}
  		\keys_set:nn { funding / year  } { #1 }
  	},
  category .code:n =
  	{
  		\str_if_eq:VnTF \l_@@_funding_tmp_type_str { staff }
  		{% staff → restricted choices
        \clist_if_in:NnTF \c_@@_funding_staff_categories_clist {#1}
  			{
  				\DTLnewdbentry{\l_@@_database_name_tl}{category}{#1}
  			}
  			{
          \msg_warning:nnne { dfg } { invalid-value }{ #1 }
          { \clist_use:Nn \c_@@_funding_staff_categories_clist {,~} }
  			}
  		}
  		{
  			% non-staff → unrestricted
  			\DTLnewdbentry{\l_@@_database_name_tl}{category}{#1}
  		}
  	},
  % following keys are especially for the previous fundings
  year            .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{year}{#1}},
  applicant       .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{applicant}{#1}},
  participant     .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{participant}{#1}},
  other-funds     .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{other-funds}{#1}},
  staff           .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{staff}{#1}},
  costs           .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{costs}{#1}},
  instrumentation .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{instrumentation}{#1}},
  fellowships     .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{fellowships}{#1}},
  globalfunds     .code:n = {\DTLnewdbentry{\l_@@_database_name_tl}{globalfunds}{#1}},
}
%    \end{macrocode}
% A keyset for instrumentation.  The flat |cost| field belongs to the
% informational |existingInstrumentation| list, is expressed in thousands of
% EUR, and is never included in funding totals.  The nested |sum| fields are
% requested-funding amounts expressed in full EUR.
%    \begin{macrocode}
\keys_define:nn { instrumentation }{
  ref-project-id  .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-project-id}{#1},
  quantity        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{quantity}{#1},
  instrument      .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{instrument}{#1},
  company         .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{company}{#1},
  year            .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{year}{#1},
  cost            .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{cost}{#1},
  financed-by     .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{financed-by}{#1},
  description     .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{description}{#1},
  sum .code:n = {
  		\tl_set:Nn \l_funding_sum_quantity_tl {sum}
  		\keys_set:nn { funding / year  } { #1 }
  	},
}
%    \end{macrocode}
%
% \paragraph{Keyset \textbf{staff}}
% The |staff| key family serves two related personnel data shapes.  Its
% |year1|--|year5| subkeys store the headcount plan per position category for
% \cs{OverviewOfFundsRequestedForStaffTable}.  The flat keys added below store
% the named and unnamed staff roster required by the DFG project template in
% the fixed |RequestedFundingStaff| database.  All keys remain optional at the
% parser level so the older overview declarations continue to work unchanged;
% database-specific validation supplies useful warnings for roster entries.
%
% The \refKey{position} sub-keyset holds named keys for each staff category
% (|postDoc|, |PhD|, |research|, etc.); each key's value is the number of
% FTEs for a specific year.  \cs{l\_staff\_year\_tl} is set to |year1|--|year5|
% before each sub-parse so the handlers can construct the correct field name
% (e.g.\ |postDoc-year2|) without extra parameters.
%    \begin{macrocode}
\tl_new:N \l_staff_year_tl          % will hold “year1”, “year2”, …
\keys_define:nn { staff / position }{
  postDoc      .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{postDoc-\tl_use:N \l_staff_year_tl}{#1},
  PhD          .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{PhD-\tl_use:N \l_staff_year_tl}{#1},
  research     .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{research-\tl_use:N \l_staff_year_tl}{#1},
  nonResearch  .code:n = \DTLnewdbentry{\l_@@_database_name_tl}
  {nonResearch-\tl_use:N \l_staff_year_tl}{#1},
  student      .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{student-\tl_use:N \l_staff_year_tl}{#1},
}

% Category warnings list the currently registered keys, so the diagnostic
% stays in sync with the category-name property list, including extensions.
\seq_new:N \l_@@_diagnostic_keys_seq
\cs_new_protected:Npn \@@_collect_diagnostic_keys:N #1
{
  \seq_clear:N \l_@@_diagnostic_keys_seq
  \prop_map_inline:Nn #1
    { \seq_put_right:Nn \l_@@_diagnostic_keys_seq {##1} }
}
\cs_new_protected:Npn \@@_warn_unknown_name:nnN #1#2#3
{
  \@@_collect_diagnostic_keys:N #3
  \msg_warning:nneee { dfg } { unknown-name } {#1} {#2}
    { \seq_use:Nn \l_@@_diagnostic_keys_seq {,~} }
}
\cs_new_protected:Npn \@@_staff_set_category:n #1
{
  \prop_if_in:NnTF \g_@@_dfg_category_names_prop {#1}
  { \DTLnewdbentry{\l_@@_database_name_tl}{category}{#1} }
  {
    \@@_collect_diagnostic_keys:N \g_@@_dfg_category_names_prop
    \msg_warning:nnne { dfg } { invalid-value } {#1}
      { \seq_use:Nn \l_@@_diagnostic_keys_seq {,~} }
  }
}

\keys_define:nn { staff }{
  unknown .code:n = { \msg_warning:nnn { dfg } { unknown-key } {#1} },
  unknown .default:V = \c_novalue_tl,
  ref-project-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-project-id}{#1},
  funding-status .choices:nn = { existing, requested }
  { \DTLnewdbentry{\l_@@_database_name_tl}{funding-status}{#1} },
  funding-status / unknown .code:n =
  { \msg_warning:nnnn { dfg } { invalid-value } {#1} { existing,~requested } },
  staff-type .choices:nn = { research, nonResearch }
  { \DTLnewdbentry{\l_@@_database_name_tl}{staff-type}{#1} },
  staff-type / unknown .code:n =
  { \msg_warning:nnnn { dfg } { invalid-value } {#1} { research,~nonResearch } },
  ref-person-id .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{ref-person-id}{#1},
  firstname .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{firstname}{#1},
  lastname .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{lastname}{#1},
  academic-degree .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{academic-degree}{#1},
  positionText .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{positionText}{#1},
  position .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{positionText}{#1},
  field-of-research .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{field-of-research}{#1},
  ref-institution-id .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{ref-institution-id}{#1},
  ref-affiliation-id .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{ref-affiliation-id}{#1},
  department .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{department}{#1},
  commitment .code:n =
  {
    \regex_match:nnTF { \A \d+ (?: \. \d+ )? \Z }
      {#1}
    { \DTLnewdbentry{\l_@@_database_name_tl}{commitment}{#1} }
    { \msg_warning:nnnn { dfg } { invalid-format } {#1}
      { a~non-negative~integer~or~decimal~using~a~decimal~point,
        ~for~example~0,~10,~or~10.5 } }
  },
  category .code:n = \@@_staff_set_category:n {#1},
  funding-source .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{funding-source}{#1},
  description .code:n =
  \DTLnewdbentry{\l_@@_database_name_tl}{description}{#1},
  year1 .code:n = {
  		\tl_set:Nn \l_staff_year_tl {year1}
  		\keys_set:nn { staff / position  } { #1 }
  	},
  year2 .code:n = {
  		\tl_set:Nn \l_staff_year_tl {year2}
  		\keys_set:nn { staff / position  } { #1 }
  	},
  year3 .code:n = {
  		\tl_set:Nn \l_staff_year_tl {year3}
  		\keys_set:nn { staff / position  } { #1 }
  	},
  year4 .code:n = {
  		\tl_set:Nn \l_staff_year_tl {year4}
  		\keys_set:nn { staff / position  } { #1 }
  	},
  year5 .code:n = {
  		\tl_set:Nn \l_staff_year_tl {year5}
  		\keys_set:nn { staff / position  } { #1 }
  },
}

% Pre-create every roster column once.  Datatool can otherwise report an
% unknown column when an optional key is omitted by every row in the database.
\bool_new:N \g_@@_requested_funding_staff_schema_ready_bool
\cs_new_protected:Npn \@@_requested_funding_staff_ensure_schema:
{
  \bool_if:NF \g_@@_requested_funding_staff_schema_ready_bool
  {
    \clist_map_inline:nn
    {
      ref-project-id, funding-status, staff-type, ref-person-id,
      firstname, lastname, academic-degree, positionText, field-of-research,
      ref-institution-id, ref-affiliation-id, department, commitment, category,
      funding-source, description
    }
    {
      \DTLifhaskey { RequestedFundingStaff } {##1}
      { }
      { \DTLaddcolumn { RequestedFundingStaff } {##1} }
    }
    \bool_gset_true:N \g_@@_requested_funding_staff_schema_ready_bool
  }
}

\tl_new:N \l_@@_requested_funding_staff_validate_project_tl
\tl_new:N \l_@@_requested_funding_staff_validate_status_tl
\tl_new:N \l_@@_requested_funding_staff_validate_type_tl
\tl_new:N \l_@@_requested_funding_staff_validate_person_tl
\tl_new:N \l_@@_requested_funding_staff_validate_lastname_tl
\tl_new:N \l_@@_requested_funding_staff_validate_institution_tl
\keys_define:nn { dfg / requested-funding-staff-validation }
{
  ref-project-id .tl_set:N =
    \l_@@_requested_funding_staff_validate_project_tl,
  funding-status .tl_set:N =
    \l_@@_requested_funding_staff_validate_status_tl,
  staff-type .tl_set:N =
    \l_@@_requested_funding_staff_validate_type_tl,
  ref-person-id .tl_set:N =
    \l_@@_requested_funding_staff_validate_person_tl,
  lastname .tl_set:N =
    \l_@@_requested_funding_staff_validate_lastname_tl,
  ref-institution-id .tl_set:N =
    \l_@@_requested_funding_staff_validate_institution_tl,
  unknown .code:n = { }
}

\cs_new_protected:Npn
  \@@_requested_funding_staff_warn_missing_institution:
{
  \msg_warning:nne { dfg } { requested-staff-institution-required }
    { \l_@@_requested_funding_staff_validate_project_tl }
}

\cs_new_protected:Npn \@@_requested_funding_staff_validate:n #1
{
  \tl_clear:N \l_@@_requested_funding_staff_validate_project_tl
  \tl_clear:N \l_@@_requested_funding_staff_validate_status_tl
  \tl_clear:N \l_@@_requested_funding_staff_validate_type_tl
  \tl_clear:N \l_@@_requested_funding_staff_validate_person_tl
  \tl_clear:N \l_@@_requested_funding_staff_validate_lastname_tl
  \tl_clear:N \l_@@_requested_funding_staff_validate_institution_tl
  \keys_set:nn { dfg / requested-funding-staff-validation } {#1}
  \tl_if_blank:VT \l_@@_requested_funding_staff_validate_project_tl
  { \msg_warning:nnn { dfg } { requested-staff-required }
    { ref-project-id } }
  \tl_if_blank:VT \l_@@_requested_funding_staff_validate_status_tl
  { \msg_warning:nnn { dfg } { requested-staff-required }
    { funding-status } }
  \tl_if_blank:VT \l_@@_requested_funding_staff_validate_type_tl
  { \msg_warning:nnn { dfg } { requested-staff-required }
    { staff-type } }
  \bool_lazy_all:nT
  {
    { \tl_if_blank_p:V \l_@@_requested_funding_staff_validate_person_tl }
    { \tl_if_blank_p:V \l_@@_requested_funding_staff_validate_lastname_tl }
  }
  { \msg_warning:nnn { dfg } { requested-staff-required }
    { ref-person-id~or~lastname } }
  \bool_lazy_all:nT
  {
    { \tl_if_blank_p:V \l_@@_requested_funding_staff_validate_person_tl }
    { \tl_if_blank_p:V \l_@@_requested_funding_staff_validate_institution_tl }
  }
  { \@@_requested_funding_staff_warn_missing_institution: }
}
%    \end{macrocode}
% A keyset for the upkeep of laboratory animals.
%    \begin{macrocode}
\keys_define:nn { UpkeepLaboratoryAnimals }{
  ref-project-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-project-id}{#1},
  species .code:n =
    {
      \tl_set:Ne \l_tmpa_tl {\tl_trim_spaces:n {#1}}
      \prop_if_in:NeTF \l_@@_animal_types_prop {\l_tmpa_tl/label}
        {
          \exp_args:NnnV \DTLnewdbentry
            {\l_@@_database_name_tl}{species}\l_tmpa_tl
        }
        {
          \msg_warning:nnne {dfg}{invalid-value}{#1}
            {\seq_use:Nn \l_@@_animal_type_ids_seq {,~}}
        }
    },
  species   .value_required:n = true,
  quantity .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{quantity}{#1},
  weeks-kept .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{weeks-kept}{#1},
  purchasing-costs   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{purchasing-costs}{#1},
  requested-funds   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{requested-funds}{#1},
  existing-funds .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{existing-funds}{#1},
}
%    \end{macrocode}
% \paragraph{Keyset \textbf{gantt}}
% Each row in a |gantt-\meta{project}| database describes one Gantt bar.
% The grouped public WP keys are normalized to this legacy schema by
% \cs{addWP}; these low-level keys and their validation remain available to
% direct \cs{addEntry} callers.
% Bars share their \refKey{id} with the corresponding work-package label, so
% \cs{addWP} automatically creates a matching Gantt entry when called.
%
% \refKey{periodStart} and \refKey{periodEnd} are quarter numbers (1--16 for a standard
% 5-year CRC period).  Setting both to the same value suppresses the bar,
% allowing a work-package item to exist in the list without occupying space
% in the chart.
%
% \refKey{style} selects one of five visual styles for the bar.  Unknown styles
% fall back to |default| with a warning, so the chart always compiles.
% Empty or whitespace-only styles select |default| without a warning.
%    \begin{macrocode}
\keys_define:nn { gantt }{
  id          .code:n     =  \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  id          .value_required:n = true,
  name        .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  description .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{description}{#1},
  periodStart .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodStart}{#1},
  periodEnd   .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{periodEnd}{#1},
  style       .choices:nn =  { crosshatch,striped,important,alternative,default }
  	{\DTLnewdbentry{\l_@@_database_name_tl}{style}{#1}},
  style / unknown .code:n = {
      \tl_if_blank:nF {#1}
        {
          \msg_warning:nnnnn { dfg } { invalid-value-fallback }{#1}
          {crosshatch,~striped,~important,~alternative,~default}{default}
        }
  		\DTLnewdbentry{\l_@@_database_name_tl}{style}{default}
  	},
}
%    \end{macrocode}
% \subsection{Core data-access commands}
%
% The following commands form the primary user-facing API for reading
% and writing the datatool databases.  Together with the keyset
% definitions above they provide a strongly-typed, validated interface
% that prevents malformed data from silently entering the proposal.
%
% \paragraph{\cs{dfgShowTag} and \cs{dfgShowCalculatedTag}}
% Direct values use |db:id:field|; aggregates use the concise form
% |calc:command [db]|.  Successive labels alternate between two vertical levels.
% The complete marker has zero width, height, and depth in both prose and tables,
% so annotations cannot change line spacing or table-row height.  When
% \refKey{showtags-tables} is false, the wrapper returns its value unchanged
% while a |tblr| cell is being rendered.  The begin-document specialisation
% keeps the normal |showtags=false| path as cheap as the unannotated output.
% In fast-project mode, skipped metadata prevents resolving the destination
% row of a reference chain; the annotation records its source row and full
% requested field path instead.
%
%    \begin{macrocode}
\NewDocumentCommand{\dfgShowTag}{ m m m o }
{%
  % #1: id
  % #2: field of database
  % #3: value from database field
  % #4: custom field (optional, e.g. database name)
  \bool_if:NTF \l_@@_class_showtags_bool
  { \texorpdfstring{\@@_show_tag_direct:nnnn {#1}{#2}{#3}{#4}}{#3} }
  {#3}%
}

\NewDocumentCommand{\dfgShowCalculatedTag}{ m m +m }
{%
  % #1: calculation command or label
  % #2: contributing database(s)
  % #3: calculated value
  \bool_if:NTF \l_@@_class_showtags_bool
  { \texorpdfstring{\@@_show_tag_value:nn { calc:#1~[#2] } {#3}}{#3} }
  {#3}%
}

\cs_new_protected:Npn \@@_show_tag_direct:nnnn #1#2#3#4
{
  \IfNoValueTF{#4}
    { \@@_show_tag_value:nn { #1:#2 } {#3} }
    { \@@_show_tag_value:nn { #4:#1:#2 } {#3} }
}

\cs_new_protected:Npn \@@_show_tag_value:nn #1#2
{
  \bool_if:nTF
    { \g_@@_tblr_inside_bool && ! \l_@@_class_showtags_tables_bool }
    {#2}
    { \@@_show_tag_overlay:nn {#1}{#2} }
}

\bool_new:N \g_@@_show_tag_upper_bool
\bool_new:N \l_@@_show_tag_leftward_bool
\dim_new:N \l_@@_show_tag_raise_dim

\cs_new_protected:Npn \@@_show_tag_overlay:nn #1#2
{
  % #1: preformatted provenance label
  % #2: displayed value
  \group_begin:
    \bool_if:NTF \g_@@_show_tag_upper_bool
      { \dim_set:Nn \l_@@_show_tag_raise_dim { 1.30em } }
      { \dim_set:Nn \l_@@_show_tag_raise_dim { .9em } }
    \bool_gset_inverse:N \g_@@_show_tag_upper_bool
    \leavevmode
    \smash{%
      \vbox to \z@ {%
			\vss
			\color{color@tags@line}%
      \bool_if:NTF \l_@@_show_tag_leftward_bool
      {%
        \llap{%
          \raise \l_@@_show_tag_raise_dim \hbox{%
            \fontsize{4}{0}\selectfont
            \ttfamily
            #1\,%
          }%
          \vrule
        }%
      }
      {%
        \rlap{%
          \vrule
          \raise \l_@@_show_tag_raise_dim \hbox{%
            \fontsize{4}{0}\selectfont
            \ttfamily
            \,%
            #1%
          }%
        }%
      }%
      }%
    }%
    \textcolor{color@tags@font}{#2}%
  \group_end:
}

% Aggregated monetary tables use full euro amounts.  Guarded tagged cells must
% invoke \cs{TblrNum} explicitly so they still use the current column's
% |table-format| for a common SI field width; outside tables \cs{num} provides
% ordinary inline output.  Marginalia temporarily clear the table-context
% boolean and therefore remain unpadded.  The informational
% existing-instrumentation cost and per-animal unit costs are formatted
% separately because their source units and precision differ from aggregated
% funding values.
\cs_new_protected:Npn \@@_show_table_number:n #1
{
  \bool_if:NTF \g_@@_tblr_inside_bool
    { \TblrNum{#1} }
    { \num{#1} }
}

\cs_new_protected:Npn \@@_show_eur:n #1
{
  \bool_if:NTF \g_@@_tblr_inside_bool
    { \TblrNum{#1} }
    {
      \num[
        round-mode = places,
        round-precision = 0
      ]{#1}
    }
}

% Existing-instrumentation costs are supplied in thousands of EUR and are not
% included in any funding aggregate.  Match the DFG table's one-decimal
% precision while still suppressing a redundant trailing zero.  The literal
% |n.a.| sentinel denotes an unavailable purchase cost and bypasses the number
% parser in both table and inline contexts; it is never converted to zero.
\cs_new_protected:Npn \@@_show_existing_instrumentation_cost:n #1
{
  \str_if_eq:eeTF {#1} {n.a.}
    { \textnormal{n.a.} }
    {
      \bool_if:NTF \g_@@_tblr_inside_bool
        { \TblrNum{#1} }
        {
          \num[
            round-mode = places,
            round-precision = 1
          ]{#1}
        }
    }
}

\cs_new_protected:Npn \@@_show_calculated_number:nnN #1#2#3
{
  \dfgShowCalculatedTag{#1}{#2}
  { \exp_args:NV \@@_show_eur:n #3 }
}

\AtBeginDocument{%
  \bool_if:NTF \l_@@_class_showtags_bool
  {%
    \RenewDocumentCommand{\dfgShowTag}{ m m m o }
    { \texorpdfstring{\@@_show_tag_direct:nnnn {#1}{#2}{#3}{#4}}{#3} }%
    \RenewDocumentCommand{\dfgShowCalculatedTag}{ m m +m }
    { \texorpdfstring{\@@_show_tag_value:nn { calc:#1~[#2] } {#3}}{#3} }%
  }
  {%
    \RenewDocumentCommand{\dfgShowTag}{ m m m o }
    {#3}%
    \RenewDocumentCommand{\dfgShowCalculatedTag}{ m m +m }
    {#3}%
  }%
}

%    \end{macrocode}
% \begin{macro}{\addEntry}
% \cs{addEntry} \oarg{keys} \marg{database} \marg{key-values}
% Adds a new row to the database named \meta{database}, populated by
% setting the keys defined under the key-path \meta{keys} from
% \meta{key-values}. If \meta{keys} is omitted, it defaults to the
% database name (\meta{database}).
%
% The \texttt{cv} database receives special treatment: entries are only
% recorded when the boolean \cs{l\_dfg\_class\_cv\_bool} is true (i.e.\ when
% a CV is actually being produced). Otherwise the entry is skipped and
% a warning is issued, so that bibliography-style CV entries can be left
% in the source unconditionally without polluting non-CV builds.
%
% The internal helper \cs{\_\_dfg\_add\_entry:nnn} performs the actual
% insertion and is shared between both branches to avoid code
% duplication.
%
% Funding declarations for |RequestedFunding| may occur in project files,
% after the proposal-wide overview tables have already been printed.  Such
% entries are additionally written to the current LaTeX auxiliary file and
% restored on the following run into |RequestedFundingOverview|.  Entries
% encountered before \cs{begin}|{document}| are copied into that overview
% database immediately.  Consequently the declarations remain next to their
% project text, while overview tables have access to the complete data set
% after the usual additional LaTeX run.  A separate database prevents the
% restored rows from duplicating the live rows used by the project tables.
% The same forward-data mechanism copies |RequestedFundingStaff| declarations
% to |RequestedFundingStaffOverview| and
% |RequestedAndExistingFundingDirectCosts| declarations to
% |RequestedAndExistingFundingDirectCostsOverview|.  Chapter 2 can therefore
% aggregate the existing staff and institutional direct-cost support declared
% later in the individual project chapters without a second user-maintained
% database.
%
% \paragraph{Funding aggregate indexes}
% The funding databases remain the authoritative row store.  In addition,
% every funding declaration updates two LaTeX3 property lists: one for
% monetary sums grouped by database, project, funding type, and year field;
% and one for staff quantities grouped by database, project, category, and
% year field.  Each index also stores the corresponding all-project and
% all-type aggregate where applicable.
%
% Both live declarations and rows restored from auxiliary files pass through
% the same registration function.  The indexes therefore remain correct as
% later project files add entries; there is no one-shot cache to invalidate.
% Summary cells perform a property lookup instead of traversing the growing
% database.  Detailed project tables still read their source rows, but collect
% all five funding types in one project-filtered traversal rather than five.
%
% \paragraph{Complete-proposal benchmark}
% The 149-page complete proposal was measured on 2026-07-17 with LuaHBTeX from
% TeX Live 2026.  Times below are for one final LuaLaTeX pass and compare the
% same proposal data before and after the aggregate-index refactor.  Absolute
% values depend on the machine and document contents; the important result is
% that lookup time no longer grows through repeated full database sums.
%
% \begin{center}
% \begin{tabular}{lrrr}
% \hline
% Operation & Before & After & Reduction \\
% \hline
% Staff overview & 135.745\,s & 6.975\,s & 94.9\,\% \\
% Instrumentation overview & 5.239\,s & 0.636\,s & 87.9\,\% \\
% 21 requested-funding tables & 90.444\,s & 28.831\,s & 68.1\,\% \\
% 19 existing-funding tables & 23.277\,s & 6.605\,s & 71.6\,\% \\
% \hline
% Combined & 254.705\,s & 43.047\,s & 83.1\,\% \\
% \hline
% \end{tabular}
% \end{center}
%
% This saves approximately 211.7 seconds per LuaLaTeX pass.  The monitored
% three-pass \texttt{make complete-proposal} release build completed in
% 33 minutes 21 seconds, so the funding changes account for approximately
% 10 minutes 35 seconds of avoided work across that build.
%    \begin{macrocode}
\tl_new:N \l_@@_add_entry_id_tl
\tl_new:N \l_@@_add_entry_existing_row_tl

\keys_define:nn { dfg / add-entry-id-probe }
{
  id      .tl_set:N = \l_@@_add_entry_id_tl,
  unknown .code:n   = { }
}

\cs_new_protected:Npn \@@_add_entry_replace_duplicate_id:n #1
{
  \tl_clear:N \l_@@_add_entry_id_tl
  \keys_set:nn { dfg / add-entry-id-probe } {#1}
  \tl_if_blank:VF \l_@@_add_entry_id_tl
  {
    \DTLifhaskey { \l_@@_database_name_tl } { id }
    {
      \DTLgetrowforkey
        { \l_@@_add_entry_existing_row_tl }
        { \l_@@_database_name_tl }
        { id }
        { \l_@@_add_entry_id_tl }
      \tl_if_blank:VF \l_@@_add_entry_existing_row_tl
      {
        \msg_warning:nnee { dfg } { duplicate-entry-id }
          { \l_@@_database_name_tl }
          { \l_@@_add_entry_id_tl }
        \DTLforeach { \l_@@_database_name_tl }
          { \l_tmpa_tl = id }
        {
          \str_if_eq:VVT \l_tmpa_tl \l_@@_add_entry_id_tl
            { \DTLremovecurrentrow }
        }
      }
    }
    { }
  }
}

\cs_new_protected:Npn \@@_add_entry:nnn #1#2#3
{
  % #1: keys     #2: database     #3: key-values
  \group_begin:
  \tl_set:Nn \l_@@_database_name_tl {#2}
  \DTLifdbexists {#2}
  { }
  { \DTLaction [ name = \l_@@_database_name_tl ] { new } }
  \@@_add_entry_replace_duplicate_id:n {#3}
  \bool_lazy_all:nT
  {
    { \str_if_eq_p:nn {#1} { staff } }
    { \str_if_eq_p:nn {#2} { RequestedFundingStaff } }
  }
  {
    \@@_requested_funding_staff_ensure_schema:
    \@@_requested_funding_staff_validate:n {#3}
  }
  \DTLaction [ name = \l_@@_database_name_tl ] { new~row }
  \str_if_eq:nnT {#1} { project }
  {
    \bool_set_true:N  \l_@@_project_consider_for_lists_bool
    \bool_set_false:N \l_@@_project_reference_only_bool
  }
  \exp_args:Ne \keys_set:nn {#1} {#3}
  \str_if_eq:nnT {#1} { project }
  {
    \bool_if:NTF \l_@@_project_consider_for_lists_bool
      { \DTLnewdbentry{\l_@@_database_name_tl}{consider-for-lists}{true} }
      { \DTLnewdbentry{\l_@@_database_name_tl}{consider-for-lists}{false} }
    \bool_if:NTF \l_@@_project_reference_only_bool
      { \DTLnewdbentry{\l_@@_database_name_tl}{reference-only}{true} }
      { \DTLnewdbentry{\l_@@_database_name_tl}{reference-only}{false} }
    \bool_gset_false:N \g_@@_project_count_ready_bool
  }
  \bool_lazy_all:nT
  {
    { \str_if_eq_p:nn {#1} { funding } }
    { \str_if_eq_p:Vn \l_@@_funding_tmp_type_str { staff } }
  }
  { \@@_funding_complete_staff_sums:n {#3} }
  \group_end:
}

% Funding tables repeatedly ask for the same sums, sometimes hundreds of
% times while tabularray measures a table.  Keep the datatool databases as
% the row store, but maintain compact aggregate indexes alongside them.
% The key layout is
%
%   database / project-or-__ALL__ / type-or-__ALL__ / field
%
% for monetary sums and
%
%   database / project-or-__ALL__ / category / quantity-field
%
% for requested staff quantities.  Values are added when an entry is
% declared, so a lookup never has to traverse a datatool database and the
% index cannot become stale when later project files add more rows.
\prop_new:N \g_@@_funding_sum_prop
\prop_new:N \g_@@_funding_staff_quantity_prop
\fp_new:N   \l_@@_funding_cache_fp
\tl_new:N   \l_@@_funding_cache_key_tl
\tl_new:N   \l_@@_funding_cache_value_tl
\tl_new:N   \l_@@_funding_cache_project_tl
\tl_new:N   \l_@@_funding_cache_type_tl
\tl_new:N   \l_@@_funding_cache_category_tl
\tl_new:N   \l_@@_funding_cache_percentage_tl
\tl_new:N   \l_@@_funding_salary_command_tl
\tl_new:N   \l_@@_funding_salary_value_tl
\tl_new:N   \l_@@_funding_cache_sum_one_tl
\tl_new:N   \l_@@_funding_cache_sum_two_tl
\tl_new:N   \l_@@_funding_cache_sum_three_tl
\tl_new:N   \l_@@_funding_cache_sum_four_tl
\tl_new:N   \l_@@_funding_cache_sum_five_tl
\tl_new:N   \l_@@_funding_cache_quantity_one_tl
\tl_new:N   \l_@@_funding_cache_quantity_two_tl
\tl_new:N   \l_@@_funding_cache_quantity_three_tl
\tl_new:N   \l_@@_funding_cache_quantity_four_tl
\tl_new:N   \l_@@_funding_cache_quantity_five_tl
\bool_new:N \l_@@_funding_calculation_store_bool
\bool_new:N \l_@@_funding_calculation_ready_bool
\bool_new:N \l_@@_funding_calculation_needed_bool

\prop_new:N \g_@@_funding_salary_commands_prop
\prop_gset_from_keyval:Nn \g_@@_funding_salary_commands_prop
{
  prof        = dfgSalaryProf,
  groupLeader = dfgSalaryGroupLeader,
  postDoc     = dfgSalaryPostDoc,
  medDoc      = dfgSalaryMedDoc,
  PhD         = dfgSalaryPhD,
  research    = dfgSalaryResearch,
  nonResearch = dfgSalaryNonResearch,
  student     = dfgSalaryStudent,
  assistant   = dfgSalaryAssistant,
  prof-W2     = dfgSalaryProf,
  prof-W3     = dfgSalaryProf
}

\keys_define:nn { dfg / funding-cache / sum }
{
  year1 .tl_set:N = \l_@@_funding_cache_sum_one_tl,
  year2 .tl_set:N = \l_@@_funding_cache_sum_two_tl,
  year3 .tl_set:N = \l_@@_funding_cache_sum_three_tl,
  year4 .tl_set:N = \l_@@_funding_cache_sum_four_tl,
  year5 .tl_set:N = \l_@@_funding_cache_sum_five_tl,
  unknown .code:n = { }
}

\keys_define:nn { dfg / funding-cache / quantity }
{
  year1 .tl_set:N = \l_@@_funding_cache_quantity_one_tl,
  year2 .tl_set:N = \l_@@_funding_cache_quantity_two_tl,
  year3 .tl_set:N = \l_@@_funding_cache_quantity_three_tl,
  year4 .tl_set:N = \l_@@_funding_cache_quantity_four_tl,
  year5 .tl_set:N = \l_@@_funding_cache_quantity_five_tl,
  unknown .code:n = { }
}

\keys_define:nn { dfg / funding-cache }
{
  ref-project-id .tl_set:N = \l_@@_funding_cache_project_tl,
  funding-type   .tl_set:N = \l_@@_funding_cache_type_tl,
  category       .tl_set:N = \l_@@_funding_cache_category_tl,
  percentage     .tl_set:N = \l_@@_funding_cache_percentage_tl,
  sum .code:n =
    { \keys_set:nn { dfg / funding-cache / sum } {#1} },
  quantity .code:n =
    { \keys_set:nn { dfg / funding-cache / quantity } {#1} },
  unknown .code:n = { }
}

\cs_new_protected:Npn \@@_funding_capture:n #1
{
  \tl_clear:N \l_@@_funding_cache_project_tl
  \tl_clear:N \l_@@_funding_cache_type_tl
  \tl_clear:N \l_@@_funding_cache_category_tl
  \tl_clear:N \l_@@_funding_cache_percentage_tl
  \tl_clear:N \l_@@_funding_cache_sum_one_tl
  \tl_clear:N \l_@@_funding_cache_sum_two_tl
  \tl_clear:N \l_@@_funding_cache_sum_three_tl
  \tl_clear:N \l_@@_funding_cache_sum_four_tl
  \tl_clear:N \l_@@_funding_cache_sum_five_tl
  \tl_clear:N \l_@@_funding_cache_quantity_one_tl
  \tl_clear:N \l_@@_funding_cache_quantity_two_tl
  \tl_clear:N \l_@@_funding_cache_quantity_three_tl
  \tl_clear:N \l_@@_funding_cache_quantity_four_tl
  \tl_clear:N \l_@@_funding_cache_quantity_five_tl
  \keys_set:nn { dfg / funding-cache } {#1}
}

\cs_new_protected:Npn \@@_funding_calculation_needed:NN #1#2
{
  \bool_lazy_all:nT
  {
    { \tl_if_blank_p:V #1 }
    { ! \tl_if_blank_p:V #2 }
  }
  { \bool_set_true:N \l_@@_funding_calculation_needed_bool }
}

\cs_new_protected:Npn \@@_funding_calculate_one:NNnn #1#2#3#4
{
  % #1 sum tl, #2 quantity tl, #3 database field, #4 period factor
  \bool_lazy_all:nT
  {
    { \tl_if_blank_p:V #1 }
    { ! \tl_if_blank_p:V #2 }
    { \bool_if_p:N \l_@@_funding_calculation_ready_bool }
  }
  {
    \exp_args:NnV \regex_match:nnTF
      { \A \d+ (?: \. \d+ )? \Z } #2
    {
      \tl_set:Nx #1
      {
        \fp_eval:n
        {
          round(
            \l_@@_funding_salary_value_tl
            * \l_@@_funding_cache_percentage_tl / 100
            * #2
            * #4,
            0
          )
        }
      }
      \bool_if:NT \l_@@_funding_calculation_store_bool
      {
        \exp_args:Nnne \DTLnewdbentry
          {\l_@@_database_name_tl}{#3}{\tl_use:N #1}
      }
    }
    {
      \bool_if:NT \l_@@_funding_calculation_store_bool
      {
        \msg_warning:nne { dfg } { funding-staff-cost-unavailable }
        { project~'\l_@@_funding_cache_project_tl',~#3:~invalid~quantity~'#2' }
      }
    }
  }
}

\cs_new_protected:Npn \@@_funding_calculate_staff_sums:
{
  \str_if_eq:VnT \l_@@_funding_cache_type_tl { staff }
  {
    \bool_set_false:N \l_@@_funding_calculation_needed_bool
    \@@_funding_calculation_needed:NN
      \l_@@_funding_cache_sum_one_tl \l_@@_funding_cache_quantity_one_tl
    \@@_funding_calculation_needed:NN
      \l_@@_funding_cache_sum_two_tl \l_@@_funding_cache_quantity_two_tl
    \@@_funding_calculation_needed:NN
      \l_@@_funding_cache_sum_three_tl \l_@@_funding_cache_quantity_three_tl
    \@@_funding_calculation_needed:NN
      \l_@@_funding_cache_sum_four_tl \l_@@_funding_cache_quantity_four_tl
    \@@_funding_calculation_needed:NN
      \l_@@_funding_cache_sum_five_tl \l_@@_funding_cache_quantity_five_tl
    \bool_if:NT \l_@@_funding_calculation_needed_bool
    {
      \bool_set_true:N \l_@@_funding_calculation_ready_bool
      \prop_get:NVNTF \g_@@_funding_salary_commands_prop
        \l_@@_funding_cache_category_tl \l_@@_funding_salary_command_tl
      {
        \cs_if_exist:cTF { \l_@@_funding_salary_command_tl }
        { \tl_set:Nx \l_@@_funding_salary_value_tl
          { \use:c { \l_@@_funding_salary_command_tl } } }
        { \bool_set_false:N \l_@@_funding_calculation_ready_bool }
      }
      { \bool_set_false:N \l_@@_funding_calculation_ready_bool }
      \exp_args:NnV \regex_match:nnF
        { \A \d+ (?: \. \d+ )? \Z }
        \l_@@_funding_cache_percentage_tl
      { \bool_set_false:N \l_@@_funding_calculation_ready_bool }
      \exp_args:NnV \regex_match:nnF
        { \A \d+ (?: \. \d+ )? \Z }
        \l_@@_funding_salary_value_tl
      { \bool_set_false:N \l_@@_funding_calculation_ready_bool }
      \bool_lazy_all:nT
      {
        { \bool_if_p:N \l_@@_funding_calculation_store_bool }
        { ! \bool_if_p:N \l_@@_funding_calculation_ready_bool }
      }
      {
        \msg_warning:nne { dfg } { funding-staff-cost-unavailable }
        {
          project~'\l_@@_funding_cache_project_tl',~category~
          '\l_@@_funding_cache_category_tl',~percentage~
          '\l_@@_funding_cache_percentage_tl'
        }
      }
      \@@_funding_calculate_one:NNnn
        \l_@@_funding_cache_sum_one_tl
        \l_@@_funding_cache_quantity_one_tl { sum-year1 } { 0.5 }
      \@@_funding_calculate_one:NNnn
        \l_@@_funding_cache_sum_two_tl
        \l_@@_funding_cache_quantity_two_tl { sum-year2 } { 1 }
      \@@_funding_calculate_one:NNnn
        \l_@@_funding_cache_sum_three_tl
        \l_@@_funding_cache_quantity_three_tl { sum-year3 } { 1 }
      \@@_funding_calculate_one:NNnn
        \l_@@_funding_cache_sum_four_tl
        \l_@@_funding_cache_quantity_four_tl { sum-year4 } { 1 }
      \@@_funding_calculate_one:NNnn
        \l_@@_funding_cache_sum_five_tl
        \l_@@_funding_cache_quantity_five_tl { sum-year5 } { 0.5 }
    }
  }
}

\cs_new_protected:Npn \@@_funding_complete_staff_sums:n #1
{
  \bool_set_true:N \l_@@_funding_calculation_store_bool
  \@@_funding_capture:n {#1}
  \@@_funding_calculate_staff_sums:
}

\cs_new_protected:Npn \@@_funding_cache_add:Nnn #1#2#3
{
  \tl_set:Nx \l_@@_funding_cache_key_tl {#2}
  \tl_set:Nx \l_@@_funding_cache_value_tl {#3}
  \tl_if_blank:VF \l_@@_funding_cache_value_tl
  {
    \prop_get:NVNTF #1
      \l_@@_funding_cache_key_tl \l_@@_funding_cache_value_tl
    {
      \fp_set:Nn \l_@@_funding_cache_fp
        { \l_@@_funding_cache_value_tl + (#3) }
    }
    { \fp_set:Nn \l_@@_funding_cache_fp {#3} }
    \prop_gput:NVx #1 \l_@@_funding_cache_key_tl
      { \fp_to_decimal:N \l_@@_funding_cache_fp }
  }
}

\cs_new_protected:Npn \@@_funding_cache_sum_year:nnn #1#2#3
{
  % #1 database, #2 field, #3 value
  \tl_if_blank:VF \l_@@_funding_cache_type_tl
  {
    \@@_funding_cache_add:Nnn \g_@@_funding_sum_prop
      {#1/\l_@@_funding_cache_project_tl/
       \l_@@_funding_cache_type_tl/#2} {#3}
    \@@_funding_cache_add:Nnn \g_@@_funding_sum_prop
      {#1/__ALL__/\l_@@_funding_cache_type_tl/#2} {#3}
  }
  \@@_funding_cache_add:Nnn \g_@@_funding_sum_prop
    {#1/\l_@@_funding_cache_project_tl/__ALL__/#2} {#3}
  \@@_funding_cache_add:Nnn \g_@@_funding_sum_prop
    {#1/__ALL__/__ALL__/#2} {#3}
}

\cs_new_protected:Npn \@@_funding_cache_quantity_year:nnn #1#2#3
{
  % #1 database, #2 field, #3 value
  \@@_funding_cache_add:Nnn \g_@@_funding_staff_quantity_prop
    {#1/\l_@@_funding_cache_project_tl/
     \l_@@_funding_cache_category_tl/#2} {#3}
  \@@_funding_cache_add:Nnn \g_@@_funding_staff_quantity_prop
    {#1/__ALL__/\l_@@_funding_cache_category_tl/#2} {#3}
}

\cs_new_protected:Npn \@@_funding_cache_entry:nn #1#2
{
  \group_begin:
  \bool_set_false:N \l_@@_funding_calculation_store_bool
  \@@_funding_capture:n {#2}
  \@@_funding_calculate_staff_sums:
  \tl_if_blank:VF \l_@@_funding_cache_project_tl
  {
    \@@_funding_cache_sum_year:nnn {#1} {sum-year1}
      {\l_@@_funding_cache_sum_one_tl}
    \@@_funding_cache_sum_year:nnn {#1} {sum-year2}
      {\l_@@_funding_cache_sum_two_tl}
    \@@_funding_cache_sum_year:nnn {#1} {sum-year3}
      {\l_@@_funding_cache_sum_three_tl}
    \@@_funding_cache_sum_year:nnn {#1} {sum-year4}
      {\l_@@_funding_cache_sum_four_tl}
    \@@_funding_cache_sum_year:nnn {#1} {sum-year5}
      {\l_@@_funding_cache_sum_five_tl}
    \str_if_eq:VnT \l_@@_funding_cache_type_tl {staff}
    {
      \tl_if_blank:VF \l_@@_funding_cache_category_tl
      {
        \@@_funding_cache_quantity_year:nnn {#1} {quantity-year1}
          {\l_@@_funding_cache_quantity_one_tl}
        \@@_funding_cache_quantity_year:nnn {#1} {quantity-year2}
          {\l_@@_funding_cache_quantity_two_tl}
        \@@_funding_cache_quantity_year:nnn {#1} {quantity-year3}
          {\l_@@_funding_cache_quantity_three_tl}
        \@@_funding_cache_quantity_year:nnn {#1} {quantity-year4}
          {\l_@@_funding_cache_quantity_four_tl}
        \@@_funding_cache_quantity_year:nnn {#1} {quantity-year5}
          {\l_@@_funding_cache_quantity_five_tl}
      }
    }
  }
  \group_end:
}

\cs_new_protected:Npn \@@_funding_sum_set:Nnnnn #1#2#3#4#5
{
  % #1 result, #2 database, #3 project, #4 type, #5 field list
  \fp_zero:N \l_@@_funding_cache_fp
  \clist_map_inline:nn {#5}
  {
    \tl_set:Nx \l_@@_funding_cache_key_tl {#2/#3/#4/##1}
    \prop_get:NVNT \g_@@_funding_sum_prop
      \l_@@_funding_cache_key_tl \l_@@_funding_cache_value_tl
    {
      \fp_add:Nn \l_@@_funding_cache_fp
        { \l_@@_funding_cache_value_tl }
    }
  }
  \tl_set:Nx #1 { \fp_to_decimal:N \l_@@_funding_cache_fp }
}

\bool_new:N \g_@@_document_started_bool

\AtBeginDocument
  { \bool_gset_true:N \g_@@_document_started_bool }

% This command is deliberately public and free of expl3 punctuation because
% it is written to, and subsequently read from, LaTeX .aux files.
\NewDocumentCommand \dfgRestoreRequestedFunding { +m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \@@_add_entry:nnn { funding } { RequestedFundingOverview } {#1}
    \@@_funding_cache_entry:nn { RequestedFundingOverview } {#1}
  }
}

% This public command is written to the auxiliary file.  Keep its name free of
% expl3 punctuation so LaTeX can read it before the document body starts.
\cs_new_protected:Npn \@@_requested_funding_staff_overview_ensure_schema:
{
  \DTLifdbexists { RequestedFundingStaffOverview }
  { }
  { \DTLaction [ name = RequestedFundingStaffOverview ] { new } }
  \clist_map_inline:nn
  {
    ref-project-id, funding-status, staff-type, ref-person-id,
    firstname, lastname, academic-degree, positionText, field-of-research,
    ref-institution-id, ref-affiliation-id, department, commitment, category,
    funding-source, description
  }
  {
    \DTLifhaskey { RequestedFundingStaffOverview } {##1}
    { }
    { \DTLaddcolumn { RequestedFundingStaffOverview } {##1} }
  }
}

\NewDocumentCommand \dfgRestoreRequestedFundingStaff { +m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \@@_requested_funding_staff_overview_ensure_schema:
    \@@_add_entry:nnn { staff } { RequestedFundingStaffOverview } {#1}
  }
}

\bool_if:NF \l_@@_class_fastcompile_project_bool
{ \@@_requested_funding_staff_overview_ensure_schema: }

% Existing direct-cost rows are normally declared in the individual project
% descriptions, after section 2.1.1 has already been typeset.  Mirror them to
% a dedicated overview database so that the project table keeps using its live
% rows without counting the restored rows twice.
\cs_new_protected:Npn
  \@@_requested_and_existing_direct_costs_overview_ensure_schema:
{
  \DTLifdbexists { RequestedAndExistingFundingDirectCostsOverview }
  { }
  { \DTLaction [ name = RequestedAndExistingFundingDirectCostsOverview ] { new } }
  \clist_map_inline:nn
  {
    ref-project-id, ref-affiliation-id, financed-by,
    sum-year1, sum-year2, sum-year3, sum-year4, sum-year5
  }
  {
    \DTLifhaskey { RequestedAndExistingFundingDirectCostsOverview } {##1}
    { }
    { \DTLaddcolumn { RequestedAndExistingFundingDirectCostsOverview } {##1} }
  }
}

% This public command is written to the auxiliary file.  Its name deliberately
% contains no expl3 punctuation so that LaTeX can read it at the start of the
% following run.
\NewDocumentCommand \dfgRestoreRequestedAndExistingFundingDirectCosts { +m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \@@_requested_and_existing_direct_costs_overview_ensure_schema:
    \@@_add_entry:nnn { funding }
      { RequestedAndExistingFundingDirectCostsOverview } {#1}
  }
}

\bool_if:NF \l_@@_class_fastcompile_project_bool
{ \@@_requested_and_existing_direct_costs_overview_ensure_schema: }

% Keep the overview tables usable on the first run, before any project-local
% entries have reached the auxiliary files.  A newly created database has no
% columns, so establish the RequestedFunding schema explicitly: otherwise
% sorting or filtering an empty overview raises ``No sort columns'' and
% ``Unknown column key'' errors.  No placeholder row is required.
\bool_if:NF \l_@@_class_fastcompile_project_bool
{
  \DTLifdbexists { RequestedFundingOverview }
    { }
    {
      \DTLaction [ name = RequestedFundingOverview ] { new }
      \DTLaddcolumn { RequestedFundingOverview } { ref-project-id }
      \DTLaddcolumn { RequestedFundingOverview } { type }
      \DTLaddcolumn { RequestedFundingOverview } { category }
      \DTLaddcolumn { RequestedFundingOverview } { percentage }
      \DTLaddcolumn { RequestedFundingOverview } { quantity-year1 }
      \DTLaddcolumn { RequestedFundingOverview } { quantity-year2 }
      \DTLaddcolumn { RequestedFundingOverview } { quantity-year3 }
      \DTLaddcolumn { RequestedFundingOverview } { quantity-year4 }
      \DTLaddcolumn { RequestedFundingOverview } { quantity-year5 }
      \DTLaddcolumn { RequestedFundingOverview } { sum-year1 }
      \DTLaddcolumn { RequestedFundingOverview } { sum-year2 }
      \DTLaddcolumn { RequestedFundingOverview } { sum-year3 }
      \DTLaddcolumn { RequestedFundingOverview } { sum-year4 }
      \DTLaddcolumn { RequestedFundingOverview } { sum-year5 }
    }
}

\cs_new_protected:Npn \@@_cache_requested_funding:n #1
{
  \bool_if:NTF \g_@@_document_started_bool
  {
    \iow_now:Nx \@auxout
      {
        \token_to_str:N \dfgRestoreRequestedFunding
        { \exp_not:n {#1} }
      }
  }
  { \dfgRestoreRequestedFunding{#1} }
}

\cs_new_protected:Npn \@@_cache_requested_funding_staff:n #1
{
  \bool_if:NTF \g_@@_document_started_bool
  {
    \iow_now:Nx \@auxout
    {
      \token_to_str:N \dfgRestoreRequestedFundingStaff
      { \exp_not:n {#1} }
    }
  }
  { \dfgRestoreRequestedFundingStaff{#1} }
}

\cs_new_protected:Npn
  \@@_cache_requested_and_existing_direct_costs:n #1
{
  \bool_if:NTF \g_@@_document_started_bool
  {
    \iow_now:Nx \@auxout
    {
      \token_to_str:N \dfgRestoreRequestedAndExistingFundingDirectCosts
      { \exp_not:n {#1} }
    }
  }
  { \dfgRestoreRequestedAndExistingFundingDirectCosts{#1} }
}

% Focused project builds retain the project rows needed by generated plots when
% images are enabled, plus the rows needed by the three local funding tables.
% In particular, do not populate or restore any proposal-wide overview database
% through the auxiliary file.
\cs_new_protected:Npn \@@_fast_project_add_entry:nnn #1#2#3
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_images_bool
  {
    \str_if_eq:nnT {#1/#2} {/project}
      { \@@_add_entry:nnn {project} {project} {#3} }
    \str_if_eq:nnT {#1} {gantt}
      { \@@_add_entry:nnn {#1} {#2} {#3} }
  }
  \bool_if:NT \l_@@_class_fastcompile_project_show_funding_tables_bool
  {
    \str_case:nn {#1/#2}
    {
      {funding/RequestedFunding}
      {
        \@@_add_entry:nnn {#1} {#2} {#3}
        \@@_funding_cache_entry:nn {#2} {#3}
      }
      {staff/RequestedFundingStaff}
        { \@@_add_entry:nnn {#1} {#2} {#3} }
      {funding/RequestedAndExistingFundingDirectCosts}
      {
        \@@_add_entry:nnn {#1} {#2} {#3}
        \@@_funding_cache_entry:nn {#2} {#3}
      }
    }
  }
}

% Retain only the database-to-keyset mapping when focused builds skip rows.
% The get parser needs the schema to consume reference paths without values.
\prop_new:N \g_@@_database_keyset_prop
\NewDocumentCommand \addEntry { O{} m m }
{
  \tl_if_blank:nTF {#1}
    {\prop_gput:Nnn \g_@@_database_keyset_prop {#2}{#2}}
    {\prop_gput:Nnn \g_@@_database_keyset_prop {#2}{#1}}
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \@@_fast_project_add_entry:nnn {#1} {#2} {#3} }
  {
  \tl_if_eq:nnTF {#1} { cv }
  { \bool_if:NTF \l_@@_class_cv_bool
	{ \@@_add_entry:nnn {#1} {#2} {#3} }
  	{ \msg_warning:nnn { dfg } { cv-entry-omitted } {#2} } }
  {% default behaviour: use #2 as family if #1 is empty
   \tl_if_empty:nTF {#1}
   { \@@_add_entry:nnn {#2} {#2} {#3} }
   {
      \@@_add_entry:nnn {#1} {#2} {#3}
      \str_if_eq:nnT {#1} { funding }
        { \@@_funding_cache_entry:nn {#2} {#3} }
      \bool_lazy_all:nT
        {
          { \str_if_eq_p:nn {#1} { funding } }
          { \str_if_eq_p:nn {#2} { RequestedFunding } }
        }
        { \@@_cache_requested_funding:n {#3} }
      \bool_lazy_all:nT
        {
          { \str_if_eq_p:nn {#1} { staff } }
          { \str_if_eq_p:nn {#2} { RequestedFundingStaff } }
        }
        { \@@_cache_requested_funding_staff:n {#3} }
      \bool_lazy_all:nT
        {
          { \str_if_eq_p:nn {#1} { funding } }
          { \str_if_eq_p:nn {#2} { RequestedAndExistingFundingDirectCosts } }
        }
        { \@@_cache_requested_and_existing_direct_costs:n {#3} }
    }
  }
  }
}
%    \end{macrocode}
% \end{macro}
%
% \begin{message}{cv-entry-omitted}
% Issued by \cs{addEntry} when an entry is targeted at the \texttt{cv}
% database but no CV is being produced (\cs{l\_dfg\_class\_cv\_bool} is
% false). The omitted entry's key-value data is included in the message
% to aid debugging.
%    \begin{macrocode}
\msg_new:nnn { dfg } { cv-entry-omitted }
{
  CV~entry~omitted:~no~CV~is~being~created.^^J
  Entry~data:~'#1'.
}
%    \end{macrocode}
% \end{message}
% There is a shortcut to define a database for e.g. a whole command to avoid all
% the time to write something like
% \cs{getEntry}\oarg{person}\marg{MM}\marg{lastname}.
% So you can define \cs{tmpLocalDB} with the database name.
%    \begin{macrocode}
\str_set:Nn \tmpLocalDB {}
%    \end{macrocode}
% \paragraph{\refCom{getEntry}}
% The primary read command: \cs{getEntry}\oarg{db}\marg{id-value}\marg{field}\oarg{id-field}.
% \begin{enumerate}
%   \item |#1|: Database name (default: \cs{tmpLocalDB}).
%   \item |#2|: The value to look up in the |id-field| column.
%   \item |#3|: The field whose value is to be returned.
%   \item |#4|: The name of the ID column (default: |id|); change this to
%         look up rows by a field other than the primary key.
% \end{enumerate}
% The guard logic runs in order:
%   If \refKey{fastcompile-project}|=true|, replace the output with a literal
%   identifier placeholder to skip the query entirely.
%   If |#1| is empty (\cs{tmpLocalDB} not set), warn and abort.
%   If the database does not exist, warn and abort.
%   Retrieve the value; if null/empty, warn (but only outside the
%   tabularray measuring pass to avoid duplicate messages).
%   Output via \cs{dfgShowTag} so that \refKey{showtags} annotations
%         are applied automatically.
%
% \textbf{PDF-bookmark note (FIXME):} When |#3| contains LaTeX commands,
% the value may produce garbage in PDF bookmarks.  Wrapping the output
% in \cs{texorpdfstring} would fix this but requires knowing at definition
% time what the field contains, which is not possible.  A workaround is
% to use \cs{texorpdfstring} at the call site for fields that appear in
% section headings.
%    \begin{macrocode}
%\getEntry [<DB>]{<id-value>}{<field>}                 [<id-column>]
%   single field, prints with \dfgShowTag wrapping
%
%\getEntry*[<DB>]{<id-value>}{<assignments>}            [<id-column>]
%   multi-field, assigns to macros, no printing
\NewDocumentCommand \dfgFastReference { m }
{ { \textcolor{error}{\texttt{<#1>}} } }

% Project IDs stay prominent when metadata lookups are skipped. Scope the
% style locally so following text and error diagnostics keep their colours.
\cs_new_protected:Npn \@@_fast_project_reference:n #1
{ \dfgFastReference{#1} }

\cs_new_protected:Npn \@@_fast_clear_assignment:w #1 = #2 \q_stop
{ \cs_set:Npn #1 { } }

\cs_new_protected:Npn \@@_fast_clear_assignments:n #1
{
  \clist_map_inline:nn {#1}
  { \@@_fast_clear_assignment:w ##1 \q_stop }
}

%    \end{macrocode}
% \paragraph{Indexed raw-row reads}
% The private reader used by class-owned field lookups indexes each database
% by its literal |id| values. Each entry retains the first matching raw row
% and its traversal position, so duplicate IDs retain the original first-match
% behavior. The index stores tokens rather than expanded field values or
% formatted reference strings. The public \cs{DTLgetvalueforkey} is unchanged.
%
% Before every indexed lookup, compare the raw database and header tokens with
% their saved snapshot. Any difference rebuilds that database's index, including
% direct Datatool edits, replacement records, sorting, and changes made locally
% inside a group. No explicit cache-reset command is required.
%
% A database containing nonliteral IDs retains the original scan because an ID
% macro can change without changing the stored tokens. Other lookup columns and
% readers without the required Datatool map interface also use the original
% reader. Property keys stringify tokens, so a candidate match is checked for
% token equality before accepting it; unusual category codes fall back to the
% original comparison. Missing and null values use the original field extractor.
%
% \paragraph{Datatool counters and hyperlink state}
% The indexed reader reproduces the lookup's global result assignment, row
% counters, current index, and final row target at the appropriate nesting level.
% Intermediate targets from the internal search walk are omitted; the terminal
% target and the surrounding output boundary remain available to labels and
% hyperlinks. Other Datatool loops keep their ordinary target creation.
%    \begin{macrocode}
\bool_new:N \l_@@_row_cache_enabled_bool
\bool_set_true:N \l_@@_row_cache_enabled_bool
\prop_new:N \g_@@_row_cache_databases_prop
\prop_new:N \g_@@_row_cache_snapshots_prop
\prop_new:N \g_@@_row_cache_literal_prop
\int_new:N \g_@@_row_cache_databases_int
\int_new:N \l_@@_row_cache_position_int
\tl_new:N \l_@@_row_cache_db_tl
\tl_new:N \l_@@_row_cache_index_tl
\tl_new:N \l_@@_row_cache_id_tl
\tl_new:N \l_@@_row_cache_record_tl
\tl_new:N \l_@@_row_cache_snapshot_tl
\tl_new:N \l_@@_row_cache_previous_tl
\tl_new:N \l_@@_row_cache_counter_tl

\cs_new_protected:Npn \@@_row_cache_build:nn #1#2
{
  \prop_gclear:c {g_@@_row_cache_#2_prop}
  \tl_gclear:c {g_@@_row_cache_last_#2_tl}
  \prop_gput:Nnn \g_@@_row_cache_literal_prop {#1}{false}
  \DTLifhaskey{#1}{id}
  {
    \prop_gput:Nnn \g_@@_row_cache_literal_prop {#1}{true}
    \group_begin:
    \int_zero:N \l_@@_row_cache_position_int
    \DTLmapdata[name={#1},read-only]
    {
      \int_incr:N \l_@@_row_cache_position_int
      \DTLmapget{key=id,return=\l_@@_row_cache_id_tl}
      \tl_gset_eq:cN {g_@@_row_cache_last_#2_tl}
        \l__datatool_map_data_row_tl
      \datatool_if_null:NF \l_@@_row_cache_id_tl
      {
        % Dynamic IDs could change first-match behavior without a DB edit.
        \tl_analysis_map_inline:Nn \l_@@_row_cache_id_tl
        {
          \str_case:nnF {##3} {{A}{} {B}{} {C}{}}
            { \prop_gput:Nnn \g_@@_row_cache_literal_prop {#1}{false} }
        }
        \exp_args:Nc \prop_if_in:NVF {g_@@_row_cache_#2_prop}
          \l_@@_row_cache_id_tl
        {
          \tl_set:Ne \l_@@_row_cache_record_tl
          {
            {\exp_not:V \l_@@_row_cache_id_tl}
            {\int_use:N \l_@@_row_cache_position_int}
            {\exp_not:V \l__datatool_map_data_row_tl}
          }
          \exp_args:Nc \prop_gput:NVV {g_@@_row_cache_#2_prop}
            \l_@@_row_cache_id_tl \l_@@_row_cache_record_tl
        }
      }
    }
    \group_end:
  }{}
}

\cs_new_protected:Npn \@@_row_cache_prepare:n #1
{
  \prop_get:NnNTF \g_@@_row_cache_databases_prop {#1}
    \l_@@_row_cache_index_tl
  {}{
    \int_gincr:N \g_@@_row_cache_databases_int
    \tl_set:Ne \l_@@_row_cache_index_tl
      {\int_use:N \g_@@_row_cache_databases_int}
    \prop_gput:NnV \g_@@_row_cache_databases_prop {#1}
      \l_@@_row_cache_index_tl
    \prop_new:c {g_@@_row_cache_\l_@@_row_cache_index_tl _prop}
    \tl_new:c {g_@@_row_cache_last_\l_@@_row_cache_index_tl _tl}
  }
  \@@_database_snapshot:nN {#1} \l_@@_row_cache_snapshot_tl
  \prop_get:NnNTF \g_@@_row_cache_snapshots_prop {#1}
    \l_@@_row_cache_previous_tl
    {}{\tl_clear:N \l_@@_row_cache_previous_tl}
  \tl_if_eq:NNF \l_@@_row_cache_snapshot_tl \l_@@_row_cache_previous_tl
  {
    \prop_gput:NnV \g_@@_row_cache_snapshots_prop {#1}
      \l_@@_row_cache_snapshot_tl
    \exp_args:NnV \@@_row_cache_build:nn {#1}
      \l_@@_row_cache_index_tl
  }
}

\cs_new_protected:Npn \@@_row_cache_current:n #1
  {\dtlcurrentrow={#1}}

\cs_new_protected:Npn \@@_row_cache_use:Nnnnn #1#2#3#4#5
{
  % Reproduce the reader's counter values and terminal link target. Intermediate
  % search-row targets are not needed: no user code executes inside this scan.
  \refstepcounter{DTLrow}
  \tl_gset:Ne \@dtl@dbname {#3}
  \int_compare:nNnT {#4} > {0}
  {
    \tl_set:Ne \l_@@_row_cache_counter_tl
      {DTLrow\int_to_roman:n {\dtlforeachlevel+1}}
    \int_gset:cn {c@\l_@@_row_cache_counter_tl} {#4-1}
    \exp_args:NV \refstepcounter \l_@@_row_cache_counter_tl
    \tl_set:Ne \DTLcurrentindex {#4}
    \dtlcurrentrow={#5}
  }
  % Datatool's xdef of a token register preserves the contained tokens.
  % Copy the raw row without expanding names, formatting or other metadata.
  \gdef\@dtl@row{#5}
  \@sdtl@getcolumnindex{\@dtl@col}{#3}{#2}
  {
    \dtlcurrentrow=\expandafter{\@dtl@row}
    \edef\@dtl@dogetval{\noexpand\dtlgetentryfromcurrentrow
      {\noexpand\@dtl@val}{\@dtl@col}}
    \@dtl@dogetval
    \global\let#1=\@dtl@val
  }
}

\cs_new_protected:Npn \@@_row_cache_found:nnnNnnn #1#2#3#4#5#6#7
{
  % Property keys stringify tokens; verify token equality for unusual catcodes.
  \tl_if_eq:NnTF \l_@@_row_cache_id_tl {#1}
    {\@@_row_cache_use:Nnnnn #4 {#5}{#6}{#2}{#3}}
    {\DTLgetvalueforkey #4 {#5}{#6}{id}{#7}}
}

\cs_new_protected:Npn \@@_getvalueforkey:Nnnnn #1#2#3#4#5
{
  \bool_lazy_all:nTF
  {
    {\bool_if_p:N \l_@@_row_cache_enabled_bool}
    {\str_if_eq_p:ee {#4}{id}}
    {\int_compare_p:n {\dtlforeachlevel<3}}
    {\cs_if_exist_p:N \DTLmapdata}
    {\cs_if_exist_p:N \l__datatool_map_data_row_tl}
  }
  {
    \DTLifdbexists{#3}
    {
      \tl_set:Ne \l_@@_row_cache_db_tl {#3}
      \exp_args:NV \@@_row_cache_prepare:n \l_@@_row_cache_db_tl
      \prop_get:NVN \g_@@_row_cache_literal_prop
        \l_@@_row_cache_db_tl \l_@@_row_cache_previous_tl
      \str_if_eq:VnTF \l_@@_row_cache_previous_tl {true}
      {
        \tl_set:Ne \l_@@_row_cache_id_tl {#5}
        \exp_args:Nc \prop_get:NVNTF
          {g_@@_row_cache_\l_@@_row_cache_index_tl _prop}
          \l_@@_row_cache_id_tl \l_@@_row_cache_record_tl
        {
          \exp_after:wN \@@_row_cache_found:nnnNnnn
            \l_@@_row_cache_record_tl #1 {#2}{#3}{#5}
        }
        {
          \@@_row_cache_use:Nnnnn #1 {#2}{#3}{\DTLrowcount{#3}}{}
          \int_compare:nNnT {\DTLrowcount{#3}} > {0}
          {
            \exp_args:Nv \@@_row_cache_current:n
              {g_@@_row_cache_last_\l_@@_row_cache_index_tl _tl}
          }
        }
      }
      {\DTLgetvalueforkey #1 {#2}{#3}{#4}{#5}}
    }
    {\DTLgetvalueforkey #1 {#2}{#3}{#4}{#5}}
  }
  {\DTLgetvalueforkey #1 {#2}{#3}{#4}{#5}}
}

\NewDocumentCommand{\getEntry}{s O{\tmpLocalDB} m m O{id}}
{%
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \IfBooleanTF{#1}
    { \@@_fast_clear_assignments:n {#4} }
    {
      \dfgShowTag {#3}{#4}
        {
          \str_if_eq:eeTF {#2} {project}
            { \@@_fast_project_reference:n {#3} }
            { \dfgFastReference{#3} }
        }
        [#2]
    }
  }
  {
    \IfBooleanTF{#1}
    { \@@_get_entry_multi:nnnn  {#2}{#3}{#4}{#5} }
    { \@@_get_entry_single:nnnn {#2}{#3}{#4}{#5} }%
  }
}

%    \end{macrocode}
% \paragraph{Reference-aware lookup (\cs{get})}
% Parse relation steps before rendering, so metadata containing braces cannot
% become part of the path. The walker carries its path in arguments rather
% than shared scratch variables; this also permits branching reference lists.
%    \begin{macrocode}
\tl_new:N \l_@@_get_path_db_tl
\tl_new:N \l_@@_get_path_id_tl
\tl_new:N \l_@@_get_path_id_field_tl
\tl_new:N \l_@@_get_path_scan_db_tl
\tl_new:N \l_@@_get_path_field_tl
\tl_new:N \l_@@_get_path_tl
\tl_new:N \l_@@_get_path_keyset_tl
\tl_new:N \l_@@_get_path_target_tl
\tl_new:N \l_@@_get_path_value_tl
\seq_new:N \l_@@_get_path_values_seq
\seq_new:N \l_@@_get_path_annotation_seq
\prop_new:N \l_@@_get_path_seen_prop

\NewDocumentCommand{\get}{s O{\tmpLocalDB} m m O{id}}
{
  \IfBooleanTF{#1}
    {\getEntry*[#2]{#3}{#4}[#5]}
    {
      \group_begin:
      \tl_set:Ne \l_@@_get_path_db_tl {#2}
      \tl_set:Ne \l_@@_get_path_id_tl {#3}
      \tl_set:Nn \l_@@_get_path_id_field_tl {#5}
      \tl_set_eq:NN \l_@@_get_path_scan_db_tl \l_@@_get_path_db_tl
      \tl_clear:N \l_@@_get_path_tl
      \seq_clear:N \l_@@_get_path_annotation_seq
      \@@_get_path_scan:n {#4}
    }
}

\prg_new_protected_conditional:Npnn \@@_get_path_if_has_key:nn #1#2 {TF}
{
  \datatool_if_has_key:nnTF {#1}{#2}
    {\prg_return_true:}
    {
      \prop_get:NnNF \g_@@_database_keyset_prop {#1}
        \l_@@_get_path_keyset_tl
        {\tl_set:Nn \l_@@_get_path_keyset_tl {#1}}
      \exp_args:NV \keys_if_exist:nnTF \l_@@_get_path_keyset_tl {#2}
        {\prg_return_true:}{\prg_return_false:}
    }
}
\prg_generate_conditional_variant:Nnn \@@_get_path_if_has_key:nn {Vn} {TF}

\cs_new_protected:Npn \@@_get_path_scan:n #1
{
  \tl_put_right:Nn \l_@@_get_path_tl {{#1}}
  \seq_put_right:Nn \l_@@_get_path_annotation_seq {#1}
  \tl_set:Nn \l_@@_get_path_field_tl {#1}
  \tl_set:Nn \l_@@_get_path_target_tl {#1}
  \regex_match:nnTF {\A ref-.+-id \Z} {#1}
    {
      \regex_replace_once:nnN {\A ref-(.+)-id \Z} {\1}
        \l_@@_get_path_target_tl
      \@@_get_path_next:
    }
    {
      % An actual scalar field takes precedence over a database shorthand.
      \@@_get_path_if_has_key:VnTF \l_@@_get_path_scan_db_tl {#1}
        {\@@_get_path_finish:}
        {
          \@@_get_path_if_has_key:VnTF \l_@@_get_path_scan_db_tl {ref-#1-id}
            {\@@_get_path_next:}
            {
              \DTLifdbexists{#1}
                {\@@_get_path_next:}
                {\@@_get_path_finish:}
            }
        }
    }
}
% xparse preserves following prose when no optional braced step is present.
\NewDocumentCommand{\@@_get_path_next:}{g}
{
  \IfNoValueTF{#1}
    {\@@_get_path_finish:}
    {
      \tl_set_eq:NN \l_@@_get_path_scan_db_tl \l_@@_get_path_target_tl
      \@@_get_path_scan:n {#1}
    }
}

\cs_new_protected:Npn \@@_get_path_missing:nnn #1#2#3
{
  \tl_clear:N \l_@@_get_path_value_tl
  \bool_if:NF \lTblrMeasuringBool
    {\msg_warning:nnnnn {dfg}{missing-key}{#1}{#2}{#3}}
}
\cs_new_protected:Npn \@@_get_path_read:nnnn #1#2#3#4
{
  \tl_clear:N \l_@@_get_path_value_tl
  \tl_if_blank:nTF {#1}
    {\msg_warning:nnn {dfg}{database-name-not-given}{#2-/-#3}}
    {
      \DTLifdbexists{#1}
        {
          \datatool_if_has_key:nnTF {#1}{#3}
            {
              \datatool_if_has_key:nnTF {#1}{#4}
                {
                  \@@_getvalueforkey:Nnnnn{\l_@@_get_path_value_tl}{#3}{#1}{#4}{#2}
                  \DTLifnullorempty{\l_@@_get_path_value_tl}
                    {\@@_get_path_missing:nnn {#1}{#2}{#3}} {}
                }
                {\@@_get_path_missing:nnn {#1}{#2}{#4}}
            }
            {\@@_get_path_missing:nnn {#1}{#2}{#3}}
        }
        {\msg_warning:nnn {dfg}{database-not-found}{#1}}
    }
}

\cs_new_protected:Npn \@@_get_path_walk:nnnw #1#2#3#4#5\q_stop
{
  \tl_if_eq:nnTF {#5}{\q_nil}
    {
      \prop_if_in:NnF \l_@@_get_path_seen_prop {{#1}{#2}{#4}}
        {
          \prop_put:Nnn \l_@@_get_path_seen_prop {{#1}{#2}{#4}} {}
          \@@_get_path_read:nnnn {#1}{#2}{#4}{#3}
          \tl_if_empty:NF \l_@@_get_path_value_tl
            {
              \seq_put_right:Ne \l_@@_get_path_values_seq
                {
                  \exp_not:N \dfgShowTag {#2}{#4}
                    {\exp_not:V \l_@@_get_path_value_tl}[#1]
                }
            }
        }
    }
    {
      \tl_set:Nn \l_@@_get_path_target_tl {#4}
      \regex_replace_once:nnN {\A ref-(.+)-id \Z} {\1}
        \l_@@_get_path_target_tl
      \use:e
        {
          \exp_not:N \@@_get_path_read:nnnn {#1}{#2}
            {ref-\l_@@_get_path_target_tl-id}{#3}
        }
      \tl_if_empty:NF \l_@@_get_path_value_tl
        {
          % Freeze both the destination database and the complete ID list
          % before recursion changes the local lookup variables.
          \use:e
            {
              \exp_not:N \@@_get_path_branch:nnn
                {\l_@@_get_path_target_tl}
                {\exp_not:V \l_@@_get_path_value_tl}
                {\exp_not:n {#5}}
            }
        }
    }
}
\cs_new_protected:Npn \@@_get_path_branch:nnn #1#2#3
{
  \clist_map_inline:nn {#2}
    {\@@_get_path_walk:nnnw {#1}{##1}{id}#3\q_stop}
}
\cs_new_protected:Npn \@@_get_path_finish:
{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
    {
      \tl_set:Ne \l_tmpa_tl
        {\seq_use:Nn \l_@@_get_path_annotation_seq {/}}
      \use:e
        {
          \exp_not:N \dfgShowTag
            {\exp_not:V \l_@@_get_path_id_tl}
            {\exp_not:V \l_tmpa_tl}
            {
              \exp_not:n
                {
                  \str_if_eq:VnTF \l_@@_get_path_db_tl {project}
                    {\@@_fast_project_reference:n {\l_@@_get_path_id_tl}}
                    {\dfgFastReference{\l_@@_get_path_id_tl}}
                }
            }
            [\exp_not:V \l_@@_get_path_db_tl]
        }
    }
    {
      \seq_clear:N \l_@@_get_path_values_seq
      \prop_clear:N \l_@@_get_path_seen_prop
      \use:e
        {
          \exp_not:N \@@_get_path_walk:nnnw
            {\l_@@_get_path_db_tl}{\l_@@_get_path_id_tl}
            {\l_@@_get_path_id_field_tl}
            \exp_not:V \l_@@_get_path_tl \exp_not:N \q_nil \exp_not:N \q_stop
        }
      \seq_use:Nn \l_@@_get_path_values_seq {,~}
    }
  \group_end:
}

% --- single-field (your existing behaviour, lightly cleaned) ----------------
\cs_new_protected:Nn \@@_get_entry_single:nnnn
{
  % #1 db, #2 id-value, #3 field, #4 id-column
  \tl_if_blank:nTF {#1}
  { \msg_warning:nne {dfg}{database-name-not-given}{#2-/-#3} }
  {%
  	\DTLifdbexists{#1}
  	{%
      \@@_getvalueforkey:Nnnnn{\thevalue}{#3}{#1}{#4}{#2}%
  		\DTLifnullorempty{\thevalue}
  		{%
  			\bool_if:NF \lTblrMeasuringBool
  			{ \msg_warning:nneee {dfg}{missing-key}{#1}{#2}{#3} }%
  		}
  		{ \dfgShowTag{#2}{#3}{\thevalue}[#1] }%
  	}
  	{ \msg_warning:nne {dfg}{database-not-found}{#1} }%
  }%
}

% --- multi-field: hoists checks out of per-field loop -----------------------
\cs_new_protected:Nn \@@_get_entry_multi:nnnn
{
  \tl_if_blank:nTF {#1}
  { \msg_warning:nne {dfg}{database-name-not-given}{#2-/-multi} }
  {%
  	\tl_set:Nx \l_tmpa_tl {#1}%
  	\tl_set:Nx \l_tmpb_tl {#2}%
  	\DTLifdbexists{\l_tmpa_tl}
  	{%
  		% \typeout{DEBUG:~about~to~assign~from~\l_tmpa_tl~for~id~\l_tmpb_tl}%
  		\use:x
  		{
  			\exp_not:N \DTLassignfirstmatch
  			{ \exp_not:V \l_tmpa_tl }
  			{ \exp_not:n {#4} }
  			{ \exp_not:V \l_tmpb_tl }
  			{ \exp_not:n {#3} }
  		}%
  		% \typeout{DEBUG:~done.~theLastName~=~\theLastName}%
  	}
  	{ \msg_warning:nne {dfg}{database-not-found}{\l_tmpa_tl} }%
  }%
}

\cs_new_protected:Npn \@@_check_empty:w #1 = #2 \q_stop #3#4
{
  % #1: target macro tokens, #2: field name, #3: db, #4: id
  \exp_args:NV \DTLifnullorempty #1
  { \msg_warning:nneee {dfg}{missing-key}{#3}{#4}{#2} }
  { }%
}

\cs_new_protected:Nn \@@_check_empty:nnn
{
  % #1 db, #2 id, #3 single "\macro = field" pair
  \@@_check_empty:w #3 \q_stop {#1}{#2}%
}

%    \end{macrocode}
% Sometimes you need to get the last name of a person in the text.
% Here is how to do it, \refCom{getName}.
%    \begin{macrocode}
\NewDocumentCommand{\getName}{m}{\getEntry[person]{#1}{lastname}}
%    \end{macrocode}
% Sometimes you need to get the full name of a person in the text.
% Here is how to do it, \refCom{getFullName}.
%    \begin{macrocode}
\NewDocumentCommand{\getFullName}{s m}
{%
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \dfgFastReference{#2} }
  {
  % #1: starred -> include academic degree
  % #2: person id
  \getEntry*[person]{#2}{
  	\theAcademicDegree = academicdegree,
  	\theFirstName      = firstname,
  	\theLastName       = lastname
  }%
  \IfBooleanT{#1}
  {
    \DTLifnullorempty{\theAcademicDegree}{}
      {\dfgShowTag{#2}{academicdegree}{\theAcademicDegree}[person]\space}
  }%
  \dfgShowTag{#2}{firstname}{\theFirstName}[person]\space
  \dfgShowTag{#2}{lastname}{\theLastName}[person]
  }
}
%    \end{macrocode}
% \paragraph{\refCom{compareEntry}}
% \refCom{compareEntry}\oarg{db}\marg{id}\marg{field}\marg{value}\marg{true}\marg{false}
% reads \meta{field} from the row with the given \meta{id} and executes
% \meta{yes} if it matches \meta{value}, otherwise \meta{no}.  It is
% used throughout the tables to branch on e.g.\ project type or status
% without repeating the full \cs{DTLgetvalueforkey}/|\if| pattern.
%
% The internal implementation \cs{dfg\_compare\_entry:nnnnnn} runs the same
% three guard checks as \refCom{getEntry} (empty DB name, non-existent DB),
% then uses \cs{exp\_args:Nx} to fully expand \cs{thevalue} before the
% \cs{tl\_if\_eq:nnTF} test, ensuring that stored macro values are resolved
% correctly.
%    \begin{macrocode}
\cs_new_protected:Npn \dfg_compare_entry:nnnnnn #1#2#3#4#5#6
{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {#6}
  {
  \tl_if_blank:nTF {#1}
  { \msg_warning:nnn { dfg } { database-name-not-given } {#1} }
  {
  	\DTLifdbexists{#1}
  	{
      \@@_getvalueforkey:Nnnnn{\thevalue}{#3}{#1}{id}{#2}%
  		\str_if_eq:eeTF { \thevalue } {#4}
  		{#5}
  		{#6}
  	}
  	{ \msg_warning:nnn { dfg } { database-not-found } {#1} }
  }
  }
}

\NewDocumentCommand \compareEntry { O{\tmpLocalDB} m m m m m }
{
  \dfg_compare_entry:nnnnnn {#1}{#2}{#3}{#4}{#5}{#6}
}
%    \end{macrocode}
% \subsection{Table and list dispatch (\cs{printTable}, \cs{printList})}
%
% Rather than requiring the user to call \cs{ProjectLeadersTable},
% \cs{OverviewOfFundsRequestedForStaffTable}, etc.\ directly, two thin
% dispatchers are provided: \cs{printTable}\oarg{opts}\marg{name} and
% \cs{printList}\oarg{opts}\marg{name}.
%
% They synthesise the command name by appending |Table| or |List| to the
% \meta{name} argument (using \cs{cs:w}\ldots\cs{cs\_end:}), then pass
% the optional argument through if present.  This pattern means new tables
% can be added to the class without any change to user-facing call sites.
%
% All three commands check |fastcompile| first and emit a \cs{dfgItemSkipped}
% placeholder instead of running the real command when compilation speed
% is prioritised. Focused project mode makes narrow exceptions when
% |fastcompile-project-show-funding-tables=true|: the three project-local
% funding tables are rendered from their retained local rows; when
% |fastcompile-project-show-images=true|, plots are rendered from retained
% project metadata. During real rendering the commands also establish the compact
% former-project context: reference-only projects receive an asterisk, and a
% local legend is added only if at least one such project was encountered.  A
% \cs{rowNumber} counter is reset before each table for use in zebra-stripe
% logic inside individual table implementations.
%    \begin{macrocode}

\tl_new:N \l_tblr_body_tl                % token list that will hold the rows

\bool_new:N \l_@@_former_project_compact_bool
\bool_new:N \g_@@_former_project_seen_bool

\cs_new_protected:Npn \@@_former_project_note:
{
  \smallskip
  \noindent
  {\normalfont\normalcolor\footnotesize
    \textsuperscript{*}\,Former~project}\par
}

\cs_new_protected:Npn \@@_former_project_context:n #1
{
  \bool_set_true:N \l_@@_former_project_compact_bool
  % Table cells and list implementations introduce their own groups, so the
  % occurrence flag must be latched globally for the duration of this context.
  \bool_gset_false:N \g_@@_former_project_seen_bool
  #1
  \bool_if:NT \g_@@_former_project_seen_bool
    { \@@_former_project_note: }
  \bool_set_false:N \l_@@_former_project_compact_bool
  \bool_gset_false:N \g_@@_former_project_seen_bool
}

\cs_new_protected:Npn \@@_print_thing:nnnn #1#2#3#4 {
  \bool_if:NTF \l_@@_class_fastcompile_bool
  { \@@_print_thing_skipped:nn {#1} {#3} }
  {%
    \@@_former_project_context:n
    {
      #4%
      \StartTimer
      \@@_print_thing_call:nnn {#1} {#2} {#3}%
      \StopTimer { \@@_print_thing_label:n {#3} }%
    }
  }
}

\cs_new_protected:Npn \@@_print_thing_call:nnn #1#2#3 {
  \tl_if_head_is_group:nTF {#3}
  { \@@_print_thing_split:nnw {#1} {#2} #3 \empty \q_stop }
  { \cs:w #3 #1 \cs_end: #2 }
}

\cs_new_protected:Npn \@@_print_thing_split:nnw #1#2#3#4 \q_stop {
  \cs:w #3 #1 \cs_end: #2 #4
}

\cs_new:Npn \@@_print_thing_label:n #1 {
  \tl_if_head_is_group:nTF {#1}
  { \@@_print_thing_label_aux:w #1 \empty \q_stop }
  { #1 }
}

\cs_new:Npn \@@_print_thing_label_aux:w #1#2 \q_stop {
  #1 \tl_if_blank:nF {#2} { - \@@_print_thing_label_tail:n {#2} }
}

\cs_new:Npn \@@_print_thing_label_tail:n #1 {
  \tl_if_head_eq_charcode:nNTF {#1} [
    { \@@_print_thing_label_skip_optional:w #1 \q_stop }
    { \tl_head:n {#1} }
}

\cs_new:Npn \@@_print_thing_label_skip_optional:w [#1]#2 \q_stop {
  \tl_head:n {#2}
}

\cs_new_protected:Npn \@@_print_thing_skipped:nn #1#2 {
  \dfgItemSkipped { \@@_print_thing_label:n {#2} #1 }
}

\cs_new:Npn \@@_print_table_name:n #1
{
  \tl_if_head_is_group:nTF {#1}
    { \@@_print_table_name_aux:w #1 \q_stop }
    {#1}
}

\cs_new:Npn \@@_print_table_name_aux:w #1#2 \q_stop {#1}

\prg_new_protected_conditional:Npnn
  \@@_print_table_if_fast_project_funding:n #1 { TF }
{
  \bool_lazy_all:nTF
  {
    { \l_@@_class_fastcompile_project_bool }
    { \l_@@_class_fastcompile_project_show_funding_tables_bool }
  }
  {
    \str_case_e:nnF { \@@_print_table_name:n {#1} }
    {
      {RequestedFunding} { \prg_return_true: }
      {RequestedFundingStaff} { \prg_return_true: }
      {RequestedAndExistingFundingDirectCosts} { \prg_return_true: }
    }
    { \prg_return_false: }
  }
  { \prg_return_false: }
}

\cs_new_protected:Npn \@@_print_table_dispatch:nn #1#2
{
  \@@_print_table_if_fast_project_funding:nTF {#2}
  {
    \@@_former_project_context:n
    {
      \setcounter{rowNumber}{0}
      \@@_print_thing_call:nnn {Table} {#1} {#2}
    }
  }
  { \@@_print_thing:nnnn {Table} {#1} {#2} {\setcounter{rowNumber}{0}} }
}

% The dispatcher owns note; all other options retain the target's syntax.
\tl_new:N \l_@@_print_table_note_tl
\tl_new:N \l_@@_print_table_options_tl
\bool_new:N \l_@@_print_table_note_given_bool
\bool_new:N \l_@@_print_table_note_found_bool
\int_new:N \l_@@_print_table_note_level_int
\keys_define:nn { @@ / print-table }
{
  note .code:n =
  {
    \bool_set_true:N \l_@@_print_table_note_given_bool
    \tl_set:Nn \l_@@_print_table_note_tl {#1}
  },
  note .value_required:n = true,
}

\cs_new_protected:Npn \@@_print_table_remark_line:
{
  \hangindent = 0.7em
  \hangafter = 1
  \UseTblrHang {remark}
  \leavevmode
  \UseTblrTemplate {remark-tag} {default}
  \UseTblrTemplate {remark-sep} {default}
  \UseTblrTemplate {remark-text} {default}
  \par
}

% Use tabularray's normal remark layout and styles. Append to an existing
% Note remark; retain other remark tags and native lettered table notes.
% The level guard excludes tables nested in cells or note text.
\DeclareTblrTemplate {remark} {dfg-print-table-note}
{
  \UseTblrAlign {remark}
  \UseTblrIndent {remark}
  \bool_set_false:N \l_@@_print_table_note_found_bool
  \MapTblrRemarks
  {
    \tl_if_blank:VF \l_@@_print_table_note_tl
    {
      \int_compare:nNnT {\gTblrLevelInt}
        = {\l_@@_print_table_note_level_int}
      {
        \tl_if_eq:NnT \InsertTblrRemarkTag {Note}
        {
          \tl_put_right:Nn \InsertTblrRemarkText
            {\space\tl_use:N \l_@@_print_table_note_tl}
          \bool_set_true:N \l_@@_print_table_note_found_bool
        }
      }
    }
    \@@_print_table_remark_line:
  }
  \tl_if_blank:VF \l_@@_print_table_note_tl
  {
    \int_compare:nNnT {\gTblrLevelInt}
      = {\l_@@_print_table_note_level_int}
    {
      \bool_if:NF \l_@@_print_table_note_found_bool
      {
        \tl_set:Nn \InsertTblrRemarkTag {Note}
        \tl_set_eq:NN \InsertTblrRemarkText \l_@@_print_table_note_tl
        \@@_print_table_remark_line:
      }
    }
  }
}

\cs_new_protected:Npn \@@_print_table_with_options:nn #1#2
  { \@@_print_table_dispatch:nn { [#1] } {#2} }

\NewDocumentCommand{\printTable}{ +o +m }{%
  % Finish the paragraph and anchor a preceding heading before table layout.
  \@@_table_start:
  % Table footers are boxed; emit their saved page footnotes afterwards.
  \begin{savenotes}
  \group_begin:
  \tl_clear:N \l_@@_print_table_note_tl
  \bool_set_false:N \l_@@_print_table_note_given_bool
  \int_set:Nn \l_@@_print_table_note_level_int {\gTblrLevelInt + 1}
  \IfNoValueTF {#1}
    { \@@_print_table_dispatch:nn { } {#2} }
    {
      \keys_set_known:nnN { @@ / print-table } {#1}
        \l_@@_print_table_options_tl
      \bool_if:NTF \l_@@_print_table_note_given_bool
      {
        \tl_if_blank:VF \l_@@_print_table_note_tl
        {
          \SetTblrTemplate {remark} {dfg-print-table-note}
          % Short tblr tables do not render footers. Tall tables retain their
          % unbreakable body and render the note; explicit long still wins.
          \SetTblrOuter[tblr]{tall}
        }
        \tl_if_blank:VTF \l_@@_print_table_options_tl
          { \@@_print_table_dispatch:nn { } {#2} }
          {
            \exp_args:NV \@@_print_table_with_options:nn
              \l_@@_print_table_options_tl {#2}
          }
      }
      % Preserve the original optional argument, including an explicit [],
      % when the dispatcher has not consumed a note key.
      { \@@_print_table_dispatch:nn { [#1] } {#2} }
    }
  \par
  \group_end:
  \end{savenotes}
}

% Person-specific institution lists also run inside tables and PI cards.
% Call their formatter directly so a nested list does not reset the outer
% former-project context; this also preserves its focused-build output.
\cs_new_protected:Npn \@@_print_list_dispatch:nn #1#2
{
  \str_if_eq:eeTF { \@@_print_table_name:n {#2} } { Institutions }
    { \@@_print_thing_call:nnn { List } {#1} {#2} }
    { \@@_print_thing:nnnn { List } {#1} {#2} { } }
}

\NewDocumentCommand{\printList}{ o +m o }{%
  % Accept old trailing options, but let the leading options take precedence.
  \IfNoValueTF {#3}
  {
    \IfNoValueTF {#1}
      { \@@_print_list_dispatch:nn { } {#2} }
      { \@@_print_list_dispatch:nn { [#1] } {#2} }
  }
  {
    \IfNoValueTF {#1}
      { \@@_print_list_dispatch:nn { [#3] } {#2} }
      { \@@_print_list_dispatch:nn { [#3,#1] } {#2} }
  }
}

% Database-aware list commands share one leading option list. Bare existing
% database names remain valid for compatibility with the previous interface.
\tl_new:N \l_@@_list_database_tl
\tl_new:N \l_@@_list_options_tl
\keys_define:nn { @@ / list-options }
{
  database .tl_set:N = \l_@@_list_database_tl,
}
\cs_new_protected:Npn \@@_list_options:n #1
{
  \tl_set:Nn \l_@@_list_database_tl {person}
  \tl_clear:N \l_@@_list_options_tl
  \tl_if_blank:nF {#1}
  {
    \DTLifdbexists{#1}
      { \tl_set:Nn \l_@@_list_database_tl {#1} }
      {
        \keys_set_known:nnN { @@ / list-options } {#1}
          \l_@@_list_options_tl
      }
  }
}

\cs_new_protected:Npn \@@_print_plot_dispatch:nn #1#2
{
  \bool_lazy_all:nTF
  {
    { \l_@@_class_fastcompile_project_bool }
    { \l_@@_class_fastcompile_project_show_images_bool }
  }
  {
    \@@_former_project_context:n
    { \@@_print_thing_call:nnn {Plot} {#1} {#2} }
  }
  { \@@_print_thing:nnnn {Plot} {#1} {#2} { } }
}

% Plot-specific keys are consumed by each renderer; remaining keys belong to
% hvfloat. Keep their values unexpanded until the native optional argument.
\tl_new:N \l_@@_plot_float_options_tl
% #1: renderer key family, #2: type-specific defaults variable, #3: call options.
% Expand the stored lists once, preserving macros and braced comma values.
\cs_new_protected:Npn \@@_plot_options_set:nNn #1#2#3
  {
    \exp_args:Nne \keys_set_known:nnN { dfg / #1 }
      {
        \exp_not:V \l_@@_custom_plot_options_tl,
        \exp_not:V #2,
        \exp_not:n {#3}
      } \l_@@_plot_float_options_tl
  }
\cs_new_protected:Npn \@@_plot_float:
  {
    \par
    \use:e
      {
        \exp_not:N \hvFloat
          [floatPos=!hb,capPos=bottom,\exp_not:V \l_@@_plot_float_options_tl]
      }
  }

\NewDocumentCommand{\printPlot}{ o +m }{%
  \IfNoValueTF {#1}
  { \@@_print_plot_dispatch:nn { } {#2} }
  { \@@_print_plot_dispatch:nn { [#1] } {#2} }%
}

\newcounter{rowNumber}
%    \end{macrocode}
% \subsection{Data tables}
%
% All tables follow the same three-phase pattern:
%   \textbf{Body accumulation:} A \cs{DTLforeach*} loop iterates
%   over the relevant database (filtered and sorted as required) and
%   appends one tblr row to the token list \cs{l\_tblr\_body\_tl}
%   via \cs{tl\_gput\_right:Nx}.  Using a global token list and
%   \texttt{:Nx} (full expansion) ensures that database values are
%   resolved at loop time rather than at tblr rendering time.
%   \textbf{Table opening:} \cs{begin}|{tblr}| with the |main| theme,
%   |expand=|\cs{l\_tblr\_body\_tl}, |long| (for page-breaking), and a
%   column spec tailored to the specific table.
%   \textbf{Header row + body:} A literal first row provides column
%         headings; \cs{l\_tblr\_body\_tl} follows as the data rows.
%
% \paragraph{ProjectLeadersTable}
% Lists all PIs who are active in the current funding period
% (\cs{theFundingPeriodNumeral}), sorted by last name.  The filter
% applies two conditions simultaneously: \refKey{period} must contain the current
% numeral and \refKey{role} must contain |PI|.  The first cell of every row
% defines the hyperlink destination |pi:<id>| used by \cs{getPI}.
% The compact gender column has no heading; its values remain in the body.
% The doctorate column uses a two-line heading and a dedicated 1.7\,cm width.
% After sorting, prefetch raw rows from the four databases used by deferred
% cell commands. Tabularray may evaluate those commands repeatedly while
% measuring widths; the shared reader reuses the index while still checking
% for intervening database changes. Cell formatting and hyperlink creation
% remain at the output site. Older map interfaces skip the prefetch step.
%    \begin{macrocode}

% Use the same institution formatter as the CV section.  The public
% \InstitutionsList maps institution ids through \_@@_one_institution:n
% and uses \par\medskip between multiple institutions in the standard layout.
% Keep the institution label in sync with the ProjectsTable display setting.
\NewDocumentCommand{\dfgPLInstitutionList}{m}{%
  \bool_if:NTF \l_@@_custom_projects_table_institution_abbreviations_bool
    { \printList[abbreviation]{{Institutions}{#1}} }
    { \printList{{Institutions}{#1}} }
}

\int_new:N \l_@@_pl_iter_int

% Keep the hyperref command protected while tabularray expands the assembled
% table body.  It is executed only when the corresponding name cell is typeset.
\cs_new_protected:Npn \@@_pi_target:n #1
  { \hypertarget{pi:#1}{} }

\NewDocumentCommand{\ProjectLeadersTable}{}{%
  \def\tblrbody{}%

  \StartTimer
  \DTLsort*{lastname}{person}%
  \StopTimer{ProjectLeaderTable-sort}

  \StartTimer
  \bool_lazy_and:nnT
    {\cs_if_exist_p:N \DTLmapdata}
    {\cs_if_exist_p:N \l__datatool_map_data_row_tl}
  {
    \clist_map_inline:nn {person,project,institution,affiliation}
      {\DTLifdbexists{##1}{\@@_row_cache_prepare:n {##1}}{}}
  }
  \StopTimer{PL-data}

  \int_zero:N \l_@@_pl_iter_int

  \StartTimer
  \DTLforeach*[
  	\DTLisinlist{\theFundingPeriodNumeral}{\period}
  	\and
  	\DTLisinlist{PI}{\role}
  ]{person}{
  	\id              = id,
  	\role            = role,
  	\lastname        = lastname,
  	\firstname       = firstname,
  	\academicdegree  = academicdegree,
  	\period          = period,
  	\refProjectId    = ref-project-id,
  	\refInstitutionId = ref-institution-id,
  	\doctorateYear   = doctorateYear,
  	\gender          = gender
  }{%
  	\int_incr:N \l_@@_pl_iter_int
  	\protected@edef\tblrbody{\tblrbody
		{\noexpand\@@_pi_target:n{\id}%
		 {\noexpand{\color{referencePI}\bfseries
        \noexpand\dfgShowTag{\id}{lastname}{\lastname}[person]},~
        \noexpand\dfgShowTag{\id}{firstname}{\firstname}[person]}
        \noexpand\\
        \noexpand\dfgShowTag{\id}{academicdegree}{\academicdegree}[person]}
      \noexpand& \noexpand\dfgShowTag{\id}{gender}{\gender}[person]
      \noexpand& \noexpand\dfgShowTag{\id}{doctorateYear}{\doctorateYear}[person]
  		\noexpand& {\noexpand\dfgPLInstitutionList{\id}}
  		\noexpand& {\noexpand\getProject*{\refProjectId}[\\]}
  		\noexpand\\
  	}%
  }
  \StopTimer{PL-loop}
  \iow_term:x { PL-iterations:~ \int_use:N \l_@@_pl_iter_int }

  \StartTimer
  \begin{tblr}[
  		theme  = main,
  		expand = \tblrbody,
  		long
  	]{
		colspec   = {t{3.5cm}@{}t{.3cm}@{}t{1.7cm}X[1.2,t]t{1.3cm}},
  		column{1} = { fg = referencePI, halign = l, valign = m },
  		column{2} = { halign = c, valign = m },
  		column{3} = { halign = c, valign = m },
  		column{4} = { halign = l, valign = m },
  		column{5} = { halign = c, valign = m },
  		rowhead   = 1,
  		row{1}    = {
                    valign = m,
  			            bg     = tableHeadingsBG,
  			            fg     = tableHeadingsFont,
  			            font   = \bfseries,
  			            guard
  		            },
  	}
  	Project~ leader
	 & % \mbox{Gender}
	 & {Doctorate          \\ obtained~in}
  	 & {Home~ institution, \\ location}
  	 & Project(s)                           \\
  	\tblrbody
  \end{tblr}
  \StopTimer{PL-render}
}
%    \end{macrocode}
% After the list of the PIs we need to have an aggregated list of the
% participating institutions.
%    \begin{macrocode}
\prop_new:N \l_@@_inst_to_aff_prop
\prop_new:N \l_@@_inst_name_prop
\prop_new:N \l_@@_inst_seen_prop
\prop_new:N \l_@@_aff_seen_prop
\prop_new:N \l_@@_aff_to_insts_prop  % values are seq names (tl)
\prop_new:N \l_@@_aff_name_prop
\seq_new:N  \l_@@_affiliations_seq
\seq_new:N  \l_@@_aff_sort_seq
\seq_new:N  \l_@@_inst_sort_seq
\tl_new:N   \l_@@_output_tl
\tl_new:N   \l_@@_aff_label_tl
\int_new:N  \l_@@_seq_counter_int
\cs_generate_variant:Nn \seq_set_from_clist:Nn { Ne , NV }

% Append an institution name to the per-affiliation seq.
% Lazily creates the seq on first use and stores its name in the prop.
\cs_new_protected:Npn \@@_append_inst:nn #1#2 {
  \prop_get:NnNTF \l_@@_aff_to_insts_prop {#1} \l_tmpd_tl
  {%
  	% \l_tmpd_tl now holds the seq's csname; append to it
  	\seq_put_right:cn { \l_tmpd_tl } {#2}%
  }
  {%
  	\int_incr:N \l_@@_seq_counter_int
  	\tl_set:Nx \l_tmpd_tl
  	{ l_@@_inst_seq_ \int_use:N \l_@@_seq_counter_int _seq }%
    \seq_clear_new:c { \l_tmpd_tl }%
  	\seq_put_right:cn { \l_tmpd_tl } {#2}%
  	\prop_put:NnV \l_@@_aff_to_insts_prop {#1} \l_tmpd_tl
  }
}
\cs_generate_variant:Nn \@@_append_inst:nn { VV }

\cs_new_protected:Npn \@@_collect_pi_institution:n #1
{
  \tl_if_blank:nF {#1}
  {
  	\prop_if_in:NnF \l_@@_inst_seen_prop {#1}
  	{%
  		\prop_put:Nnn \l_@@_inst_seen_prop {#1} {1}%
  		\prop_get:NnNT \l_@@_inst_to_aff_prop {#1} \l_tmpb_tl
  		{%
  			\prop_get:NnNT \l_@@_inst_name_prop {#1} \l_tmpc_tl
        {
          \tl_set:Ne \l_tmpe_tl
          {
            \exp_not:N \dfgShowTag {#1}{name}
              {\exp_not:V \l_tmpc_tl}[institution]
          }
          \@@_append_inst:VV \l_tmpb_tl \l_tmpe_tl
        }%
  			\prop_if_in:NVF \l_@@_aff_seen_prop \l_tmpb_tl
  			{%
  				\prop_put:NVn \l_@@_aff_seen_prop \l_tmpb_tl {1}%
  				\seq_put_right:NV \l_@@_affiliations_seq \l_tmpb_tl
  			}%
  		}%
  	}%
  }
}

\int_new:N \l_@@_participating_columns_int
\dim_new:N \l_@@_participating_column_sep_dim
\tl_new:N \l_@@_participating_order_tl
\tl_new:N \l_@@_participating_raster_options_tl
\keys_define:nn { @@ / participating-institutions }
{
  columns .int_set:N = \l_@@_participating_columns_int,
  columns .value_required:n = true,
  column~sep .dim_set:N = \l_@@_participating_column_sep_dim,
  column~sep .value_required:n = true,
  order .choice:,
  order / alpha .code:n =
    { \tl_set:Nn \l_@@_participating_order_tl {alpha} },
  order / count .code:n =
    { \tl_set:Nn \l_@@_participating_order_tl {count} },
  order / unknown .code:n =
    {
      \msg_warning:nnn { dfg } { unknown-institution-order } {#1}
      \tl_set:Nn \l_@@_participating_order_tl {alpha}
    },
  alpha .meta:n = { order=alpha },
  count .meta:n = { order=count },
}

\cs_new_protected:Npn \@@_participating_institutions_raster:n #1
{
  \begin{tcbraster}[
    raster~ columns=1,
    raster~ equal~ height=rows,
    raster~ column~ skip=12pt,
    raster~ row~ skip=10pt,
    #1]
    \tl_use:N \l_@@_output_tl
  \end{tcbraster}
}

% Flow whole affiliation boxes down balanced columns without equal-height rows.
\cs_new_protected:Npn \@@_participating_institutions_columns:
{
  \par\addvspace{\medskipamount}
  \setlength{\columnsep}{\l_@@_participating_column_sep_dim}
  \setlength{\multicolsep}{0pt}
  \int_compare:nNnTF {\l_@@_participating_columns_int} > {1}
  {
    \begin{multicols}{\int_use:N \l_@@_participating_columns_int}
      \raggedcolumns
      \tl_use:N \l_@@_output_tl
    \end{multicols}
  }
  { \tl_use:N \l_@@_output_tl }
}

\NewDocumentCommand{\ParticipatingInstitutionsList}{ O{count} }
{%
  \group_begin:
  % Zero selects the existing raster; columns=1,2,... selects flowing columns.
  \int_zero:N \l_@@_participating_columns_int
  \dim_set:Nn \l_@@_participating_column_sep_dim {12pt}
  % Accept the legacy alpha/count options as well as order and raster keys.
  \tl_set:Nn \l_@@_participating_order_tl {count}
  \keys_set_known:nnN { @@ / participating-institutions } {#1}
    \l_@@_participating_raster_options_tl
  \prop_clear:N \l_@@_inst_to_aff_prop
  \prop_clear:N \l_@@_inst_name_prop
  \prop_clear:N \l_@@_inst_seen_prop
  \prop_clear:N \l_@@_aff_seen_prop
  \prop_clear:N \l_@@_aff_to_insts_prop
  \seq_clear:N  \l_@@_affiliations_seq
  \tl_clear:N   \l_@@_output_tl
  \int_zero:N   \l_@@_seq_counter_int

  % --- 1. One pass over institution: id -> aff-id, id -> name ---------
  \DTLforeach*{institution}{
  	\l_tmpa_tl = id,
  	\l_tmpb_tl = ref-affiliation-id,
  	\l_tmpc_tl = name
  }{%
  	\prop_put:NVV \l_@@_inst_to_aff_prop \l_tmpa_tl \l_tmpb_tl
  	\prop_put:NVV \l_@@_inst_name_prop   \l_tmpa_tl \l_tmpc_tl
  }

  % --- 2. One pass over person: collect active PI institutions --------
  \DTLforeach*[
  	\DTLisinlist{\theFundingPeriodNumeral}{\pPeriod} \and
  	\DTLisinlist{PI}{\pRole}
  ]{person}{ \l_tmpa_tl = ref-institution-id ,\pPeriod=period,\pRole=role}{%
  	\seq_set_from_clist:NV \l_tmpa_seq \l_tmpa_tl
  	\seq_map_inline:Nn \l_tmpa_seq
  	{ \@@_collect_pi_institution:n {##1} }%
  }

  % --- 3a. Precompute affiliation display names ----------------------
  \prop_clear:N \l_@@_aff_name_prop
  \seq_map_inline:Nn \l_@@_affiliations_seq {%
  	\getEntry*[affiliation]{##1}{ \l_tmpa_tl = name }%
  	\prop_put:NnV \l_@@_aff_name_prop {##1} \l_tmpa_tl
  }

  % --- 3b. Sort affiliations according to requested order ------------
  \str_case:VnF \l_@@_participating_order_tl
  {
  	{ alpha }
  	{%
  		\seq_sort:Nn \l_@@_affiliations_seq
  		{%
  			\prop_get:NnN \l_@@_aff_name_prop {##1} \l_tmpa_tl
  			\prop_get:NnN \l_@@_aff_name_prop {##2} \l_tmpb_tl
  			\str_compare:eNeTF { \l_tmpa_tl } < { \l_tmpb_tl }
  				{ \sort_return_same: }
  				{ \sort_return_swapped: }%
  		}%
  	}
  	{ count }
  	{%
  		\seq_sort:Nn \l_@@_affiliations_seq
  		{%
  			\prop_get:NnN \l_@@_aff_to_insts_prop {##1} \l_tmpc_tl
  			\prop_get:NnN \l_@@_aff_to_insts_prop {##2} \l_tmpd_tl
  			\int_compare:nNnTF
  			{ \seq_count:c { \l_tmpc_tl } } > { \seq_count:c { \l_tmpd_tl } }
  				{ \sort_return_same: }
  				{%
  					\int_compare:nNnTF
  					{ \seq_count:c { \l_tmpc_tl } } < { \seq_count:c { \l_tmpd_tl } }
  						{ \sort_return_swapped: }
  						{%
  							% equal counts → alphabetical tiebreak
  							\prop_get:NnN \l_@@_aff_name_prop {##1} \l_tmpa_tl
  							\prop_get:NnN \l_@@_aff_name_prop {##2} \l_tmpb_tl
  							\str_compare:eNeTF { \l_tmpa_tl } < { \l_tmpb_tl }
  								{ \sort_return_same: }
  								{ \sort_return_swapped: }%
  						}%
  				}%
  		}%
  	}
  }
  {%
    \msg_warning:nne { dfg } { unknown-institution-order }
    { \l_@@_participating_order_tl }%
  	\seq_sort:Nn \l_@@_affiliations_seq
  	{%
  		\prop_get:NnN \l_@@_aff_name_prop {##1} \l_tmpa_tl
  		\prop_get:NnN \l_@@_aff_name_prop {##2} \l_tmpb_tl
  		\str_compare:eNeTF { \l_tmpa_tl } < { \l_tmpb_tl }
  			{ \sort_return_same: }
  			{ \sort_return_swapped: }%
  	}%
  }

  % --- 4. Emit output -------------------------------------------------
  \seq_map_inline:Nn \l_@@_affiliations_seq {%
    \int_compare:nNnTF {\l_@@_participating_columns_int} > {0}
    {
      \tl_put_right:Nn \l_@@_output_tl
      {
        \begin{tcolorbox}[blankest,before~upper=\RaggedRight,
          before={\par\noindent},after={\par\addvspace{10pt}}]
      }
    }
    {
      % Preserve the raster's own before/after hooks for row placement.
      \tl_put_right:Nn \l_@@_output_tl
        {\begin{tcolorbox}[blankest,before~upper=\RaggedRight]}
    }%
  	\getEntry*[affiliation]{##1}{
  		\theAffName     = name,
  		\theAffLocation = location
  	}%
  	\prop_get:NnN \l_@@_aff_to_insts_prop {##1} \l_tmpd_tl
  	\seq_set_eq:Nc \l_@@_inst_sort_seq { \l_tmpd_tl }%
  	\seq_sort:Nn \l_@@_inst_sort_seq
  	{%
  		\str_compare:nNnTF {####1} < {####2}
  			{ \sort_return_same: }
  			{ \sort_return_swapped: }%
  	}%
  	\tl_set:Nx \l_@@_aff_label_tl { \seq_use:Nn \l_@@_inst_sort_seq {\\} }%
  	\tl_put_right:Nx \l_@@_output_tl {%
  		{ \exp_not:N \usekomafont{subsubsection}
        \exp_not:N \textbf{%
          \exp_not:N \dfgShowTag {##1}{name}
            {\exp_not:V \theAffName}[affiliation]}
        \exp_not:n {\space(}
        \exp_not:N \dfgShowTag {##1}{location}
          {\exp_not:V \theAffLocation}[affiliation]
        \exp_not:n {)\\} }%
    \exp_not:V \l_@@_aff_label_tl
  	}%
    \tl_put_right:Nn \l_@@_output_tl {\end{tcolorbox}}%
  }
  \seq_if_empty:NF \l_@@_affiliations_seq
  {
    \int_compare:nNnTF {\l_@@_participating_columns_int} > {0}
      { \@@_participating_institutions_columns: }
      {
        \exp_args:NV \@@_participating_institutions_raster:n
          \l_@@_participating_raster_options_tl
      }
  }
  \group_end:
}

%    \end{macrocode}
% Very similar to the table for the PIs we need one table for the projects.
% First we start with a helper command to get for each referenced person the
% required data.
% Use the same raster in both cardinality branches: a standalone tcolorbox
% and a top-aligned raster have different baseline placement after a heading.
% Selecting one or two columns inside the raster preserves a full-width single
% card and keeps its leading gap consistent with the established multi-PI layout.
%    \begin{macrocode}
\NewDocumentCommand{\getPersonInformation}{O{person} m}
{%
  % #1: database
  % #2: comma-separated list of person ids
  \def\tmpLocalDB{#1}%
  \seq_clear:N \l_tmpa_seq
  \seq_set_from_clist:Ne \l_tmpa_seq {#2}%
  \begin{tcbraster}[
    raster~valign=top,
    raster~columns=\bool_if:NTF \l_@@_project_one_PI_bool {1}{2},
    raster~equal~height=rows,
    raster~column~skip=12pt,
    raster~row~skip=10pt,
    PIbox
  ]
    \seq_map_inline:Nn \l_tmpa_seq
      {\__getperson_one:n {##1}}
  \end{tcbraster}
}

\bool_new:N \l_@@_pi_academicdegree_below_bool

\cs_new_protected:Npn \__getperson_one:n #1
{%
  \getEntry*[\tmpLocalDB]{#1}{
  	\theFirstName      = firstname,
  	\theLastName       = lastname,
  	\theAcademicDegree = academicdegree,
  	\thePhone          = phone,
  	\theEmail          = email,
    \theInstitution    = ref-institution-id,
  	\theORCiD         = orcid
  }%
  % Match the tallest title in this raster; equal-height groups settle over
  % successive LaTeX runs. Keep title text at the top of the reserved space.
  \begin{tcolorbox}[PIbox,title={
      \tcbox[blankest,tcbox~ width=forced~ left,
        equal~ height~ group={dfg-PI-titles-\thetcbraster}]{%
        \parbox[t]{\linewidth}{%
          \RaggedRight\bfseries
          \dfgShowTag{#1}{firstname}{\theFirstName}[\tmpLocalDB]\space
          \color{referencePI}
          \dfgShowTag{#1}{lastname}{\theLastName}[\tmpLocalDB]
          \normalfont\normalcolor
          \bool_if:NTF \l_@@_pi_academicdegree_below_bool
            {\newline}
            {,\space}
          \dfgShowTag{#1}{academicdegree}{\theAcademicDegree}[\tmpLocalDB]}}}]
  	\ifdefempty{\theORCiD}{\mbox{~}\\[.75\baselineskip]}{\getORCiD{#1}\\}
    \ifdefempty{\theInstitution}{}{\printList{{Institutions}{#1}}\newline}
    \ifdefempty{\thePhone}{}
      {\str_case:Vn \l_@@_custom_pi_contact_style_tl
        {
          {icons}
            {\mbox{\faPhone\space
             \dfgShowTag{#1}{phone}{\thePhone}[\tmpLocalDB]}\quad}
          {text}
            {\mbox{Phone:\space
             \dfgShowTag{#1}{phone}{\thePhone}[\tmpLocalDB]}\quad}
          {none}
            {\mbox{\dfgShowTag{#1}{phone}{\thePhone}[\tmpLocalDB]}\quad}
        }}
    \ifdefempty{\theEmail}{}
      {\str_case:Vn \l_@@_custom_pi_contact_style_tl
        {
          {icons}
            {\mbox{\faEnvelope\space
              \dfgShowTag{#1}{email}{\theEmail}[\tmpLocalDB]}}
          {text}
            {\mbox{E-Mail:\space
              \dfgShowTag{#1}{email}{\theEmail}[\tmpLocalDB]}}
          {none}
            {\mbox{\dfgShowTag{#1}{email}{\theEmail}[\tmpLocalDB]}}
        }}
  \end{tcolorbox}
}

% ============================================================
%  Precompute compact project-table data per person
% ============================================================

% --- Shared allocations outside each function ----------------------
\prop_new:N \g_@@_proj_pi_prop
\bool_new:N \g_@@_proj_pi_built_bool
\prop_new:N \g_@@_aff_narrow_prop
\prop_new:N \g_@@_inst_narrow_prop
\prop_new:N \g_@@_proj_pi_institution_ids_prop
\prop_new:N \g_@@_projects_table_institution_abbreviation_prop
\prop_new:N \g_@@_projects_table_institution_name_prop
\prop_new:N \g_@@_projects_table_abbreviation_owner_id_prop
\prop_new:N \g_@@_projects_table_abbreviation_owner_name_prop
\prop_new:N \g_@@_projects_table_abbreviation_warned_prop
\tl_new:N \l_@@_projects_table_legend_tl
\seq_new:N \l_@@_projects_table_institution_ids_seq
\seq_new:N \l_@@_projects_table_sorted_institution_ids_seq
\clist_new:N \l_@@_projects_table_institution_ids_clist
\tl_new:N \l_@@_projects_table_institution_abbreviation_tl

\cs_new_protected:Npn \@@_projects_table_collect_person_institutions:n #1
{
  \prop_get:NnNT \g_@@_proj_pi_institution_ids_prop {#1} \l_tmpa_tl
  {
    \clist_set:NV \l_@@_projects_table_institution_ids_clist \l_tmpa_tl
    \clist_map_inline:Nn \l_@@_projects_table_institution_ids_clist
    {
      \seq_if_in:NnF \l_@@_projects_table_institution_ids_seq {##1}
        { \seq_put_right:Nn \l_@@_projects_table_institution_ids_seq {##1} }
    }
  }
}

\cs_new_protected:Npn \@@_projects_table_collect_institutions:n #1
{
  \bool_if:NT \l_@@_custom_projects_table_institution_abbreviations_bool
  {
    \clist_map_function:nN {#1}
      \@@_projects_table_collect_person_institutions:n
  }
}

\cs_new_protected:Npn \@@_projects_table_institution_legend:
{
  \bool_if:NT \l_@@_custom_projects_table_institution_abbreviations_bool
  {
    \tl_clear:N \l_@@_projects_table_legend_tl
    \seq_set_eq:NN \l_@@_projects_table_sorted_institution_ids_seq
      \l_@@_projects_table_institution_ids_seq
    \seq_sort:Nn \l_@@_projects_table_sorted_institution_ids_seq
    {
      \prop_get:NnN \g_@@_projects_table_institution_abbreviation_prop
        {##1} \l_tmpa_tl
      \prop_get:NnN \g_@@_projects_table_institution_abbreviation_prop
        {##2} \l_tmpb_tl
      \str_compare:eNeTF
        { \str_casefold:V \l_tmpa_tl }
        >
        { \str_casefold:V \l_tmpb_tl }
        { \sort_return_swapped: }
        { \sort_return_same: }
    }
    \seq_map_inline:Nn \l_@@_projects_table_sorted_institution_ids_seq
    {
      \prop_get:NnN \g_@@_projects_table_institution_abbreviation_prop
        {##1} \l_tmpa_tl
      \prop_get:NnN \g_@@_projects_table_institution_name_prop
        {##1} \l_tmpb_tl
      \DTLifnullorempty{\l_tmpa_tl}{}
      {
        \tl_if_blank:VF \l_@@_projects_table_legend_tl
          { \tl_put_right:Nn \l_@@_projects_table_legend_tl { ;~ } }
        \tl_put_right:Nx \l_@@_projects_table_legend_tl
        {
          \exp_not:N \textbf { \exp_not:V \l_tmpa_tl }
          \c_space_tl = \c_space_tl
          \exp_not:V \l_tmpb_tl
        }
      }
    }
    \tl_if_blank:VF \l_@@_projects_table_legend_tl
    {
      \par\vspace{.15\baselineskip}
      {\tiny\RaggedRight\setlength{\parskip}{0pt}\noindent
        \textit{Institution~abbreviations:}\space
        \tl_use:N \l_@@_projects_table_legend_tl
        \par
      }
    }
  }
}


% Helper for render-time formatting
\NewDocumentCommand{\dfgPIformat}{mmm}{%
  % #1 = person id, #2 = firstname, #3 = lastname
  \dfgShowTag{#1}{firstname}{#2}[person]\space
  {\color{referencePI}\bfseries
    \dfgShowTag{#1}{lastname}{#3}[person],}\space
}

% Precompute once: store only the tokens, not \color & \bfseries directly
\cs_new_protected:Npn \@@_proj_pi_build: {
  \bool_if:NF \g_@@_proj_pi_built_bool {
  	\bool_gset_true:N \g_@@_proj_pi_built_bool

	  % Pass 1+2: precompute institution strings (as before)
  	\prop_new:N \l_@@_aff_narrow_prop
  	\DTLforeach*{affiliation}{
  		\l_tmpa_tl = id,
  		\l_tmpb_tl = name
  	}{%
  		\prop_put:NVV \l_@@_aff_narrow_prop \l_tmpa_tl \l_tmpb_tl
  	}

  \prop_new:N \l_@@_inst_narrow_prop
  \DTLforeach*{institution}{
  		\l_tmpa_tl = id,
  		\l_tmpb_tl = name,
		\l_tmpc_tl = ref-affiliation-id,
      \l_@@_projects_table_institution_abbreviation_tl = abbreviation
  	}{%
		\prop_gput:NVV \g_@@_projects_table_institution_abbreviation_prop
      \l_tmpa_tl \l_@@_projects_table_institution_abbreviation_tl
		\prop_gput:NVV \g_@@_projects_table_institution_name_prop
      \l_tmpa_tl \l_tmpb_tl
		\DTLifnullorempty{\l_@@_projects_table_institution_abbreviation_tl}{}
    {
      \prop_get:NVNTF \g_@@_projects_table_abbreviation_owner_name_prop
        \l_@@_projects_table_institution_abbreviation_tl \l_tmpe_tl
      {
        \tl_if_eq:NNF \l_tmpe_tl \l_tmpb_tl
        {
          \prop_if_in:NVF \g_@@_projects_table_abbreviation_warned_prop
            \l_@@_projects_table_institution_abbreviation_tl
          {
            \prop_get:NVN \g_@@_projects_table_abbreviation_owner_id_prop
              \l_@@_projects_table_institution_abbreviation_tl \l_tmpf_tl
            \msg_warning:nneeee { dfg } { duplicate-institution-abbreviation }
              { \l_@@_projects_table_institution_abbreviation_tl }
              { \l_tmpe_tl }
              { \l_tmpb_tl }
              { \l_tmpf_tl,~\l_tmpa_tl }
            \prop_gput:NVn \g_@@_projects_table_abbreviation_warned_prop
              \l_@@_projects_table_institution_abbreviation_tl { 1 }
          }
        }
      }
      {
        \prop_gput:NVV \g_@@_projects_table_abbreviation_owner_id_prop
          \l_@@_projects_table_institution_abbreviation_tl \l_tmpa_tl
        \prop_gput:NVV \g_@@_projects_table_abbreviation_owner_name_prop
          \l_@@_projects_table_institution_abbreviation_tl \l_tmpb_tl
      }
    }
		\bool_if:NTF
		  \l_@@_custom_projects_table_institution_abbreviations_bool
		{
		  \@@_institution_abbreviation_or_name:nN
		    { \l_tmpa_tl } \l_tmpf_tl
		}
		{
		  \tl_set:Nn \l_@@_institution_label_field_tl { name }
      \@@_getvalueforkey:Nnnnn{\l_tmpf_tl}{name}{institution}{id}{\l_tmpa_tl}
		}
  		\prop_get:NVNT \l_@@_aff_narrow_prop \l_tmpc_tl \l_tmpd_tl {
          \tl_if_blank:VTF \l_tmpf_tl
          {
            \tl_set:Nx \l_tmpe_tl
            {
              \exp_not:N \dfgShowTag
                {\exp_not:V \l_tmpc_tl}{name}
                {\exp_not:V \l_tmpd_tl}[affiliation]
            }
          }
          {
            \tl_set:Nx \l_tmpe_tl
            {
              \exp_not:N \dfgShowTag
                {\exp_not:V \l_tmpa_tl}
                {\exp_not:V \l_@@_institution_label_field_tl}
                {\exp_not:V \l_tmpf_tl}[institution]
              ,~
              \exp_not:N \dfgShowTag
                {\exp_not:V \l_tmpc_tl}{name}
                {\exp_not:V \l_tmpd_tl}[affiliation]
            }
          }
  			\prop_put:NVV \l_@@_inst_narrow_prop \l_tmpa_tl \l_tmpe_tl
  		}
  	}

  	% Pass 3: per Person die ganze Zelle vorberechnen, mit \dfgPIformat
  	\DTLforeach*{person}{
  		\l_tmpa_tl = id,
  		\l_tmpb_tl = firstname,
  		\l_tmpc_tl = lastname,
  		\l_tmpd_tl = ref-institution-id
  	}{%
		\prop_gput:NVV \g_@@_proj_pi_institution_ids_prop
      \l_tmpa_tl \l_tmpd_tl
  		\tl_clear:N \l_tmpe_tl
  		\tl_put_right:Nx \l_tmpe_tl {%
  			\exp_not:N \dfgPIformat
        { \exp_not:V \l_tmpa_tl }
  			{ \exp_not:V \l_tmpb_tl }
  			{ \exp_not:V \l_tmpc_tl }%
  		}%
  		% Institutions, separator ";~"
  		\seq_set_from_clist:NV \l_tmpa_seq \l_tmpd_tl
  		\bool_set_true:N \l_tmpa_bool
  		\seq_map_inline:Nn \l_tmpa_seq {%
  			\bool_if:NTF \l_tmpa_bool
  			{ \bool_set_false:N \l_tmpa_bool }
  			{ \tl_put_right:Nn \l_tmpe_tl { ;~ } }%
  			\prop_get:NnNT \l_@@_inst_narrow_prop {##1} \l_tmpf_tl
  			{ \tl_put_right:NV \l_tmpe_tl \l_tmpf_tl }%
  		}
  		\prop_gput:NVV \g_@@_proj_pi_prop \l_tmpa_tl \l_tmpe_tl
  	}
  }
}

% Schneller Drop-in
\NewDocumentCommand{\dfgFastPIinProjectsTable}{m}{%
  \@@_proj_pi_build:
  \seq_set_from_clist:Nn \l_tmpa_seq {#1}%
  \bool_set_true:N \l_tmpa_bool
  \seq_map_inline:Nn \l_tmpa_seq {%
  	\bool_if:NTF \l_tmpa_bool
  	{ \bool_set_false:N \l_tmpa_bool }
  	{ \newline }%
  	\prop_get:NnNT \g_@@_proj_pi_prop {##1} \l_tmpb_tl
  	{ \tl_use:N \l_tmpb_tl }%
  }
}

\NewDocumentCommand{\dfgPIinProjectsTable}{O{person} m}
{%
  % #1: database
  % #2: comma-separated list of person ids
  \def\tmpLocalDB{#1}%
  \seq_clear:N \l_tmpa_seq
  \seq_set_from_clist:Nn \l_tmpa_seq {#2}%
  \bool_set_true:N \l_tmpa_bool
  \seq_map_inline:Nn \l_tmpa_seq
  {%
  	\bool_if:NTF \l_tmpa_bool
  	{ \bool_set_false:N \l_tmpa_bool }
  	{ \newline }%
  	\__pi_in_projects_one:n {##1}%
  }%
}

\cs_new_protected:Npn \__pi_in_projects_one:n #1
{%
  \getEntry*[\tmpLocalDB]{#1}{
  	\theAcademicDegree = academicdegree,
  	\theFirstName = firstname,
  	\theLastName  = lastname
  }%
  \group_begin:
  %%\theAcademicDegree\space%
  \dfgShowTag{#1}{firstname}{\theFirstName}[\tmpLocalDB]\space
  \color{referencePI}\bfseries
  \dfgShowTag{#1}{lastname}{\theLastName}[\tmpLocalDB],\space
  \normalfont\normalcolor
  \printList[abbreviation,noaddress,nolocation,nozip,narrow]{{Institutions}{#1}}%
  \group_end:
}
\NewDocumentCommand{\ProjectsTable}{mm}
{%
  \def\tblrbody{}%
  \clist_clear:N \l_@@_research_area_clist
  \tl_clear:N    \l_tmpa_tl
  \clist_clear:N \l_tmpa_clist
  \seq_clear:N   \l_tmpb_seq
  \seq_clear:N   \l_tmpa_seq
  \seq_clear:N   \l_@@_projects_table_institution_ids_seq
  \@@_proj_pi_build:

  \StartTimer
  \DTLsort{number}{project}%
  \StopTimer{Proj-#1-sort}

  \int_zero:N \l_tmpa_int

  \StartTimer
  \DTLforeach*[
  	\DTLisPrefix{\pNumber}{#1}
    \and
    \not\DTLiseq{\pConsiderForLists}{false}
  ]{project}{
  	\pID          = id,
  	\pNumber      = number,
  	\pName        = name,
  	\pStatus      = project-status,
  	\pType        = project-type,
    \pConsiderForLists = consider-for-lists,
  	\l_tmpa_clist = research-area,
  	\pRefPersonId = ref-person-id
  }{%
  	\int_incr:N \l_tmpa_int
    \exp_args:NV \@@_projects_table_collect_institutions:n \pRefPersonId
  	% --- reset ALL flags each iteration ---------------------------------
  	\bool_set_false:N \l_@@_project_type_research_bool
  	\bool_set_false:N \l_@@_project_type_service_bool
  	\bool_set_false:N \l_@@_project_type_mgk_bool
  	\bool_set_false:N \l_@@_project_type_admin_bool

  	\bool_set_false:N \l_@@_project_status_N_bool
  	\bool_set_false:N \l_@@_project_status_E_bool
  	\bool_set_false:N \l_@@_project_status_C_bool


  	\str_case:Vn {\pStatus}
  	{
  		{N}{ \bool_set_true:N \l_@@_project_status_N_bool }
  		{E}{ \bool_set_true:N \l_@@_project_status_E_bool }
  		{C}{ \bool_set_true:N \l_@@_project_status_C_bool }
  	}

  	\str_case:Vn {\pType}{
  		{research}{ \bool_set_true:N \l_@@_project_type_research_bool }
  		{service} { \bool_set_true:N \l_@@_project_type_service_bool  }
  		{mgk}     { \bool_set_true:N \l_@@_project_type_mgk_bool      }
  		{admin}   { \bool_set_true:N \l_@@_project_type_admin_bool    }
  	}

  	\bool_if:nT
  	{ ( \l_@@_project_type_research_bool || \l_@@_project_type_service_bool ) && ! \l_@@_project_status_E_bool }
  	{%
    \clist_set:NV \l_tmpa_clist \l_tmpa_clist
  		\clist_sort:Nn \l_tmpa_clist
  		{ \fp_compare:nTF {##1 < ##2} {\sort_return_swapped:} {\sort_return_same:} }%
  		\seq_set_from_clist:NN \l_tmpa_seq \l_tmpa_clist
  		\seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq
  		{%
  			\prop_if_in:NnTF \g_@@_dfg_research_areas_prop {##1}
  			{ ##1 }
  			{ \textcolor{error}{\textbf{##1}} }%
  		}%
  	}

  	\protected@edef\tblrbody{\tblrbody
      \noexpand\getProject{\pID}
      & \bool_if:NF \l_@@_project_status_C_bool
          { {\noexpand\getProjectColor{\pID}%
              \noexpand\dfgShowTag{\pID}{project-status}{\pStatus}[project]} }
      & \noexpand\dfgShowTag{\pID}{name}{\pName}[project]
  		&
  		\bool_if:nT
  		{ ( \l_@@_project_type_research_bool || \l_@@_project_type_service_bool ) && ! \l_@@_project_status_E_bool }
      {{\noexpand\dfgShowTag{\pID}{research-area}
          {\seq_use:Nn \l_tmpb_seq {\\}}[project]}}
  		& \dfgFastPIinProjectsTable{\pRefPersonId}
  		\\
  	}%
  }
  \StopTimer{Proj-#1-loop}
  \iow_term:x { Proj-#1-iterations:~ \int_use:N \l_tmpa_int }

  \StartTimer
  \begin{tblr}[
  		theme   = main,
  		expand  = \tblrbody,
  		caption = {Project~area~#1~--~#2},
  		long
  	]{
      % The unbroken Research heading needs 15 mm at the default table size.
      % The N status marker also needs slightly more than 2 mm.
      colspec     = {m{1.1cm}@{}m{0.25cm}X[m]m{1.5cm}X[1.3,m]},
  		rowhead     = 1,
      % Alignment is controlled by halign, not by font declarations:
      % a row-level raggedright would override centered columns.
        rows        = {halign=l},
        column{2}   = {halign=c},
        column{4}   = {halign=c,guard},
		% column{1}   = {fg=tableFirstColumn},
  		row{1}      = {
                          valign = m,
  			              bg     = tableHeadingsBG,
  			              fg     = tableHeadingsFont,
  			              font   = \bfseries,
  			              % halign = c,
  			              guard
  		              },
  	}
  	Project
  	 & %{Status}
  	 & Title
  	 & {\mbox{Research}                                               \\area}
  	 & Project\space leader(s),\space institute(s),\space location(s)         \\
	\tblrbody
  \end{tblr}
  \@@_projects_table_institution_legend:
  \StopTimer{Proj-#1-render}
}
%    \end{macrocode}
% \paragraph{Project overview table}
% \cs{projectOverviewTable} produces the compact project list used on the
% proposal's final page.  Current and new projects remain in project-number
% order; ending projects (status |E|) are moved to the end.  The status marker
% is omitted for current projects and printed after the project number for all
% other statuses. Status markers use the same project colour as the identifier.
% The table is boxed once and shrunk proportionally only when it exceeds the
% space below the logo. The cap uses the smaller of the page goal and the text
% block plus the unused footer area, preserving the physical bottom margin.
% A final zero kern makes the box depth zero; vertical output avoids extra
% paragraph or baseline glue. Fewer projects retain their natural type size.
%
% Project-leader names are resolved while the table body is assembled.  This
% avoids repeating database lookups during tabularray's measuring and rendering
% passes.  All three headings use the canonical dark blue at a larger size;
% the cell-specific rule ensures that the first heading (``Project'') is not
% overridden by the first-column styling.  The final-page source can therefore
% remain deliberately small:
% |\pagestyle{empty}| followed by |\printTable{projectOverview}|.
%    \begin{macrocode}
\tl_new:N  \l_@@_project_overview_body_tl
\tl_new:N  \l_@@_project_overview_ending_body_tl
\tl_new:N  \l_@@_project_overview_id_tl
\tl_new:N  \l_@@_project_overview_number_tl
\tl_new:N  \l_@@_project_overview_name_tl
\tl_new:N  \l_@@_project_overview_status_tl
\tl_new:N  \l_@@_project_overview_consider_for_lists_tl
\tl_new:N  \l_@@_project_overview_person_ids_tl
\tl_new:N  \l_@@_project_overview_leaders_tl
\tl_new:N  \l_@@_project_overview_project_cell_tl
\seq_new:N \l_@@_project_overview_person_seq

\cs_new_protected:Npn \@@_project_overview_set_leaders:n #1
{
  \tl_clear:N \l_@@_project_overview_leaders_tl
  \seq_set_from_clist:Nn \l_@@_project_overview_person_seq {#1}
  \seq_map_indexed_inline:Nn \l_@@_project_overview_person_seq
  {
    \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{firstname}{person}{id}{##2}
    \@@_getvalueforkey:Nnnnn{\l_tmpb_tl}{lastname}{person}{id}{##2}
    \int_compare:nNnT {##1} > {1}
      { \tl_put_right:Nn \l_@@_project_overview_leaders_tl { \newline } }
    \tl_if_blank:VF \l_tmpa_tl
    {
      \tl_put_right:Ne \l_@@_project_overview_leaders_tl
      {
        \exp_not:N \dfgShowTag {##2}{firstname}
          {\exp_not:V \l_tmpa_tl}[person]
        \exp_not:N \space
      }
    }
    \tl_put_right:Ne \l_@@_project_overview_leaders_tl
    {
      \exp_not:N \hyperlink { pi:\exp_not:n {##2} }
      {
        \exp_not:N \textbf
        {
          \exp_not:N \color { referencePI }
          \exp_not:N \dfgShowTag {##2}{lastname}
            {\exp_not:V \l_tmpb_tl}[person]
        }
      }
    }
  }
}

\cs_new_protected:Npn \@@_project_overview_append_row:N #1
{
  \exp_args:NV \@@_project_overview_set_leaders:n
    \l_@@_project_overview_person_ids_tl
  \tl_set:Ne \l_@@_project_overview_project_cell_tl
  {
    \exp_not:N \getProject
      { \exp_not:V \l_@@_project_overview_id_tl }
  }
  \str_if_eq:VnF \l_@@_project_overview_status_tl { C }
  {
    \tl_if_blank:VF \l_@@_project_overview_status_tl
    {
      \tl_put_right:Ne \l_@@_project_overview_project_cell_tl
      {
        \exp_not:N \,
        \exp_not:N \getProjectColor
          {\exp_not:V \l_@@_project_overview_id_tl}
        \exp_not:N \dfgShowTag
          {\exp_not:V \l_@@_project_overview_id_tl}{project-status}
          {\exp_not:V \l_@@_project_overview_status_tl}[project]
      }
    }
  }
  \tl_put_right:Ne #1
  {
    { \exp_not:V \l_@@_project_overview_project_cell_tl }
    & {
      \exp_not:N \dfgShowTag
        {\exp_not:V \l_@@_project_overview_id_tl}{name}
        {\exp_not:V \l_@@_project_overview_name_tl}[project]
    }
    & { \exp_not:V \l_@@_project_overview_leaders_tl }
    \exp_not:N \\
  }
}

\cs_new_protected:Npn \@@_project_overview_collect:
{
  \DTLsort{number}{project}
  \DTLforeach*{project}
  {
    \l_@@_project_overview_id_tl         = id,
    \l_@@_project_overview_number_tl     = number,
    \l_@@_project_overview_name_tl       = name,
    \l_@@_project_overview_status_tl     = project-status,
    \l_@@_project_overview_consider_for_lists_tl = consider-for-lists,
    \l_@@_project_overview_person_ids_tl = ref-person-id
  }
  {
    \str_if_eq:VnF \l_@@_project_overview_consider_for_lists_tl { false }
    {
      \str_if_eq:VnTF \l_@@_project_overview_status_tl { E }
        { \@@_project_overview_append_row:N \l_@@_project_overview_ending_body_tl }
        { \@@_project_overview_append_row:N \l_@@_project_overview_body_tl }
    }
  }
  \tl_put_right:NV \l_@@_project_overview_body_tl
    \l_@@_project_overview_ending_body_tl
}

\box_new:N \l_@@_project_overview_box
\cs_new_protected:Npn \@@_project_overview_typeset:
{
 % \par\vspace*{-5\baselineskip}
  \begin{center}
    \crcLogo[height=1cm]
  \end{center}
  \enlargethispage{3\baselineskip}
  \vbox_set:Nn \l_@@_project_overview_box
  {
  \hbox:n
  {
  \begin{tblr}[
    theme  = main,
    expand = \l_@@_project_overview_body_tl
  ]{
    vspan       = even,
    rowsep      = 1pt,
    rows        = {ht=2.4\baselineskip,valign=m},
    colspec     = {m{1.5cm}X[m]m{4cm}},
    rowhead     = 1,
	column{1}   = {font=\Large\bfseries,valign=m,fg=tableFirstColumn},
    column{2,3} = {halign=l},
    row{1}      = {font=\large\bfseries,fg=tableHeadingsFont,halign=c,valign=m},
  }
    Project
    & Title
    & Project\space leader(s) \\
    \l_@@_project_overview_body_tl
  \end{tblr}
  }
  \kern0pt
  }
  \dim_set:Nn \l_tmpa_dim
    { \dim_min:nn {\pagegoal} {\textheight+\footskip} - \pagetotal - 1pt }
  \dim_compare:nNnT {\box_ht:N \l_@@_project_overview_box} > {\l_tmpa_dim}
    { \box_resize_to_ht_plus_dp:Nn \l_@@_project_overview_box {\l_tmpa_dim} }
  \par\nointerlineskip
  \hbox_to_wd:nn {\linewidth}
    { \hfil\box_use_drop:N \l_@@_project_overview_box\hfil }
}

\NewDocumentCommand{\projectOverviewTable}{}
{
  \group_begin:
  \DTLifdbexists{project}
  {
    \tl_clear:N \l_@@_project_overview_body_tl
    \tl_clear:N \l_@@_project_overview_ending_body_tl
    \@@_project_overview_collect:
    \@@_project_overview_typeset:
  }
  { \msg_warning:nnn { dfg } { database-not-found } { project } }
  \group_end:
}
%    \end{macrocode}
% Aggregate the codes displayed by the project tables: non-ending research
% and service projects that are considered for lists. Explicit exclusions
% remain available. Clear both the raw and formatted lists on every call.
%    \begin{macrocode}
\clist_new:N \l_@@_research_area_clist   % new clist name
\clist_new:N \l_@@_research_area_final_clist   % new clist name
\NewDocumentCommand{\ResearchAreasFromProjectsList}{o}{
  % #1: IDs of project to be excluded
  \clist_clear:N \l_@@_research_area_clist
  \clist_clear:N \l_@@_research_area_final_clist
  \tl_clear:N \l_tmpa_tl

  \DTLforeach[
  	% exclude mentioned projects (for whatsoever reason)
  	\not\DTLisinlist{\pNumber}{#1}% 1st condition
    \and
    \not\DTLiseq{\pConsiderForLists}{false}
    \and
    \not\DTLiseq{\pStatus}{E}
  ]
  {project}{%
  	\pNumber       =number,
  	\pType         =project-type,
    \pStatus       =project-status,
    \pConsiderForLists=consider-for-lists,
  	\l_tmpa_tl     =research-area%
  }{%
    % Match the types whose research-area cells are shown in ProjectsTable.
  	\bool_set_false:N \l_@@_project_type_research_bool
  	\bool_set_false:N \l_@@_project_type_service_bool
  	\bool_set_false:N \l_@@_project_type_mgk_bool
  	\bool_set_false:N \l_@@_project_type_admin_bool

  	\str_case:Vn {\pType}{
  		{research}{ \bool_set_true:N \l_@@_project_type_research_bool }
  		{service} { \bool_set_true:N \l_@@_project_type_service_bool  }
  		{mgk}     { \bool_set_true:N \l_@@_project_type_mgk_bool      }
  		{admin}   { \bool_set_true:N \l_@@_project_type_admin_bool    }
  	}
    \bool_lazy_any:nT
      {{\l_@@_project_type_research_bool}{\l_@@_project_type_service_bool}}
  	{\clist_put_right:NV \l_@@_research_area_clist { \l_tmpa_tl }}%
  }
  \clist_remove_duplicates:N \l_@@_research_area_clist
  % Sort the fixed-width classification code numerically after removing
  % punctuation; treating `2.21-02` as an fp expression would parse the
  % hyphen as subtraction.
  \clist_sort:Nn \l_@@_research_area_clist
  {
    \tl_set:Nn \l_tmpa_tl {##1}
    \tl_set:Nn \l_tmpb_tl {##2}
    \regex_replace_all:nnN { [-.] } {} \l_tmpa_tl
    \regex_replace_all:nnN { [-.] } {} \l_tmpb_tl
    \exp_args:NnV \regex_match:nnTF { \A \d+ \Z } \l_tmpa_tl
      {
        \exp_args:NnV \regex_match:nnTF { \A \d+ \Z } \l_tmpb_tl
          {
            \int_compare:nNnTF { \l_tmpa_tl } < { \l_tmpb_tl }
              { \sort_return_same: }
              { \sort_return_swapped: }
          }
          { \sort_return_same: }
      }
      {
        \exp_args:NnV \regex_match:nnTF { \A \d+ \Z } \l_tmpb_tl
          { \sort_return_swapped: }
          { \sort_return_same: }
      }
  }

  \clist_map_inline:Nn \l_@@_research_area_clist {
  	\clist_put_right:NV \l_@@_research_area_final_clist { \dfgResearchAreasList{##1}}
  }

  \dfgShowCalculatedTag{ResearchAreasFromProjectsList}{project}
  {
    \clist_use:Nnnn \l_@@_research_area_final_clist {,~}{,~}{,~and~}%
    .%final dot.
  }
}
%    \end{macrocode}
% \subsection{DFG research area classification}
% \label{sec:research-areas}
% The DFG publishes an official hierarchical subject classification list;
% a project must declare which areas its work belongs to.  The global
% property list \cs{g\_@@\_dfg\_research\_areas\_prop} maps every
% classification code (e.g.\ |2.11-01|) to its English label.
%
% Usage: supply one or more codes as a comma-separated value in the
% |research-area| key of an \refCom{addEntry}|{project}| block.
% \cs{printResearchAreas} then looks up and formats them as a
% natural-language list.
%
% \textbf{Sorting note:} the codes are numeric strings with a hyphen
% (|2.11-01|), which cannot be compared as plain integers.  The sort
% in \cs{printResearchAreas} uses \cs{fp\_compare:nTF} after stripping
% the hyphen suffix — a known workaround for the absence of a
% lexicographic sort in expl3 for this mixed format.
%    \begin{macrocode}
\prop_new:N \g_@@_dfg_research_areas_prop
\prop_gset_from_keyval:Nn \g_@@_dfg_research_areas_prop
{
  1.11-01 = {Prehistory~and~World~Archaeology},
  1.11-02 = {Greek~and~Latin~Philology},
  1.11-03 = {Ancient~History},
  1.11-04 = {Classical,~Roman,~Christian~and~Islamic~Archaeology},
  1.11-05 = {Egyptology~and~Ancient~Near~Eastern~Studies},

  1.12-01 = {Medieval~History},
  1.12-02 = {Early~Modern~History},
  1.12-03 = {Modern~and~Contemporary~History},
  1.12-04 = {History~of~Science},

  1.13-01 = {Art~History},
  1.13-02 = {Musicology},
  1.13-03 = {Theatre~and~Media~Studies},

  1.14-01 = {General~and~Comparative~Linguistics,~Experimental~Linguistics,~Typology,~Non-European~Languages},
  1.14-02 = {Individual~Linguistics,~Historical~Linguistics},
  1.14-03 = {Applied~Linguistics,~Computational~Linguistics},

  1.15-01 = {German~Medieval~Studies~(Medieval~German~Literature)},
  1.15-02 = {German~Literary~and~Cultural~Studies~(Modern~German~Literature)},
  1.15-03 = {European~and~American~Literary~and~Cultural~Studies},
  1.15-04 = {General~and~Comparative~Literary~Studies;~Cultural~Studies},

  1.16-01 = {Social~and~Cultural~Anthropology~and~Ethnology},
  1.16-02 = {Asian~Studies},
  1.16-03 = {African,~American~and~Oceania~Studies},
  1.16-04 = {Islamic~Studies,~Arabian~Studies,~Semitic~Studies},
  1.16-05 = {Religious~Studies~and~Jewish~Studies},

  1.17-01 = {Protestant~Theology},
  1.17-02 = {Roman~Catholic~Theology},

  1.18-01 = {History~of~Philosophy},
  1.18-02 = {Theoretical~Philosophy},
  1.18-03 = {Practical~Philosophy},

  1.21-01 = {General~Education~and~History~of~Education},
  1.21-02 = {General~and~Domain-Specific~Teaching~and~Learning},
  1.21-03 = {Education~Systems~and~Educational~Institutions},
  1.21-04 = {Educational~Research~on~Socialisation,~Welfare~and~Professionalism},

  1.22-01 = {General,~Cognitive~and~Mathematical~Psychology},
  1.22-02 = {Biological~Psychology~and~Cognitive~Neuroscience},
  1.22-03 = {Developmental~and~Educational~Psychology},
  1.22-04 = {Social~Psychology,~Industrial~and~Organisational~Psychology},
  1.22-05 = {Personality~Psychology,~Clinical~and~Medical~Psychology,~Methodology},

  1.23-01 = {Sociological~Theory},
  1.23-02 = {Empirical~Social~Research},
  1.23-03 = {Communication~Sciences},
  1.23-04 = {Political~Science},

  1.24-01 = {Economic~Theory},
  1.24-02 = {Economic~Policy,~Applied~Economics},
  1.24-03 = {Accounting~and~Finance},
  1.24-04 = {Management~and~Marketing},
  1.24-05 = {Operations~Management~and~Computer~Science~for~Business~Administration},
  1.24-06 = {Statistics~and~Econometrics},
  1.24-07 = {Economic~and~Social~History},

  1.25-01 = {Principles~of~Law~and~Jurisprudence},
  1.25-02 = {Private~Law},
  1.25-03 = {Public~Law},
  1.25-04 = {Criminal~Law},
  1.25-05 = {Criminology},

  2.11-01 = {Biochemistry},
  2.11-02 = {Biophysics},
  2.11-03 = {Cell~Biology},
  2.11-04 = {Structural~Biology},
  2.11-05 = {General~Genetics~and~Functional~Genome~Biology},
  2.11-06 = {Developmental~Biology},
  2.11-07 = {Bioinformatics~and~Theoretical~Biology},

  2.12-01 = {Evolution~and~Systematics~of~Plants~and~Fungi},
  2.12-02 = {Ecology~and~Biodiversity~of~Plants~and~Ecosystems},
  2.12-03 = {Organismic~Interactions,~Chemical~Ecology~and~Microbiomes~of~Plant~Systems},
  2.12-04 = {Plant~Physiology},
  2.12-05 = {Plant~Biochemistry~and~Biophysics},
  2.12-06 = {Plant~Cell~and~Developmental~Biology},
  2.12-07 = {Plant~Genetics~and~Genomics},

  2.13-01 = {Systematics~and~Morphology~(Zoology)},
  2.13-02 = {Evolution,~Anthropology},
  2.13-03 = {Ecology~and~Biodiversity~of~Animals~and~Ecosystems,~Organismic~Interactions},
  2.13-04 = {Sensory~and~Behavioural~Biology},
  2.13-05 = {Animal~Physiology~and~Biochemistry},
  2.13-06 = {Evolutionary~Cell~and~Developmental~Biology~(Zoology)},

  2.21-01 = {Metabolism,~Biochemistry~and~Genetics~of~Microorganisms},
  2.21-02 = {Microbial~Ecology~and~Applied~Microbiology},
  2.21-03 = {Medical~Microbiology~and~Mycology,~Hygiene,~Molecular~Infection~Biology},
  2.21-04 = {Virology},
  2.21-05 = {Immunology},
  2.21-06 = {Parasitology~and~Biology~of~Tropical~Infectious~Disease~Pathogens},

  2.22-01 = {Epidemiology~and~Medical~Biometry~/~Statistics},
  2.22-02 = {Public~Health,~Healthcare~Research,~Social~and~Occupational~Medicine},
  2.22-03 = {Human~Genetics},
  2.22-04 = {Anatomy~and~Physiology},
  2.22-05 = {Nutritional~Sciences},
  2.22-06 = {Pathology},
  2.22-07 = {Medical~Informatics~and~Medical~Bioinformatics},
  2.22-08 = {Pharmacy},
  2.22-09 = {Pharmacology},
  2.22-10 = {Toxicology,~Laboratory~Medicine},
  2.22-11 = {Anaesthesiology},
  2.22-12 = {Cardiology,~Angiology},
  2.22-13 = {Pneumology,~Thoracic~Surgery},
  2.22-14 = {Hematology,~Oncology},
  2.22-15 = {Gastroenterology},
  2.22-16 = {Nephrology},
  2.22-17 = {Endocrinology,~Diabetology,~Metabolism},
  2.22-18 = {Rheumatology},
  2.22-19 = {Dermatology},
  2.22-20 = {Pediatric~and~Adolescent~Medicine},
  2.22-21 = {Gynaecology~and~Obstetrics},
  2.22-22 = {Clinical~Immunology~and~Allergology},
  2.22-23 = {Reproductive~Medicine,~Urology},
  2.22-24 = {Biogerontology~and~Geriatric~Medicine},
  2.22-25 = {General~and~Visceral~Surgery},
  2.22-26 = {Cardiac~and~Vascular~Surgery},
  2.22-27 = {Orthopaedics,~Traumatology,~Reconstructive~Surgery},
  2.22-28 = {Dentistry,~Oral~Surgery},
  2.22-29 = {Otolaryngology,~Phoniatrics~and~Audiology},
  2.22-30 = {Radiology},
  2.22-31 = {Clinical~Infectiology~and~Tropical~Medicine},
  2.22-32 = {Medical~Physics,~Biomedical~Technology},
  2.22-33 = {Nuclear~Medicine,~Radiotherapy,~Radiobiology},

  2.23-01 = {Developmental~Neurobiology},
  2.23-02 = {Molecular~Biology~and~Physiology~of~Neurons~and~Glial~Cells},
  2.23-03 = {Experimental~and~Theoretical~Network~Neuroscience},
  2.23-04 = {Cognitive,~Systems~and~Behavioural~Neurobiology},
  2.23-05 = {Experimental~Models~for~the~Understanding~of~Nervous~System~Diseases},
  2.23-06 = {Molecular~and~Cellular~Neurology~and~Neuropathology},
  2.23-07 = {Clinical~Neurology;~Neurosurgery~and~Neuroradiology},
  2.23-08 = {Human~Cognitive~and~Systems~Neuroscience},
  2.23-09 = {Biological~Psychiatry},
  2.23-10 = {Clinical~Psychiatry,~Psychotherapy,~Child~and~Adolescent~Psychiatry},
  2.23-11 = {Ophthalmology},

  2.31-01 = {Soil~Sciences},
  2.31-02 = {Plant~Breeding~and~Plant~Pathology},
  2.31-03 = {Plant~Cultivation,~Plant~Nutrition,~Agricultural~Technology},
  2.31-04 = {Ecology~of~Land~Use},
  2.31-05 = {Agricultural~Economics,~Agricultural~Policy,~Agricultural~Sociology},
  2.31-06 = {Forestry},
  2.31-07 = {Animal~Breeding,~Animal~Nutrition,~Animal~Husbandry},

  3.11-01 = {Inorganic~Molecular~Chemistry~-~Synthesis~and~Characterisation},
  3.11-02 = {Organic~Molecular~Chemistry~-~Synthesis~and~Characterisation},

  3.12-01 = {Solid~State~and~Surface~Chemistry,~Material~Synthesis},
  3.12-02 = {Physical~Chemistry~of~Solids~and~Surfaces,~Material~Characterisation},

  3.13-01 = {Physical~Chemistry~of~Molecules,~Liquids~and~Interfaces,~Biophysical~Chemistry},

  3.14-01 = {Analytical~Chemistry},

  3.15-01 = {Biological~and~Biomimetic~Chemistry},
  3.15-02 = {Food~Chemistry},

  3.16-01 = {Preparatory~and~Physical~Chemistry~of~Polymers},
  3.16-02 = {Experimental~and~Theoretical~Physics~of~Polymers},
  3.16-03 = {Polymer~Materials},

  3.17-01 = {Theoretical~Chemistry:~Electron~Structure,~Dynamics,~Simulation},
  3.17-02 = {Theoretical~Chemistry:~Molecules,~Materials,~Surfaces},

  3.21-01 = {Experimental~Condensed~Matter~Physics},
  3.21-02 = {Theoretical~Condensed~Matter~Physics},

  3.22-01 = {Statistical~Physics,~Nonlinear~Dynamics,~Complex~Systems,~Soft~and~Fluid~Matter,~Biological~Physics},

  3.23-01 = {Optics,~Quantum~Optics~and~Physics~of~Atoms,~Molecules~and~Plasmas},

  3.24-01 = {Nuclear~and~Elementary~Particle~Physics,~Quantum~Mechanics,~Relativity,~Fields},

  3.25-01 = {Astrophysics~and~Astronomy},

  3.31-01 = {Mathematics},

  3.41-01 = {Atmospheric~Science},
  3.41-02 = {Oceanography},

  3.42-01 = {Geology},
  3.42-02 = {Palaeontology},

  3.43-01 = {Geophysics},
  3.43-02 = {Geodesy,~Photogrammetry,~Remote~Sensing,~Geoinformatics,~Cartography},

  3.44-01 = {Mineralogy,~Petrology~and~Geochemistry},

  3.45-01 = {Physical~Geography},
  3.45-02 = {Human~Geography},

  3.46-01 = {Hydrogeology,~Hydrology,~Limnology,~Urban~Water~Management,~Water~Chemistry,~Integrated~Water~Resources~Management},

  4.11-01 = {Metal-Cutting~and~Abrasive~Manufacturing~Engineering},
  4.11-02 = {Primary~Shaping~and~Reshaping~Technology,~Additive~Manufacturing},
  4.11-03 = {Joining~and~Separation~Technology},
  4.11-04 = {Plastics~Engineering},
  4.11-05 = {Production~Systems,~Operations~Management,~Quality~Management~and~Factory~Planning},
  4.11-06 = {Production~Automation~and~Assembly~Technology},

  4.12-01 = {Engineering~Design,~Machine~Elements,~Product~Development},
  4.12-02 = {Mechanics},
  4.12-03 = {Lightweight~Construction,~Textile~Technology},
  4.12-04 = {Acoustics},

  4.21-01 = {Chemical~and~Thermal~Process~Engineering},
  4.21-02 = {Technical~Chemistry},
  4.21-03 = {Mechanical~Process~Engineering},
  4.21-04 = {Biological~Process~Engineering},
  4.21-05 = {Systems~Process~Engineering},

  4.22-01 = {Energy~Process~Engineering},
  4.22-02 = {Technical~Thermodynamics},
  4.22-03 = {Fluid~Mechanics},
  4.22-04 = {Hydraulic~and~Turbo~Engines~and~Piston~Engines},

  4.31-01 = {Metallurgical,~Thermal~and~Thermomechanical~Treatment~of~Materials},
  4.31-02 = {Materials~in~Sintering~Processes~and~Generative~Manufacturing~Processes},
  4.31-03 = {Coating~and~Surface~Technology},
  4.31-04 = {Mechanical~Properties~of~Metallic~Materials~and~their~Microstructural~Origins},
  4.31-05 = {Glass,~Ceramics~and~Derived~Composites},
  4.31-06 = {Polymeric~and~Biogenic~Materials~and~Derived~Composites},

  4.32-01 = {Synthesis~and~Properties~of~Functional~Materials},
  4.32-02 = {Biomaterials},
  4.32-03 = {Thermodynamics~and~Kinetics~as~well~as~Properties~of~Phases~and~Microstructure~of~Materials},
  4.32-04 = {Computer-Aided~Design~of~Materials~and~Simulation~of~Materials~Behaviour~from~Atomic~to~Microscopic~Scale},

  4.41-01 = {Automation,~Mechatronics,~Control~Systems,~Intelligent~Technical~Systems,~Robotics},
  4.41-02 = {Measurement~Systems},
  4.41-03 = {Microsystems},
  4.41-04 = {Traffic~and~Transport~Systems,~Intelligent~and~Automated~Traffic},
  4.41-05 = {Human~Factors,~Ergonomics,~Human-Machine~Systems},
  4.41-06 = {Biomedical~Systems~Technology},

  4.42-01 = {Electronic~Semiconductors,~Components~and~Circuits,~Integrated~Systems,~Sensor~Technology,~Theoretical~Electrical~Engineering},
  4.42-02 = {Communication~Technology~and~Networks,~High-Frequency~Technology~and~Photonic~Systems,~Signal~Processing~and~Machine~Learning~for~Information~Technology},
  4.42-03 = {Electrical~Energy~Systems,~Power~Management,~Power~Electronics,~Electrical~Machines~and~Drives},
  4.42-04 = {Hardware~Systems~and~Architectures~for~Information~Technology~and~Artificial~Intelligence,~Quantum~Engineering~Systems},

  4.43-01 = {Theoretical~Computer~Science},
  4.43-02 = {Software~Engineering~and~Programming~Languages},
  4.43-03 = {Security~and~Dependability,~Operating,~Communication~and~Distributed~Systems},
  4.43-04 = {Artificial~Intelligence~and~Machine~Learning~Methods},
  4.43-05 = {Image~and~Language~Processing,~Computer~Graphics~and~Visualisation,~Human~Computer~Interaction,~Ubiquitous~and~Wearable~Computing},
  4.43-06 = {Data~Management,~Data-Intensive~Systems,~Computer~Science~Methods~in~Business~Informatics},
  4.43-07 = {Computer~Architecture,~Embedded~and~Massively~Parallel~Systems},

  4.51-01 = {Architecture,~Building~and~Construction~History,~Construction~Research,~Sustainable~Building~Technology},
  4.51-02 = {Urbanism,~Spatial~Planning,~Transportation~and~Infrastructure~Planning,~Landscape~Planning},
  4.51-03 = {Construction~Material~Sciences,~Chemistry,~Building~Physics},
  4.51-04 = {Structural~Engineering,~Building~Informatics~and~Construction~Operation},
  4.51-05 = {Applied~Mechanics,~Statics~and~Dynamics},
  4.51-06 = {Geotechnics,~Hydraulic~Engineering},

}

\NewDocumentCommand{\dfgResearchAreasList}{m}{
  \exp_args:Ne \@@_research_area_print:n { \tl_trim_spaces:n {#1} }
}
\cs_new_protected:Npn \@@_research_area_print:n #1
{
  % #1: a single code, with surrounding spaces removed
  \prop_if_in:NnTF \g_@@_dfg_research_areas_prop {#1}
  {
  	% key exists → fetch the description and typeset it
  	\prop_get:NnN \g_@@_dfg_research_areas_prop {#1} \l_tmpa_tl
  	\textbf{#1}:~\l_tmpa_tl
  }
  {
  	% key missing → same fallback as your original macro
  	\textcolor{error}{\textbf{#1}:~ research~ area~ not~ found}
  	\msg_warning:nne { dfg } { research-area-not-found }{#1}
  }
}
%    \end{macrocode}
% We turn to the early career phases
%    \begin{macrocode}
\str_new:N \l_@@_row_color_str
\tl_new:N \l_@@_early_career_name_style_tl
\NewDocumentCommand{\EarlyCareerResearchersTable}{ O{EarlyCareerResearcher} }{%
  \group_begin:
  % Training histories may refer to former projects without annotating them.
  \cs_set_protected:Npn \@@_project_reference_only_indicator: { }
  \def\dfgLocalDB{#1}
  \DTLifdbexists{\dfgLocalDB}{%
    % Older rosters may have no defence-date column at all.
    \DTLifhaskey{\dfgLocalDB}{dateDefense}{}
      {\DTLaddcolumn{\dfgLocalDB}{dateDefense}}
  	\DTLsort*{ref-project-id,lastname}{\dfgLocalDB}%
  	\def\tblrbody{}%
  	\DTLforeach*{\dfgLocalDB}{%
  		\pRefProjectID=ref-project-id,%
  		\pLastname=lastname,%
  		\pFirstname=firstname,%
  		\pFinancedBy=financed-by,%
  		\pTopic=topic,%
  		\pCategory=category,%
  		\pPeriodStart=periodStart,%
      \pPeriodEnd=periodEnd,%
    \pDateDefense=dateDefense%
  	}{
  		\str_case:en {\pCategory}{
  			{MD}{\str_set:Nn \l_@@_row_color_str {green!10} }
  			{PhD}{\str_set:Nn \l_@@_row_color_str {blue!10} }
  		}
    % Highlight only the name cell for completed doctoral candidates.
    \tl_clear:N \l_@@_early_career_name_style_tl
    \DTLifnullorempty{\pDateDefense}{}
    {
      \tl_if_blank:VF \pDateDefense
        {\tl_set:Nn \l_@@_early_career_name_style_tl {font=\bfseries}}
    }
      \@@_getvalueforkey:Nnnnn{\theProjectNumber}{number}{project}{id}{\pRefProjectID}
  		\protected@edef\tblrbody{\tblrbody
        \SetRow{\l_@@_row_color_str}
  	       	\datatool_if_null:NTF {\theProjectNumber}{\pRefProjectID}{\getProject{\pRefProjectID}}
      & \SetCell{\l_@@_early_career_name_style_tl}
        \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{lastname}
          {\pLastname}[\dfgLocalDB],~
        \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{firstname}
          {\pFirstname}[\dfgLocalDB]
      & \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{financed-by}
          {\pFinancedBy}[\dfgLocalDB]
      & \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{topic}
          {\pTopic}[\dfgLocalDB]
  			&
  			{
  				\ifdefempty{\pPeriodEnd}{since~}{}
          \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{periodStart}
            {\pPeriodStart}[\dfgLocalDB]
          \ifdefempty{\pPeriodEnd}{}{--            \noexpand\dfgShowTag{\pRefProjectID/\pLastname}{periodEnd}
              {\pPeriodEnd}[\dfgLocalDB]}}
  			\\
  		}}%
  	\begin{tblr}[%
  			theme=main,
  			expand=\tblrbody,
  			long
  		]{
        colspec = {t{1cm}t{3cm}t{1.2cm}X[t]t{2.5cm}},
  			rowhead = 1,
  			column{1} = {
                      font=\bfseries,halign=l,
  				            fg = {tableFirstColumn}
  			            },
        % Names must not stretch interword spaces when a line wraps.
        column{2} = {halign=l},
  			% row{even}={bg=tableRows},
        column{4} = {font={\footnotesize\itshape},halign=l},
  			row{1}       = {
  				               bg       = tableHeadingsBG,
  				               fg       = tableHeadingsFont,
  				               font     = \footnotesize\bfseries,
  				               halign   = {c},
                               valign   = {m},
  				               guard
  			               },
  		}
  		Project %
  		 & Surname,~ first~ name             %
  		 & {Type~ of~            \\ funding} %
  		 & Topic                             %
  		 & Duration                          \\
  		\tblrbody
  	\end{tblr}}
  {
  	Database~ \texttt{#1}~ missing.
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
  \group_end:
}
%    \end{macrocode}
% Following now the section about diversity and equity.
% Before that there is a command to get proper position names based on a
% property list.
%    \begin{macrocode}

\prop_new:N \g_@@_dfg_position_names_prop
\prop_gset_from_keyval:Nn \g_@@_dfg_position_names_prop
{
  PhD         = {Doctoral~researchers},
  postDoc     = {Postdoctoral~researchers},
  groupLeader = {Research~ group~ leaders,~
  		junior~ research~ group~ leaders,~
  		junior~ professors},
  research    = {Other~ research~ staff},
  nonResearch = {Non-research~ staff},
  student     = {Student~ and~ graduate~ assistants},
  prof        = {Professors},
  prof-W2     = {Professors~ W2/C3},
  prof-W3     = {Professors~ W3/C4}
}
\prop_new:N \g_@@_dfg_category_names_prop
\prop_gset_from_keyval:Nn \g_@@_dfg_category_names_prop
{
  PhD         = {Doctoral~researcher},
  postDoc     = {Postdoctoral~researcher},
  medDoc      = {Medical~doctoral~researcher},
  groupLeader = {(Jr.)~ Research~ group~ leader},
  research    = {Other~ research~ staff},
  nonResearch = {Non-research~ staff},
  student     = {Student/graduate~ assistant},
  assistant   = {Research~assistant},
  prof        = {Professor},
  prof-W2     = {Professor~ (W2/C3)},
  prof-W3     = {Professor~ (W3/C4)},
}
\prop_new:N \g_@@_dfg_category_abbreviations_prop
\prop_gset_from_keyval:Nn \g_@@_dfg_category_abbreviations_prop
{
  PhD         = {Doct.~cand.},
  postDoc     = {Postdoc},
  medDoc      = {Med.~doc.},
  groupLeader = {Group~leader},
  research    = {Other~res.},
  nonResearch = {Non-res.},
  student     = {Stud./grad.~asst.},
  assistant   = {Res.~asst.},
  prof        = {Prof.},
  prof-W2     = {Prof.~(W2/C3)},
  prof-W3     = {Prof.~(W3/C4)},
}
\cs_generate_variant:Nn \prop_if_in:NnTF { NeTF }
% Keep canonical names available for validation and custom-category fallbacks.
% Both public labels and staff-roster cells use this resolver.
\prg_new_protected_conditional:Npnn \@@_category_name_get:nN #1#2 { TF }
{
  \prop_if_in:NeTF \g_@@_dfg_category_names_prop {#1}
  {
    \bool_if:NTF \l_@@_custom_category_abbreviations_bool
    {
      \prop_if_in:NeTF \g_@@_dfg_category_abbreviations_prop {#1}
        {\prop_get:NeN \g_@@_dfg_category_abbreviations_prop {#1} #2}
        {\prop_get:NeN \g_@@_dfg_category_names_prop {#1} #2}
    }
    {\prop_get:NeN \g_@@_dfg_category_names_prop {#1} #2}
    \prg_return_true:
  }
  {\prg_return_false:}
}

\NewDocumentCommand{\dfgPositionName}{m}{%
  \prop_if_in:NeTF \g_@@_dfg_position_names_prop {#1}
  {
  	\prop_get:NeN \g_@@_dfg_position_names_prop {#1} \l_tmpa_tl
  	\l_tmpa_tl
  }
  {
  	\textcolor{error}{mismatch:~#1}
    \@@_warn_unknown_name:nnN {position~in~\string\dfgPositionName} {#1}
      \g_@@_dfg_position_names_prop
  }
}
\NewDocumentCommand{\dfgCategoryName}{m}{
  \@@_category_name_get:nNTF {#1} \l_tmpa_tl
    {\tl_use:N \l_tmpa_tl}
  {
  	\textcolor{error}{mismatch:~#1}
    \@@_warn_unknown_name:nnN {category~in~\string\dfgCategoryName} {#1}
      \g_@@_dfg_category_names_prop
  }
}
%    \end{macrocode}
%    \begin{macrocode}
\NewDocumentCommand{\GenderEqualityStaffTable}{ O{GenderEqualityStaff} }{%
  \def\dfgLocalDB{#1}
  \DTLifdbexists{\dfgLocalDB}{%
  	\tl_clear:N \l_tblr_body_tl
  	\DTLforeach*[
  		\DTLiseq{PhD}{\pPosition}
  		\OR
  		\DTLiseq{postDoc}{\pPosition}
  	]{\dfgLocalDB}{%
  		\pPosition=position,%
  		\pPrevObjPctFemale=previous-objective-percentage-female,%
  		\pStatusQuoNumFemale=status-quo-number-female,%
  		\pStatusQuoPctFemale=status-quo-percentage-female,%
  		\pFutureObjPctFemale=future-objective-percentage-female%
  	}{
  		\tl_gput_right:Nx \l_tblr_body_tl
  		{
      \dfgShowTag{\pPosition}{position}
        {\dfgPositionName{\pPosition}}[\dfgLocalDB] &
      \dfgShowTag{\pPosition}{previous-objective-percentage-female}
        {\pPrevObjPctFemale}[\dfgLocalDB] &
      \dfgShowTag{\pPosition}{status-quo-number-female}
        {\pStatusQuoNumFemale}[\dfgLocalDB] &
      \dfgShowTag{\pPosition}{status-quo-percentage-female}
        {\pStatusQuoPctFemale}[\dfgLocalDB] &
      \dfgShowTag{\pPosition}{future-objective-percentage-female}
        {\pFutureObjPctFemale}[\dfgLocalDB] \\
  		}
  	}
  	\begin{tblr}[%
  			theme=main,
			note{a}={Reference~ date:~ proposal~ for~ \dfgFundingPeriodText\space~ funding~ period},
  			expand=\l_tblr_body_tl,
  			long
  		]{
  			vspan=even,
  			%row{Z}= {font={\footnotesize\bfseries}},
  			colspec = {
  					X[m] % position
  					m{2cm} % proportion
  					m{2cm} % number
  					m{2cm} % female
  					m{3cm}
  				},
  			hspan=minimal, % !!!!! https://tex.stackexchange.com/a/637391/98739
  			vline{3} = {3-3}{1pt,solid,fg={tableLines}},
  			vline{5} = {1-3}{1pt,solid,fg={tableLines}},
  			hline{4} = {1pt,solid,fg={tableLines}},
  			% hline{Y} = {1pt,solid,fg={tableOuterLines}},
  			hline{2} = {wd=0pt},
  			rowhead = 3,
  			column{2-5}={halign={c}},
  			%  column{1} = {font={\bfseries},
  			%    fg = {rwthBlue}},
  			row{2-3} ={
  				          guard,
                          valign={m},
  				          font={\footnotesize\bfseries},
  				          fg={tableHeadingsFont},
  				          bg={white}},
        row{1}={valign=m},
  		}
  		\SetCell[r=3]{c} % empty
  		 & \SetCell[c=3]{c} Second~ funding~ period  %
  		 &                                           %
  		 &                                           %
  		 & Third~ funding~ period                    \\
  		% empty
  		 & {Objective~ [\unit{\percent}]}
  		 & \SetCell[c=2]{c}{Status~ Quo\TblrNote{a}}
  		 &
  		 & {Objective~ [\unit{\percent}]}            \\
  		% empty
  		 &                                           % empty
  		 & Number
  		 & [\unit{\percent}]
  		 & f                                         \\
  		\tl_use:N \l_tblr_body_tl
  		% Total
  		%  &                                           % objective
  		%  &                                           % number
  		%  &                                           % percentage
  		%  &                                           % objective \\
  	\end{tblr}}
  {
  	Database~ \texttt{#1}~ missing.
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}
%    \end{macrocode}
%    \begin{macrocode}
\int_new:N \l_@@_count_int
\int_new:N \l_@@_total_int
\int_new:N \l_@@_tmp_int
\int_new:N \l_@@_tmp_total_int
\int_new:N \l_@@_tmp_position_int
\int_new:N \l_@@_tmp_gender_int
\int_new:N \l_@@_percent_int
%    \end{macrocode}
% Cached counting infrastructure:
% Count each requested funding phase once, then retain its position/gender
% counts across later phase switches. Compare unexpanded database and header
% tokens before reuse so edits, sorts and scoped changes invalidate the cache.
% Preserve the horizontal microtype boundary when restoring cached counts.
% The cached counts and active phase selector remain global across groups.
% Restoring saved counts in horizontal mode inserts cancelling nonzero kerns
% of |1sp| and |-1sp| to retain the original scan's microtype boundary. Omitting
% this boundary can shift the optical centering of numerals in table cells.
%    \begin{macrocode}
\prop_new:N \g_@@_counts_prop
\prop_new:N \g_@@_counts_by_phase_prop
\prop_new:N \g_@@_count_snapshots_prop
\tl_new:N   \l_@@_count_snapshot_tl
\tl_new:N   \l_@@_count_previous_snapshot_tl
\tl_new:N   \l_@@_count_cache_key_tl
\tl_new:N   \l_@@_count_cached_values_tl
\tl_new:N   \l_@@_count_key_tl
\tl_new:N   \g_@@_count_phase_tl
\tl_new:N   \l_@@_count_db_tl
% Compare the stored tokens, without expanding metadata. This also detects
% direct Datatool edits and locally scoped changes, not only \addEntry calls.
\cs_new_protected:Npn \@@_database_snapshot:nN #1#2
{
  \tl_set:Ne #2
  {
    { \exp_not:v {dtldb@#1} }
    { \exp_not:v {dtlkeys@#1} }
  }
}
%    \end{macrocode}
% Keep both the active phase and saved phase counts global, so nested groups
% cannot restore a stale phase selector after switching periods.
% Compute counts for ALL (position, gender) combinations in one pass.
% Stores them in |\g_@@_counts_prop|, keyed by position and gender.
% |\dfg_compute_counts:nn {<db>} {<phase>}|.
%    \begin{macrocode}
\cs_new_protected:Npn \dfg_compute_counts:nn #1#2
{
  \@@_database_snapshot:nN {#1} \l_@@_count_snapshot_tl
  \prop_get:NeNTF \g_@@_count_snapshots_prop {#1}
    \l_@@_count_previous_snapshot_tl
    { }
    { \tl_clear:N \l_@@_count_previous_snapshot_tl }
  \tl_if_eq:NNF \l_@@_count_snapshot_tl \l_@@_count_previous_snapshot_tl
  {
    \prop_gclear:N \g_@@_counts_by_phase_prop
    \tl_gclear:N \g_@@_count_phase_tl
    \prop_gput:NeV \g_@@_count_snapshots_prop {#1}
      \l_@@_count_snapshot_tl
  }
  \tl_set:Nx \l_@@_count_cache_key_tl { #1 | #2 }
  \tl_if_eq:NNF \l_@@_count_cache_key_tl \g_@@_count_phase_tl
  {
    \tl_gset_eq:NN \g_@@_count_phase_tl \l_@@_count_cache_key_tl
    \prop_get:NVNTF \g_@@_counts_by_phase_prop \l_@@_count_cache_key_tl
      \l_@@_count_cached_values_tl
    {
      \exp_args:NNV \prop_gset_from_keyval:Nn \g_@@_counts_prop
        \l_@@_count_cached_values_tl
      % Two cancelling kerns retain the original scan's boundary for
      % microtype, preserving the centering of digits without PDF anchors.
      \mode_if_horizontal:T { \tex_kern:D 1sp \tex_kern:D -1sp }
    }
    {
  	\prop_gclear:N \g_@@_counts_prop
  	\DTLforeach*[
  		\DTLisinlist{#2}{\pPeriod}
  		\and
  		\DTLisinlist{PI}{\pRole}
  	]{#1}{
  		\pPosition = position,
  		\pGender   = gender,
  		\pPeriod   = period,
  		\pRole     = role
  	}{
  		\tl_set:Nx \l_@@_count_key_tl { \pPosition | \pGender }
  		\prop_get:NVNTF \g_@@_counts_prop \l_@@_count_key_tl \l_tmpb_tl
  		{
  			\int_set:Nn \l_@@_count_int { \l_tmpb_tl + 1 }
  			\prop_gput:NVx \g_@@_counts_prop \l_@@_count_key_tl
  			{ \int_use:N \l_@@_count_int }
  		}
  		{
  			\prop_gput:NVn \g_@@_counts_prop \l_@@_count_key_tl { 1 }
  		}
  	}
      \prop_gput:NVx \g_@@_counts_by_phase_prop \l_@@_count_cache_key_tl
        { \prop_to_keyval:N \g_@@_counts_prop }
    }
  }
}
% O(1) lookup. Returns 0 for unknown keys.
% \dfg_count_lookup:nn {<position>} {<gender>}  -> integer literal
\cs_new:Npn \dfg_count_lookup:nn #1#2
{
  \prop_if_in:NnTF \g_@@_counts_prop { #1 | #2 }
  { \prop_item:Nn \g_@@_counts_prop { #1 | #2 } }
  { 0 }
}

% Set <int> to count for (position, gender) — uses cache.
% \dfg_count_position_set:Nnnnn <int> {<db>} {<position>} {<gender>} {<phase>}
\cs_new_protected:Npn \dfg_count_position_set:Nnnnn #1#2#3#4#5
{
  \prop_if_in:NnTF \g_@@_dfg_position_names_prop {#3}
  {
  	\dfg_compute_counts:nn {#2} {#5}
  	\int_set:Nn #1 { \dfg_count_lookup:nn {#3} {#4} }
  }
  {
  	\textcolor{error}{mismatch:~#3}
    \@@_warn_unknown_name:nnN {staff~position~for~counts} {#3}
      \g_@@_dfg_position_names_prop
  }
}

% Sum across all genders for one position.
% \dfg_total_position_set:Nnnn <int> {<db>} {<position>} {<phase>}
\cs_new_protected:Npn \dfg_total_position_set:Nnnn #1#2#3#4
{
  \dfg_compute_counts:nn {#2} {#4}
  \int_set:Nn #1
  {
  	\dfg_count_lookup:nn {#3} {f}
  	+ \dfg_count_lookup:nn {#3} {m}
  	+ \dfg_count_lookup:nn {#3} {d}
  }
}

% Sum across all positions for one gender.
% \dfg_total_gender_set:Nnnn <int> {<db>} {<gender>} {<phase>}
\cs_new_protected:Npn \dfg_total_gender_set:Nnnn #1#2#3#4
{
  \dfg_compute_counts:nn {#2} {#4}
  \int_set:Nn #1
  {
  	\dfg_count_lookup:nn {postDoc}     {#3}
  	+ \dfg_count_lookup:nn {groupLeader} {#3}
  	+ \dfg_count_lookup:nn {prof-W2}    {#3}
  	+ \dfg_count_lookup:nn {prof-W3}    {#3}
  }
}

% Grand total across all positions and genders.
% \dfg_total_position_gender_set:Nnn <int> {<db>} {<phase>}
\cs_new_protected:Npn \dfg_total_position_gender_set:Nnn #1#2#3
{
  \dfg_compute_counts:nn {#2} {#3}
  \int_zero:N #1
  \clist_map_inline:nn {postDoc, groupLeader, prof-W2, prof-W3}
  {
  	\clist_map_inline:nn { f , m , d }
  	{
  		\int_add:Nn #1 { \dfg_count_lookup:nn {##1} {####1} }
  	}
  }
}
%    \end{macrocode}
% You can get the count of PIs of a certain position, gender and funding phase. 
%    \begin{macrocode}
\NewDocumentCommand{\getPositionGenderPhaseAmount}{ O{person} m m m }
{
  % #1: database
  % #2: position
  % #3: gender
  % #4: phase
  \dfg_count_position_set:Nnnnn \l_@@_tmp_int {#1} {#2} {#3} {#4}
  \dfgShowCalculatedTag{getPositionGenderPhaseAmount}{#1}
    { \int_use:N \l_@@_tmp_int }
}
%    \end{macrocode}
% This command sums up a certain gender column based on a funding phase. 
%    \begin{macrocode}
\NewDocumentCommand{\getPositionPhaseTotal}{ O{person} m m }
{
  % #1: database
  % #2: position
  % #3: phase

  \dfg_total_position_set:Nnnn \l_@@_total_int {#1} {#2} {#3}

  % no macro supplied → print the total
  \dfgShowCalculatedTag{getPositionPhaseTotal}{#1}
    { \int_use:N \l_@@_total_int }
}
%    \end{macrocode}
% This command sums up a certain gender column based on a funding phase. 
%    \begin{macrocode}
\NewDocumentCommand{\getGenderPhaseTotal}{ O{person} m m  }
{
  % #1: database
  % #2: gender
  % #3: phase
  \dfg_total_gender_set:Nnnn \l_@@_total_int {#1} {#2} {#3}

  % % no macro supplied → print the total
  \dfgShowCalculatedTag{getGenderPhaseTotal}{#1}
    { \int_use:N \l_@@_total_int }
}
%    \end{macrocode}
% This will get you the percentage of a certain position, gender and phase.
% Mainly for the table below, but can be used anywhere.
%    \begin{macrocode}
\NewDocumentCommand{\getPositionGenderPhasePercentage}{ O{person} m m m}
{
  % #1: database
  % #2: position
  % #3: gender
  % #4: phase

  \dfg_total_position_set:Nnnn \l_@@_total_int {#1} {#2} {#4}

  % --- number of the requested gender ---------------------------
  \dfg_count_position_set:Nnnnn \l_@@_tmp_int {#1}{#2}{#3}{#4}

  % --- avoid division by zero ----------------------------------
  \dfgShowCalculatedTag{getPositionGenderPhasePercentage}{#1}
  {
    \int_compare:nNnTF { \l_@@_total_int } = { 0 }
    { 0 }
    {
      % --- integer percentage (rounded) ------------------------
      \int_set:Nn \l_@@_percent_int
      { \fp_eval:n { round( 100 * \l_@@_tmp_int / \l_@@_total_int ) } }

      % print the integer together with the percent sign
      \int_use:N \l_@@_percent_int
    }
  }
}
%    \end{macrocode}
% The following command is meant to get the overall percentage of a certain
% gender.
% It goes into the final total row of the table, but it also can be used
% elsewhere with any funding phase you want.
%    \begin{macrocode}
\NewDocumentCommand{\getGenderPhasePercentage}{ O{person} m m  }
{
  % #1: database
  % #2: gender
  % #3: phase

  \int_zero:N \l_@@_percent_int
  \int_zero:N \l_@@_tmp_int
  \int_zero:N \l_@@_tmp_total_int

  \dfg_total_position_gender_set:Nnn \l_@@_tmp_total_int {#1} {#3}


  % % --- number of the requested gender ---------------------------
  \dfg_total_gender_set:Nnnn \l_@@_tmp_gender_int {#1}{#2}{#3}

  % --- avoid division by zero ----------------------------------
  \dfgShowCalculatedTag{getGenderPhasePercentage}{#1}
  {
    \int_compare:nNnTF { \l_@@_tmp_total_int } = { 0 }
    { 0 }
    {
      % --- integer percentage (rounded) ------------------------
      \int_set:Nn \l_@@_percent_int
      { \fp_eval:n { round( 100 * \l_@@_tmp_gender_int / \l_@@_tmp_total_int ) } }

      % print the integer together with the percent sign
      \int_use:N \l_@@_percent_int
    }
  }
  % \par Gender: #2--
  % Phase: #3--
  % Count: \int_use:N \l_@@_tmp_gender_int --
  % Count Total:\int_use:N \l_@@_tmp_total_int\par------------
}
%    \end{macrocode}
% Finally the table which is mostly calculated automatically based on the person-database.
%    \begin{macrocode}
\bool_new:N \l_@@_gender_leaders_all_sexes_bool
\tl_new:N \l_@@_gender_leaders_database_tl
\tl_new:N \l_@@_gender_leaders_unknown_options_tl
\clist_new:N \l_@@_gender_leaders_unknown_options_clist
\keys_define:nn {dfg/gender-leaders}
{
  all-sexes .bool_set:N = \l_@@_gender_leaders_all_sexes_bool,
  all-sexes .default:n = true,
  database .tl_set:N = \l_@@_gender_leaders_database_tl,
}
\NewDocumentCommand{\GenderEqualityProjectLeadersTable}{ O{} }
{
  \group_begin:
  \bool_set_false:N \l_@@_gender_leaders_all_sexes_bool
  \tl_set:Nn \l_@@_gender_leaders_database_tl {GenderEqualityProjectLeaders}
  \keys_set_known:nnN {dfg/gender-leaders} {#1}
    \l_@@_gender_leaders_unknown_options_tl
  \tl_if_blank:VF \l_@@_gender_leaders_unknown_options_tl
  {
    % Preserve the old bare database argument, including when combined with
    % a new display flag. Unknown key=value pairs still receive key errors.
    \clist_set:NV \l_@@_gender_leaders_unknown_options_clist
      \l_@@_gender_leaders_unknown_options_tl
    \int_compare:nNnTF
      {\clist_count:N \l_@@_gender_leaders_unknown_options_clist} = {1}
    {
      \exp_args:NV \tl_if_in:nnTF \l_@@_gender_leaders_unknown_options_tl {=}
      {
        \exp_args:NnV \keys_set:nn {dfg/gender-leaders}
          \l_@@_gender_leaders_unknown_options_tl
      }
      {
        \tl_set:Ne \l_@@_gender_leaders_database_tl
          {\clist_item:Nn \l_@@_gender_leaders_unknown_options_clist {1}}
      }
    }
    {
      \exp_args:NnV \keys_set:nn {dfg/gender-leaders}
        \l_@@_gender_leaders_unknown_options_tl
    }
  }
  \bool_if:NTF \l_@@_gender_leaders_all_sexes_bool
    { \exp_args:NV \@@_gender_leaders_all:n \l_@@_gender_leaders_database_tl }
    { \exp_args:NV \@@_gender_leaders_female:n \l_@@_gender_leaders_database_tl }
  \group_end:
}
\cs_new_protected:Npn \@@_gender_leaders_all:n #1
{%
  \def\dfgLocalDB{#1}
  \DTLifdbexists{\dfgLocalDB}{%
    % Invalidate once per table. Both counts and their phase are global, so
    % cell groups and prose commands always agree on the cached period.
    \tl_gclear:N \g_@@_count_phase_tl
  	\tl_clear:N \l_tblr_body_tl
  	\DTLforeach*[
  		% just making absolutely sure we only have the data sets we need.
  		\DTLiseq{postDoc}{\pPosition}
  		\OR
  		\DTLiseq{groupLeader}{\pPosition}
  		\OR
  		\DTLiseq{prof-W2}{\pPosition}
  		\OR
  		\DTLiseq{prof-W3}{\pPosition}
  	]{\dfgLocalDB}{%
  		\pPosition=position,%
  		\pPrevObjPctFemale=previous-objective-percentage-female,%
  		\pFutureObjPctFemale=future-objective-percentage-female%
  	}{

  		\tl_gput_right:Nx \l_tblr_body_tl
  		{
      \dfgShowTag{\pPosition}{position}
        {\dfgPositionName{\pPosition}}[\dfgLocalDB] % position
      \int_compare:nNnT {\theFundingPeriodNumeral} = {3}
      {
      & \getPositionGenderPhaseAmount{\pPosition}{f}{1}
      & \getPositionGenderPhaseAmount{\pPosition}{m}{1}
      & \getPositionGenderPhaseAmount{\pPosition}{d}{1}
      & \getPositionGenderPhasePercentage{\pPosition}{f}{1}
      & \getPositionGenderPhasePercentage{\pPosition}{m}{1}
      & \getPositionGenderPhasePercentage{\pPosition}{d}{1}
      }
      & \dfgShowTag{\pPosition}{previous-objective-percentage-female}
          {\pPrevObjPctFemale}[\dfgLocalDB] % objective
  			& \getPositionGenderPhaseAmount{\pPosition}{f}{\theFundingPeriodNumeralPrevious} % f number
  			& \getPositionGenderPhaseAmount{\pPosition}{m}{\theFundingPeriodNumeralPrevious} % m number
  			& \getPositionGenderPhaseAmount{\pPosition}{d}{\theFundingPeriodNumeralPrevious}% d number
  			&  \getPositionGenderPhasePercentage{\pPosition}{f}{\theFundingPeriodNumeralPrevious}% f percentage
  			&  \getPositionGenderPhasePercentage{\pPosition}{m}{\theFundingPeriodNumeralPrevious}% m percentage
  			&  \getPositionGenderPhasePercentage{\pPosition}{d}{\theFundingPeriodNumeralPrevious}% d percentage
      & \dfgShowTag{\pPosition}{future-objective-percentage-female}
          {\pFutureObjPctFemale}[\dfgLocalDB] % f objective
      \int_compare:nNnT {\theFundingPeriodNumeral} = {3}
      {
        & \getPositionGenderPhaseAmount{\pPosition}{f}{3}
        & \getPositionGenderPhaseAmount{\pPosition}{m}{3}
        & \getPositionGenderPhaseAmount{\pPosition}{d}{3}
        & \getPositionGenderPhasePercentage{\pPosition}{f}{3}
        & \getPositionGenderPhasePercentage{\pPosition}{m}{3}
        & \getPositionGenderPhasePercentage{\pPosition}{d}{3}
      }
  			\\
  		}
  	}
    \tl_gput_right:Nx \l_tblr_body_tl
    {
      \exp_not:n {Total\printMarginalia{
  			     Total~ no.:~
  			     \dfg_total_position_gender_set:Nnn \l_@@_tmp_total_int
  			     {person} % database
  			     {\theFundingPeriodNumeralPrevious} % phase
             \num{\int_use:N \l_@@_tmp_total_int}

      }}
      \int_compare:nNnT {\theFundingPeriodNumeral} = {3}
      {
      & \getGenderPhaseTotal{f}{1}
      & \getGenderPhaseTotal{m}{1}
      & \getGenderPhaseTotal{d}{1}
      & \getGenderPhasePercentage{f}{1}
      & \getGenderPhasePercentage{m}{1}
      & \getGenderPhasePercentage{d}{1}
      }
  		 &                                                                % objective
  		 & \getGenderPhaseTotal{f}{\theFundingPeriodNumeralPrevious}      % number f
  		 & \getGenderPhaseTotal{m}{\theFundingPeriodNumeralPrevious}      % number m
  		 & \getGenderPhaseTotal{d}{\theFundingPeriodNumeralPrevious}      % number d
  		 & \getGenderPhasePercentage{f}{\theFundingPeriodNumeralPrevious} % percentage f
  		 & \getGenderPhasePercentage{m}{\theFundingPeriodNumeralPrevious} % percentage m
  		 & \getGenderPhasePercentage{d}{\theFundingPeriodNumeralPrevious} % percentage d
      & % current-period objective
      \int_compare:nNnT {\theFundingPeriodNumeral} = {3}
      {
        & \getGenderPhaseTotal{f}{3}
        & \getGenderPhaseTotal{m}{3}
        & \getGenderPhaseTotal{d}{3}
        & \getGenderPhasePercentage{f}{3}
        & \getGenderPhasePercentage{m}{3}
        & \getGenderPhasePercentage{d}{3}
      }
      \\
    }
    \int_compare:nNnTF {\theFundingPeriodNumeral} = {3}
    {
      \@@_gender_leaders_render:nn
      {
        vline{2,8,15}={1-4}{1pt,solid,tableLines},
        vline{5,12,19}={3-4}{1pt,solid,tableLines},
        vline{9,16}={3-4}{1pt,solid,tableLines},
        colspec={X[m] *{6}{m{0.5cm}} m{1.3cm}
                         *{6}{m{0.5cm}} m{1.3cm} *{6}{m{0.5cm}}},
        colsep=1pt,
        column{1}={halign=l},
        column{2-21}={halign=c},
        cell{2}{8,15}={font=\scriptsize\bfseries},
      }
      {
        \SetCell[r=4]{l} Position
        & \SetCell[c=6]{c} First~ funding~ period & & & & &
        & \SetCell[c=7]{c} Second~ funding~ period & & & & & &
        & \SetCell[c=7]{c} Third~ funding~ period & & & & & & \\
        & \SetCell[c=6]{c} Status~ Quo & & & & &
        & {Objective~ [\unit{\percent}]}
        & \SetCell[c=6]{c} Status~ Quo\TblrNote{a} & & & & &
        & {Objective~ [\unit{\percent}]}
        & \SetCell[c=6]{c} Status~ Quo\TblrNote{a} & & & & & \\
        & \SetCell[c=3]{c} Number & &
        & \SetCell[c=3]{c} [\unit{\percent}] & &
        &
        & \SetCell[c=3]{c} Number & &
        & \SetCell[c=3]{c} [\unit{\percent}] & &
        &
        & \SetCell[c=3]{c} Number & &
        & \SetCell[c=3]{c} [\unit{\percent}] & & \\
        & f & m & d & f & m & d
        &
        & f & m & d & f & m & d
        & f
        & f & m & d & f & m & d \\
      }
    }
    {
      \@@_gender_leaders_render:nn
      {
        vline{3}={3-4}{1pt,solid,tableLines},
        vline{6}={4-4}{1pt,solid,tableLines},
        vline{9}={1-4}{1pt,solid,tableLines},
        colspec={X[m] m{2cm} *{6}{m{0.5cm}} m{3cm}},
        column{2-9}={halign=c},
      }
      {
        \SetCell[r=4]{l} Position
        & \SetCell[c=7]{c}
          \int_case:nnF {\theFundingPeriodNumeralPrevious}
            {{1}{First}{2}{Second}} {Previous}~ funding~ period & & & & & &
        & \dfgFundingPeriodText\space funding~ period \\
        & {Objective~ [\unit{\percent}]}
        & \SetCell[c=6]{c} Status~ Quo\TblrNote{a} & & & & &
        & {Objective~ [\unit{\percent}]} \\
        &
        & \SetCell[c=3]{c} Number & &
        & \SetCell[c=3]{c} [\unit{\percent}] & &
        & \\
        & & f & m & d & f & m & d & f \\
      }
    }
  }
  {
    Database~ \texttt{#1}~ missing.
    \msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}
%    \end{macrocode}
% Female-only view: the third-period layout follows DFG form 60.200,
% including the current period's number/percentage next to its original target.
% The existing future-objective field supplies that target, preserving metadata.
%    \begin{macrocode}
\cs_new:Npn \@@_gender_leaders_female_cells:nn #1#2
{
  & \getPositionGenderPhaseAmount{#1}{f}{#2}
  & \getPositionGenderPhasePercentage{#1}{f}{#2}
}
\cs_new_protected:Npn \@@_gender_leaders_female:n #1
{
  \def\dfgLocalDB{#1}
  \DTLifdbexists{\dfgLocalDB}
  {
    \tl_gclear:N \g_@@_count_phase_tl
    \tl_clear:N \l_tblr_body_tl
    \DTLforeach*[
      \DTLiseq{postDoc}{\pPosition}\OR
      \DTLiseq{groupLeader}{\pPosition}\OR
      \DTLiseq{prof-W2}{\pPosition}\OR
      \DTLiseq{prof-W3}{\pPosition}
    ]{\dfgLocalDB}{
      \pPosition=position,
      \pPrevObjPctFemale=previous-objective-percentage-female,
      \pFutureObjPctFemale=future-objective-percentage-female
    }
    {
      \tl_gput_right:Nx \l_tblr_body_tl
      {
        \dfgShowTag{\pPosition}{position}
          {\dfgPositionName{\pPosition}}[\dfgLocalDB]
        \int_compare:nNnTF {\theFundingPeriodNumeral} = {3}
        {
          \@@_gender_leaders_female_cells:nn {\pPosition}{1}
          \@@_gender_leaders_female_cells:nn {\pPosition}{2}
          & \dfgShowTag{\pPosition}{future-objective-percentage-female}
              {\pFutureObjPctFemale}[\dfgLocalDB]
          \@@_gender_leaders_female_cells:nn {\pPosition}{3}
        }
        {
          & \dfgShowTag{\pPosition}{previous-objective-percentage-female}
              {\pPrevObjPctFemale}[\dfgLocalDB]
          \@@_gender_leaders_female_cells:nn
            {\pPosition}{\theFundingPeriodNumeralPrevious}
          & \dfgShowTag{\pPosition}{future-objective-percentage-female}
              {\pFutureObjPctFemale}[\dfgLocalDB]
        }
        \\
      }
    }
    \tl_gput_right:Nx \l_tblr_body_tl
    {
      Total
      \int_compare:nNnTF {\theFundingPeriodNumeral} = {3}
      {
        & \getGenderPhaseTotal{f}{1} & \getGenderPhasePercentage{f}{1}
        & \getGenderPhaseTotal{f}{2} & \getGenderPhasePercentage{f}{2}
        &
        & \getGenderPhaseTotal{f}{3} & \getGenderPhasePercentage{f}{3}
      }
      {
        &
        & \getGenderPhaseTotal{f}{\theFundingPeriodNumeralPrevious}
        & \getGenderPhasePercentage{f}{\theFundingPeriodNumeralPrevious}
        &
      }
      \\
    }
    \int_compare:nNnTF {\theFundingPeriodNumeral} = {3}
    {
      \@@_gender_leaders_render:nnnn
      {
        colspec={X[m] m{1.2cm} m{.8cm} m{1.2cm} m{.8cm}
                 m{2cm} m{1.2cm} m{.8cm}},
        vline{2,4,6}={1-2}{1pt,solid,tableLines},
        column{2-8}={halign=c},
      }
      {
        \SetCell[r=2]{l} Position~(female)
        & \SetCell[c=2]{c} First~ funding~ period &
        & \SetCell[c=2]{c} Second~ funding~ period &
        & \SetCell[c=3]{c} {Status~ Quo\TblrNote{a}\\Third~ funding~ period} & & \\
        & Number & [\unit{\percent}]
        & Number & [\unit{\percent}]
        & {Original~ objective~[\unit{\percent}]} & Number & [\unit{\percent}] \\
      }
      {2}{3}
    }
    {
      \@@_gender_leaders_render:nnnn
      {
        colspec={X[m] m{2cm} m{1.5cm} m{1.5cm} m{3cm}},
        vline{3}={2-2}{1pt,solid,tableLines},
        vline{5}={1-2}{1pt,solid,tableLines},
        column{2-5}={halign=c},
      }
      {
        \SetCell[r=2]{l} Position~(female)
        & \SetCell[c=3]{c}
          \int_case:nnF {\theFundingPeriodNumeralPrevious}
            {{1}{First}{2}{Second}} {Previous}~ funding~ period & &
        & \dfgFundingPeriodText\space funding~ period \\
        & {Original~ objective~[\unit{\percent}]}
        & {Number\TblrNote{a}} & [\unit{\percent}]
        & {Objective~[\unit{\percent}]} \\
      }
      {2}{3}
    }
  }
  {
    Database~ \texttt{#1}~ missing.
    \msg_warning:nne {dfg}{database-not-found}{#1}
  }
}

%    \end{macrocode}
% Share the table styling between the two-period and three-period layouts.
% The complete four-row header repeats if the table crosses a page boundary.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_gender_leaders_render:nn #1#2
  { \@@_gender_leaders_render:nnnn {#1}{#2}{4}{5} }
\cs_new_protected:Npn \@@_gender_leaders_render:nnnn #1#2#3#4
{
  \begin{tblr}[
    theme=main,
    note{a}={Reference~ date:~ proposal~ for~ \dfgFundingPeriodText\space funding~ period},
    expand=\l_tblr_body_tl,
    long
  ]{
    vspan=even,
    hspan=minimal,
    row{Z}={font={\footnotesize\bfseries}},
    hline{#4}={1pt,solid,tableLines},
    hline{Y}={1pt,solid,fg={tableOuterLines}},
    hline{2}={wd=0pt},
    row{odd}={bg=white},
    row{even}={bg=tableRows},
    row{1-#3}={bg=tableHeadingsBG},
    rowhead=#3,
    row{2-#3}={guard,font={\footnotesize\bfseries},
              fg={tableHeadingsFont},bg=white},
    #1,
    row{1-#3}={valign=m},
  }
    #2
    \l_tblr_body_tl
  \end{tblr}
}
%    \end{macrocode}
% We continue with the list of existing instrumentation.  Quantities are
% printed in text cells, so their multiplication sign uses \cs{texttimes};
% a math-only \cs{times} would fail for a nonempty quantity.
% Left-aligned columns use the standard \cs{raggedright} command through
% the shared theme setup. The description column selects this with |l|.
%    \begin{macrocode}
\NewDocumentCommand{\ExistingInstrumentationTable}{ O{existingInstrumentation} }{%
  \def\dfgLocalDB{#1}
  \def\tblrbody{}
  \DTLifdbexists{\dfgLocalDB}{%
    \DTLsort{ref-project-id}{\dfgLocalDB}%
  	\DTLforeach*{\dfgLocalDB}{%
  		\instProject=ref-project-id,%
  		\instInstrument=instrument,%
  		\instCompany=company,%
  		\instQuantity=quantity,%
  		\instYear=year,%
  		\instCost=cost,%
  		\instSource=financed-by%
  	}{%
		\protected@edef\tblrbody{\tblrbody
  			\getProject{\instProject}
      & \ifdefempty{\instQuantity}{}{
          \noexpand\dfgShowTag{\instProject/\instInstrument}{quantity}
            {\instQuantity}[\dfgLocalDB]\,\texttimes\,}
        \noexpand\dfgShowTag{\instProject/\instInstrument}{instrument}
          {\instInstrument}[\dfgLocalDB]
      \ifdefempty{\instCompany}{}{\space(
        \noexpand\dfgShowTag{\instProject/\instInstrument}{company}
          {\instCompany}[\dfgLocalDB])}
      & \noexpand\dfgShowTag{\instProject/\instInstrument}{year}
          {\instYear}[\dfgLocalDB]
      & \noexpand\dfgShowTag{\instProject/\instInstrument}{cost}
          {\noexpand\@@_show_existing_instrumentation_cost:n{\instCost}}[\dfgLocalDB]
      & \noexpand\dfgShowTag{\instProject/\instInstrument}{financed-by}
          {\instSource}[\dfgLocalDB]
  			\\
  		}}%
  	\begin{tblr}[%
  			theme=main,
  			expand=\tblrbody,
  			long,
			note{a}={Figures~ in~ thousands},
  		]{%
  			%rowsep=1pt,
  			vspan=even,
			colspec = {X[-1,m]X[4.5,l,m]X[m]X[-1,c,si={table-format=4.1}]X[1.7,m]},
  			rowhead = 1,

  			column{3}={halign={c}},
			column{4}={halign={r},guard},
  			column{5}={halign={l}},
  			% cell{1}{4}={valign={m}},
  			cell{1}{1-5} = {cmd={\hypersetup{linkcolor=tableLink}}},
            row{1}={valign=m, halign={c},guard},
  			% row{1} = {font={\bfseries},fg={white}}
  		}
  		Project %
  		 & Description~ of~ instrumentation                           %
  		 & {Year~ of~                       \\ purchase}
  		 & \SetCell{c}{{{Cost~ of~          \\purchase}}}\TblrNote{a}
  		 & {Source~ of~                     \\ funding}               \\
  		\tblrbody
  	\end{tblr}
  }
  {
  	Database~ \texttt{#1}~ missing.
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  	a	}
}
%    \end{macrocode}
% Laboratory-animal tables and queries resolve types through the registry.
% Tables prepare
% every data row and aggregate exactly once, before tabularray measures cells.
% Temporary totals are local to this call. Blank/invalid numbers remain
% unavailable, while explicit zero is a supplied value. Financial totals sum
% the declared funding columns; no inferred purchase/housing bill is substituted.
%    \begin{macrocode}
\tl_new:N \l_@@_animal_database_tl
\tl_new:N \l_@@_animal_totals_by_tl
\tl_new:N \l_@@_animal_assignments_tl
\tl_new:N \l_@@_animal_body_tl
\tl_new:N \l_@@_animal_type_tl
\tl_new:N \l_@@_animal_quantity_tl
\tl_new:N \l_@@_animal_weeks_tl
\tl_new:N \l_@@_animal_purchase_tl
\tl_new:N \l_@@_animal_requested_tl
\tl_new:N \l_@@_animal_existing_tl
\tl_new:N \l_@@_animal_number_tl
\prop_new:N \l_@@_animal_totals_prop
\prop_new:N \l_@@_animal_missing_prop
\prop_new:N \l_@@_animal_known_prop
\bool_new:N \l_@@_animal_incomplete_bool
\keys_define:nn { dfg / animal-table }
  {
    database .tl_set:N = \l_@@_animal_database_tl,
    database .value_required:n = true,
    totals-by .choices:nn = {group,type}
      { \tl_set:NV \l_@@_animal_totals_by_tl \l_keys_choice_tl },
    totals-by .value_required:n = true,
    totals-by / unknown .code:n =
      { \msg_warning:nnnn {dfg}{invalid-value}{#1}{group,~type} },
    unknown .code:n =
      { \msg_warning:nnee {dfg}{unknown-key}{\l_keys_path_str}{#1} }
  }
\cs_new_protected:Npn \@@_animal_column:Nn #1#2
  {
    \cs_set:Npn #1 {}
    \DTLifhaskey{\l_@@_animal_database_tl}{#2}
      { \tl_put_right:Nn \l_@@_animal_assignments_tl {#1=#2,} } {}
  }
\cs_new_protected:Npn \@@_animal_number:nNN #1#2#3
  {
    \tl_clear:N #3
    \DTLifnullorempty{#2} {}
      {
        \tl_set:Ne \l_@@_animal_number_tl {#2}
        \tl_trim_spaces:N \l_@@_animal_number_tl
        \str_if_eq:nnTF {#1}{quantity}
          {
            \exp_args:NnV \regex_match:nnTF
              {\A \d+ \Z} \l_@@_animal_number_tl
              { \tl_set:Ne #3 {\fp_eval:n {\l_@@_animal_number_tl}} }
              { \@@_animal_bad_number:n {#1} }
          }
          {
            \exp_args:NnV \regex_match:nnTF
              {\A \d+ (?: \. \d+ )? \Z} \l_@@_animal_number_tl
              { \tl_set:Ne #3 {\fp_eval:n {\l_@@_animal_number_tl}} }
              { \@@_animal_bad_number:n {#1} }
          }
      }
  }
\cs_new_protected:Npn \@@_animal_bad_number:n #1
  {
    \msg_warning:nneee {dfg}{animal-row-invalid}
      {\l_@@_animal_database_tl}{\pProject}
      {invalid~'#1=\l_@@_animal_number_tl';~
       use~a~non-negative~\str_if_eq:nnTF {#1}{quantity}{integer}{number}}
  }
\cs_new_protected:Npn \@@_animal_add:nN #1#2
  {
    \prop_if_in:NeF \l_@@_animal_totals_prop {#1}
      { \prop_put:Nen \l_@@_animal_totals_prop {#1}{0} }
    \tl_if_blank:VTF #2
      {
        \prop_put:Nen \l_@@_animal_missing_prop {#1}{true}
        \bool_set_true:N \l_@@_animal_incomplete_bool
      }
      {
        \prop_get:NeN \l_@@_animal_totals_prop {#1} \l_tmpa_tl
        \prop_put:Nee \l_@@_animal_totals_prop {#1}
          {\fp_eval:n {\l_tmpa_tl + #2}}
        \prop_put:Nen \l_@@_animal_known_prop {#1}{true}
      }
  }
\cs_new_protected:Npn \@@_animal_project:n #1
  { \tl_if_blank:nTF {#1}{\textemdash}{\getProject{#1}} }
\cs_new_protected:Npn \@@_animal_number_print:nn #1#2
  {
    \tl_if_blank:nTF {#2}
      { \textemdash }
      {
        \str_case:nnF {#1}
          {
            {funds}{\@@_show_eur:n {#2}}
            {costs}
              {\num[round-mode=places,round-precision=2,round-pad=false]{#2}}
          }
          {\@@_show_table_number:n {#2}}
      }
  }
\cs_new_protected:Npn \@@_animal_total_print:nn #1#2
  {
    \prop_get:NnN \l_@@_animal_totals_prop {#2} \l_tmpa_tl
    \prop_if_in:NnTF \l_@@_animal_missing_prop {#2}
      {
        \prop_if_in:NnTF \l_@@_animal_known_prop {#2}
          { \exp_args:NnV \@@_animal_number_print:nn {#1} \l_tmpa_tl }
          { \textemdash }
        \textsuperscript{*}
      }
      { \exp_args:NnV \@@_animal_number_print:nn {#1} \l_tmpa_tl }
  }
\cs_new_protected:Npn \@@_animal_prepare_row:
  {
    \DTLifnullorempty{\pProject}{\cs_set:Npn \pProject {}}{}
    \tl_clear:N \l_@@_animal_type_tl
    \DTLifnullorempty{\pSpecies}{}
      {
        \tl_set:Ne \l_@@_animal_type_tl {\pSpecies}
        \tl_trim_spaces:N \l_@@_animal_type_tl
      }
    \@@_animal_type_get:nnN {\l_@@_animal_type_tl}{label}
      \l_@@_animal_label_tl
    \tl_if_blank:VTF \l_@@_animal_label_tl
      {
        \tl_set:Nn \l_@@_animal_label_tl {Missing~type}
        \tl_set:Nn \l_@@_animal_group_tl {!unclassified}
        \tl_clear:N \l_@@_animal_rate_tl
        \msg_warning:nneee {dfg}{animal-row-invalid}
          {\l_@@_animal_database_tl}{\pProject}
          {a~registered~'species'~is~required}
      }
      {
        \@@_animal_type_get:nnN {\l_@@_animal_type_tl}{housing-rate}
          \l_@@_animal_rate_tl
        \str_if_eq:VnTF \l_@@_animal_totals_by_tl {type}
          { \tl_set_eq:NN \l_@@_animal_group_tl \l_@@_animal_type_tl }
          {
            \@@_animal_type_get:nnN {\l_@@_animal_type_tl}{total-group}
              \l_@@_animal_group_tl
          }
      }
    \@@_animal_number:nNN {quantity} \pQuantity \l_@@_animal_quantity_tl
    \@@_animal_number:nNN {weeks-kept} \pWeeksKept \l_@@_animal_weeks_tl
    \@@_animal_number:nNN {housing-rate}
      \l_@@_animal_rate_tl \l_@@_animal_rate_value_tl
    \@@_animal_number:nNN {purchasing-costs}
      \pPurchasingCosts \l_@@_animal_purchase_tl
    \@@_animal_number:nNN {requested-funds}
      \pRequestedFunds \l_@@_animal_requested_tl
    \@@_animal_number:nNN {existing-funds}
      \pExistingFunds \l_@@_animal_existing_tl
    \@@_animal_add:nN {group/\l_@@_animal_group_tl/quantity}
      \l_@@_animal_quantity_tl
    \@@_animal_add:nN {all/quantity} \l_@@_animal_quantity_tl
    \@@_animal_add:nN {all/requested-funds} \l_@@_animal_requested_tl
    \@@_animal_add:nN {all/existing-funds} \l_@@_animal_existing_tl
    \tl_put_right:Ne \l_@@_animal_body_tl
      {
        \exp_not:N \@@_animal_project:n {\exp_not:V \pProject}
        & \exp_not:N \dfgShowTag
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}{species}
            {\exp_not:V \l_@@_animal_label_tl}[\exp_not:V \l_@@_animal_database_tl]
        & \exp_not:N \@@_animal_data_cell:nnnn {quantity}
            {\exp_not:V \l_@@_animal_quantity_tl}{number}
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}
        & \exp_not:N \@@_animal_data_cell:nnnn {weeks-kept}
            {\exp_not:V \l_@@_animal_weeks_tl}{number}
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}
        & \exp_not:N \dfgShowCalculatedTag {animalHousingRate}
            {settings,\exp_not:V \l_@@_animal_database_tl}
            {\exp_not:N \@@_animal_number_print:nn {number}
              {\exp_not:V \l_@@_animal_rate_value_tl}}
        & \exp_not:N \@@_animal_data_cell:nnnn {purchasing-costs}
            {\exp_not:V \l_@@_animal_purchase_tl}{number}
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}
        & \exp_not:N \@@_animal_data_cell:nnnn {requested-funds}
            {\exp_not:V \l_@@_animal_requested_tl}{funds}
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}
        & \exp_not:N \@@_animal_data_cell:nnnn {existing-funds}
            {\exp_not:V \l_@@_animal_existing_tl}{funds}
            {\exp_not:V \pProject/\exp_not:V \l_@@_animal_type_tl}
        \exp_not:N \\
      }
  }
\cs_new_protected:Npn \@@_animal_data_cell:nnnn #1#2#3#4
  {
    \dfgShowTag{#4}{#1}
      {\@@_animal_number_print:nn {#3}{#2}}[\l_@@_animal_database_tl]
  }
\cs_new_protected:Npn \@@_animal_foreach:n #1
  { \DTLforeach*{\l_@@_animal_database_tl}{#1}{\@@_animal_prepare_row:} }
\cs_new_protected:Npn \@@_animal_subtotal:n #1
  {
    \prop_if_in:NnT \l_@@_animal_totals_prop {group/#1/quantity}
      {
        \str_if_eq:nnTF {#1}{!unclassified}
          { \tl_set:Nn \l_@@_animal_plural_tl {Unclassified} }
          {
            \@@_animal_type_get:nnN {#1}{label-plural}
              \l_@@_animal_plural_tl
          }
        \tl_put_right:Ne \l_@@_animal_body_tl
          {
            & \exp_not:N \SetCell{font=\exp_not:N \bfseries}
                \exp_not:V \l_@@_animal_plural_tl
            & \exp_not:N \SetCell{font=\exp_not:N \bfseries}
                \exp_not:N \@@_animal_total_print:nn {number}{group/#1/quantity}
            & \exp_not:N \SetCell{tableNoValue}
            & \exp_not:N \SetCell{tableNoValue}
            & \exp_not:N \SetCell{tableNoValue}
            & \exp_not:N \SetCell{tableNoValue}
            & \exp_not:N \SetCell{tableNoValue}
            \exp_not:N \\
          }
      }
  }
\cs_new_protected:Npn \@@_animal_prepare:
  {
    \tl_clear:N \l_@@_animal_body_tl
    \tl_clear:N \l_@@_animal_assignments_tl
    \prop_clear:N \l_@@_animal_totals_prop
    \prop_clear:N \l_@@_animal_missing_prop
    \prop_clear:N \l_@@_animal_known_prop
    \bool_set_false:N \l_@@_animal_incomplete_bool
    \clist_map_inline:nn {quantity,requested-funds,existing-funds}
      { \prop_put:Nnn \l_@@_animal_totals_prop {all/##1}{0} }
    \DTLifhaskey{\l_@@_animal_database_tl}{ref-project-id}
      { \DTLsort{ref-project-id}{\l_@@_animal_database_tl} }{}
    \@@_animal_column:Nn \pProject {ref-project-id}
    \@@_animal_column:Nn \pSpecies {species}
    \@@_animal_column:Nn \pQuantity {quantity}
    \@@_animal_column:Nn \pWeeksKept {weeks-kept}
    \@@_animal_column:Nn \pPurchasingCosts {purchasing-costs}
    \@@_animal_column:Nn \pRequestedFunds {requested-funds}
    \@@_animal_column:Nn \pExistingFunds {existing-funds}
    \exp_args:NV \@@_animal_foreach:n \l_@@_animal_assignments_tl
    \tl_put_right:Nn \l_@@_animal_body_tl
      {\SetHline{-}{tableLines,0.5pt}}
    \seq_map_function:NN \l_@@_animal_type_ids_seq \@@_animal_subtotal:n
    \@@_animal_subtotal:n {!unclassified}
    \tl_put_right:Nn \l_@@_animal_body_tl
      {
        Total & All~animals
        & \@@_animal_total_print:nn {number}{all/quantity}
        & \SetCell{tableNoValue}
        & \SetCell{tableNoValue}
        & \SetCell{tableNoValue}
        & \@@_animal_total_print:nn {funds}{all/requested-funds}
        & \@@_animal_total_print:nn {funds}{all/existing-funds}
      }
    \clist_map_inline:nn {quantity,requested-funds,existing-funds}
      {
        \prop_if_in:NnT \l_@@_animal_missing_prop {all/##1}
          {
            \msg_warning:nnee {dfg}{animal-total-incomplete}
              {\l_@@_animal_database_tl}{##1}
          }
      }
  }
% Inline queries share the table's validation, summation and missing-value
% display. They scan the selected rows without sorting the database or
% constructing a table body. Each call is local and reads current data/rates.
\msg_new:nnn {dfg}{animal-query-invalid}
  { Invalid~animal~query:~#1.~The~result~is~unavailable. }
\msg_new:nnn {dfg}{animal-query-incomplete}
  { Animal~query~in~'#1'~(#2):~'#3'~is~incomplete.~
    Only~supplied,~valid~amounts~are~included;~the~result~is~marked~*. }
\tl_new:N \l_@@_animal_query_scope_tl
\tl_new:N \l_@@_animal_query_id_tl
\tl_new:N \l_@@_animal_query_cost_tl
\tl_new:N \l_@@_animal_query_value_tl
\tl_new:N \l_@@_animal_query_format_tl
\bool_new:N \l_@@_animal_query_valid_bool
\bool_new:N \l_@@_animal_query_match_bool
\bool_new:N \l_@@_animal_query_product_valid_bool
\cs_new_protected:Npn \@@_animal_query_reject:n #1
  {
    \msg_warning:nne {dfg}{animal-query-invalid}{#1}
    \bool_set_false:N \l_@@_animal_query_valid_bool
  }
\cs_new_protected:Npn \@@_animal_query_select:nn #1#2
  {
    \str_if_eq:VnF \l_@@_animal_query_scope_tl {all}
      {
        \str_if_eq:VnF \l_@@_animal_query_scope_tl {#1}
          { \@@_animal_query_reject:n {use~either~'type'~or~'group'} }
      }
    \tl_set:Nn \l_@@_animal_query_scope_tl {#1}
    \tl_set:Ne \l_@@_animal_query_id_tl {#2}
    \tl_trim_spaces:N \l_@@_animal_query_id_tl
    \prop_if_in:NeF \l_@@_animal_types_prop
      {\l_@@_animal_query_id_tl/label}
      { \@@_animal_query_reject:n
          {'#1'~must~name~a~registered~animal~type,~got~'\l_@@_animal_query_id_tl'} }
  }
\keys_define:nn {dfg/animal-query}
  {
    database .tl_set:N = \l_@@_animal_database_tl,
    database .value_required:n = true,
    group .code:n = {\@@_animal_query_select:nn {group}{#1}},
    group .value_required:n = true,
    type .code:n = {\@@_animal_query_select:nn {type}{#1}},
    type .value_required:n = true,
    unknown .code:n =
      {\@@_animal_query_reject:n {unknown~key~'\l_keys_path_str'}}
  }
\keys_define:nn {dfg}
  {animal-cost-query .inherit:n = {dfg/animal-query}}
\keys_define:nn {dfg/animal-cost-query}
  {
    cost .choices:nn = {requested,existing,purchase,housing,total}
      {\tl_set:NV \l_@@_animal_query_cost_tl \l_keys_choice_tl},
    cost .value_required:n = true,
    cost / unknown .code:n =
      {\@@_animal_query_reject:n
        {unknown~cost~'#1';~use~requested,~existing,~purchase,~housing,~or~total}},
    unknown .code:n =
      {\@@_animal_query_reject:n {unknown~key~'\l_keys_path_str'}}
  }
\cs_new_protected:Npn \@@_animal_query_product:nn #1#2
  {
    \tl_clear:N \l_@@_animal_query_value_tl
    \bool_set_true:N \l_@@_animal_query_product_valid_bool
    \tl_map_inline:nn {#2}
      {
        \tl_if_blank:VT ##1
          {\bool_set_false:N \l_@@_animal_query_product_valid_bool}
      }
    \bool_if:NT \l_@@_animal_query_product_valid_bool
      {\tl_set:Ne \l_@@_animal_query_value_tl {\fp_eval:n {#1}}}
    \@@_animal_add:nN {query/selected}\l_@@_animal_query_value_tl
  }
\cs_new_protected:Npn \@@_animal_query_calculated:
  {
    \@@_animal_number:nNN {quantity}\pQuantity\l_@@_animal_quantity_tl
    \str_if_eq:VnF \l_@@_animal_query_cost_tl {housing}
      {
        \@@_animal_number:nNN {purchasing-costs}
          \pPurchasingCosts\l_@@_animal_purchase_tl
        \@@_animal_query_product:nn
          {\l_@@_animal_quantity_tl * \l_@@_animal_purchase_tl}
          {\l_@@_animal_quantity_tl \l_@@_animal_purchase_tl}
      }
    \str_if_eq:VnF \l_@@_animal_query_cost_tl {purchase}
      {
        \@@_animal_number:nNN {weeks-kept}\pWeeksKept\l_@@_animal_weeks_tl
        \@@_animal_type_get:nnN {\l_@@_animal_type_tl}{housing-rate}
          \l_@@_animal_rate_tl
        \@@_animal_number:nNN {housing-rate}
          \l_@@_animal_rate_tl\l_@@_animal_rate_value_tl
        \@@_animal_query_product:nn
          {\l_@@_animal_quantity_tl * \l_@@_animal_weeks_tl
            * \l_@@_animal_rate_value_tl}
          {\l_@@_animal_quantity_tl \l_@@_animal_weeks_tl
            \l_@@_animal_rate_value_tl}
      }
  }
\cs_new_protected:Npn \@@_animal_query_row:
  {
    \DTLifnullorempty{\pProject}{\cs_set:Npn \pProject {}}{}
    \tl_clear:N \l_@@_animal_type_tl
    \DTLifnullorempty{\pSpecies}{}
      {
        \tl_set:Ne \l_@@_animal_type_tl {\pSpecies}
        \tl_trim_spaces:N \l_@@_animal_type_tl
      }
    \bool_set_true:N \l_@@_animal_query_match_bool
    \str_case:Vn \l_@@_animal_query_scope_tl
      {
        {type}
          {
            \str_if_eq:VVF \l_@@_animal_type_tl \l_@@_animal_query_id_tl
              {\bool_set_false:N \l_@@_animal_query_match_bool}
          }
        {group}
          {
            \@@_animal_type_get:nnN {\l_@@_animal_type_tl}{total-group}
              \l_@@_animal_group_tl
            \str_if_eq:VVF \l_@@_animal_group_tl \l_@@_animal_query_id_tl
              {\bool_set_false:N \l_@@_animal_query_match_bool}
          }
      }
    \bool_if:NT \l_@@_animal_query_match_bool
      {
        \str_case:VnF \l_@@_animal_query_cost_tl
          {
            {quantity}
              {
                \@@_animal_number:nNN {quantity}
                  \pQuantity\l_@@_animal_query_value_tl
                \@@_animal_add:nN {query/selected}\l_@@_animal_query_value_tl
              }
            {requested}
              {
                \@@_animal_number:nNN {requested-funds}
                  \pRequestedFunds\l_@@_animal_query_value_tl
                \@@_animal_add:nN {query/selected}\l_@@_animal_query_value_tl
              }
            {existing}
              {
                \@@_animal_number:nNN {existing-funds}
                  \pExistingFunds\l_@@_animal_query_value_tl
                \@@_animal_add:nN {query/selected}\l_@@_animal_query_value_tl
              }
          }
          {\@@_animal_query_calculated:}
      }
  }
\cs_new_protected:Npn \@@_animal_query_foreach:n #1
  {\DTLforeach*{\l_@@_animal_database_tl}{#1}{\@@_animal_query_row:}}
\cs_new_protected:Npn \@@_animal_query:nn #1#2
  {
    \group_begin:
    \tl_set:Nn \l_@@_animal_database_tl {UpkeepLaboratoryAnimals}
    \tl_set:Nn \l_@@_animal_query_scope_tl {all}
    \tl_clear:N \l_@@_animal_query_id_tl
    \tl_set:Nn \l_@@_animal_query_cost_tl {requested}
    \tl_set:Nn \l_@@_animal_query_format_tl {funds}
    \bool_set_true:N \l_@@_animal_query_valid_bool
    \str_if_eq:nnTF {#1}{count}
      {
        \keys_set:nn {dfg/animal-query}{#2}
        \tl_set:Nn \l_@@_animal_query_cost_tl {quantity}
        \tl_set:Nn \l_@@_animal_query_format_tl {number}
      }
      {
        \keys_set:nn {dfg/animal-cost-query}{#2}
        \clist_if_in:nVT {purchase,housing,total}\l_@@_animal_query_cost_tl
          {\tl_set:Nn \l_@@_animal_query_format_tl {costs}}
      }
    \tl_trim_spaces:N \l_@@_animal_database_tl
    \bool_if:NTF \l_@@_animal_query_valid_bool
      {
        \DTLifdbexists{\l_@@_animal_database_tl}
          {
            \tl_clear:N \l_@@_animal_assignments_tl
            \prop_clear:N \l_@@_animal_totals_prop
            \prop_clear:N \l_@@_animal_missing_prop
            \prop_clear:N \l_@@_animal_known_prop
            \prop_put:Nnn \l_@@_animal_totals_prop {query/selected}{0}
            \@@_animal_column:Nn \pProject {ref-project-id}
            \@@_animal_column:Nn \pSpecies {species}
            \@@_animal_column:Nn \pQuantity {quantity}
            \@@_animal_column:Nn \pWeeksKept {weeks-kept}
            \@@_animal_column:Nn \pPurchasingCosts {purchasing-costs}
            \@@_animal_column:Nn \pRequestedFunds {requested-funds}
            \@@_animal_column:Nn \pExistingFunds {existing-funds}
            \exp_args:NV \@@_animal_query_foreach:n \l_@@_animal_assignments_tl
            \prop_if_in:NnT \l_@@_animal_missing_prop {query/selected}
              {
                \msg_warning:nneee {dfg}{animal-query-incomplete}
                  {\l_@@_animal_database_tl}
                  {\l_@@_animal_query_scope_tl
                    \tl_if_blank:VF \l_@@_animal_query_id_tl
                      {=\l_@@_animal_query_id_tl}}
                  {\l_@@_animal_query_cost_tl}
              }
            \exp_args:NV \@@_animal_total_print:nn
              \l_@@_animal_query_format_tl {query/selected}
          }
          {
            \msg_warning:nne {dfg}{database-not-found}{\l_@@_animal_database_tl}
            \textemdash
          }
      }
      {\textemdash}
    \group_end:
  }
\NewDocumentCommand \getAnimalCount {O{}}
  {\@@_animal_query:nn {count}{#1}}
\NewDocumentCommand \getAnimalCosts {O{}}
  {\@@_animal_query:nn {cost}{#1}}
\NewDocumentCommand{\UpkeepLaboratoryAnimalsTable}{ O{} }
  {
    \group_begin:
    \tl_set:Nn \l_@@_animal_database_tl {UpkeepLaboratoryAnimals}
    \tl_set:Nn \l_@@_animal_totals_by_tl {group}
    \tl_if_blank:nF {#1}
      {
        % The former optional argument was a bare database name.
        \tl_if_in:nnTF {#1}{=}
          { \keys_set:nn {dfg/animal-table}{#1} }
          { \tl_set:Nn \l_@@_animal_database_tl {#1} }
      }
    \tl_trim_spaces:N \l_@@_animal_database_tl
    \DTLifdbexists{\l_@@_animal_database_tl}
      {
        \@@_animal_prepare:
        \begin{tblr}[
          theme=main,
          expand=\l_@@_animal_body_tl,
          long,
          note{a}={Figures~in~EUR.},
        ]{
          vspan=even,
          colspec={Q[l] X[2,l]
            X[1.1,c,si={table-format=6}]
            X[1.3,c,si={table-format=3.2,table-auto-round=false}]
            X[-1,c,si={table-format=2.2,table-auto-round=false}]
            X[-1,c,si={table-format=5.2,table-auto-round=false}]
            Q[c,si={table-format=6}]
            X[-1,c,si={table-format=6}]},
          rowhead=1,
          column{3-8}={guard},
          hline{Y}={wd=1pt,tableLines},
          row{Z}={bg=white,fg=black,font=\footnotesize\bfseries,
            halign=c,valign=t},
          row{1}={guard,halign=c,valign=m,cmd={\hypersetup{linkcolor=tableLink}}},
        }
          Project & Species & Quantity
          & {Average\\number~of\\weeks~kept}
          & {Housing~costs\\per~animal\\per~week\TblrNote{a}}
          & {\mbox{Purchase}\\costs\\per~animal\TblrNote{a}}
          & {\mbox{Requested}\\funds\TblrNote{a}}
          & {Existing\\funds\TblrNote{a}} \\
          \l_@@_animal_body_tl
        \end{tblr}
        \bool_if:NT \l_@@_animal_incomplete_bool
          {
            \par\smallskip
            {\normalfont\footnotesize
              \textsuperscript{*}~Incomplete~total:~only~supplied,~valid~
              values~are~included.~A~dash~means~no~valid~value~was~supplied.}
          }
      }
      {
        Database~\texttt{\tl_use:N \l_@@_animal_database_tl}~missing.
        \msg_warning:nne {dfg}{database-not-found}{\l_@@_animal_database_tl}
      }
    \group_end:
  }
%    \end{macrocode}
%
%    \begin{macrocode}
\newcommand{\dfgRotate}[1]{\rotatebox{90}{\dfgPositionName{#1}}}
%    \end{macrocode}
%
% \paragraph{\refCom{getCountRequestedStaff} with aggregate indexing}
% Funding declarations update a property-list index when they are read.
% Consequently this command only performs one property lookup; it never
% traverses a datatool database.  This matters especially for
% \pkg{tabularray}, which evaluates table cells more than once while measuring
% and typesetting them.  Missing tuples and explicit zero values both print
% the faded multiplication sign used elsewhere in funding tables, preserving
% the display of the former database sum.
%
% \begin{docCommand}{getCountRequestedStaff}{\oarg{project}\marg{year}\marg{category}}
%   Sum of the requested staff |quantity-year|\meta{year} values in
%   the currently selected requested-funding database, normally
%   |RequestedFunding|, filtered by \meta{category} and (when
%   \meta{project} is given) by \meta{project}.  Display follows the
%   usual table conventions: an absent or zero sum prints a faded
%   \cs{texttimes}, and any other value prints verbatim.
% \end{docCommand}
%    \begin{macrocode}
\tl_new:N \l_@@_requested_staff_database_tl
\tl_set:Nn \l_@@_requested_staff_database_tl { RequestedFunding }

\NewDocumentCommand{\getCountRequestedStaff}{omm}{%
  \tl_set:Nx \l_@@_funding_cache_key_tl
  {
    \IfNoValueTF{#1}
      {\tl_use:N \l_@@_requested_staff_database_tl/
       __ALL__/#3/quantity-year#2}
      {\tl_use:N \l_@@_requested_staff_database_tl/
       #1/#3/quantity-year#2}
  }
  \dfgShowCalculatedTag{getCountRequestedStaff}
    {\l_@@_requested_staff_database_tl}
  {
    \prop_get:NVNTF \g_@@_funding_staff_quantity_prop
      \l_@@_funding_cache_key_tl \l_@@_funding_cache_value_tl
    {
      \fp_compare:nNnTF {\l_@@_funding_cache_value_tl} = {0}
        {\textcolor{tableNoValue!60!black}{\texttimes}}
        {\l_@@_funding_cache_value_tl}
    }
    {\textcolor{tableNoValue!60!black}{\texttimes}}
  }
}
%    \end{macrocode}
%
% \paragraph{\refCom{OverviewExistingStaffTable}}
% The chapter-2 overview reuses the project-level staff roster instead of
% maintaining a second set of totals.  Only records with
% |funding-status=existing| are counted.  Each record contributes one person
% to every distinct parent affiliation reached through its
% |ref-institution-id| list; when that field is absent, both organisation and
% category are inherited through |ref-person-id| from the central |person|
% row.  Multiple institutions at the same affiliation are counted once.  The
% comma-separated applicant affiliations come from |meta|
% and occupy the first numeric columns.  The heading is singular for one
% applicant affiliation and plural for several.  Other affiliations are added
% in first-use order.
%
% Because project declarations normally occur after chapter 2, the default
% database is |RequestedFundingStaffOverview|, restored from the preceding
% LaTeX run's auxiliary file.  Passing |RequestedFundingStaff| explicitly is
% useful in focused tests or documents that load all rows before the table.
%
% The DFG overview has seven fixed category rows.  The more detailed roster
% categories |medDoc| and |assistant| are folded into enquote{Other research
% staff} and enquote{Student and graduate assistants}, respectively.
%
% \begin{docCommand}{OverviewExistingStaffTable}{\oarg{database}}
%   Print the DFG enquote{Overview of existing staff}.  The optional database
%   defaults to |RequestedFundingStaffOverview|.  Use the public call
%   \refCom{printTable}|{OverviewExistingStaff}| in chapter 2.  Direct calls
%   also emit the standard skipped-item notice instead of querying unavailable
%   metadata when either fast-compilation mode is active.
% \end{docCommand}
%    \begin{macrocode}
\seq_new:N  \l_@@_oes_affiliation_seq
\prop_new:N \l_@@_oes_affiliation_name_prop
\prop_new:N \l_@@_oes_affiliation_abbreviation_prop
\prop_new:N \l_@@_oes_count_prop
\prop_new:N \l_@@_oes_row_affiliation_seen_prop
\tl_new:N   \l_@@_oes_applicant_affiliation_tl
\tl_new:N   \l_@@_oes_person_tl
\tl_new:N   \l_@@_oes_category_tl
\tl_new:N   \l_@@_oes_institutions_tl
\tl_new:N   \l_@@_oes_affiliation_tl
\tl_new:N   \l_@@_oes_candidate_affiliation_tl
\tl_new:N   \l_@@_oes_registered_affiliation_tl
\tl_new:N   \l_@@_oes_affiliation_name_tl
\tl_new:N   \l_@@_oes_affiliation_abbreviation_tl
\tl_new:N   \l_@@_oes_lookup_key_tl
\tl_new:N   \l_@@_oes_database_tl
\tl_new:N   \l_@@_oes_table_body_tl
\tl_new:N   \l_@@_oes_colspec_tl
\int_new:N  \l_@@_oes_affiliation_count_int
\int_new:N  \l_@@_oes_applicant_affiliation_count_int
\int_new:N  \l_@@_oes_other_affiliation_count_int
\int_new:N  \l_@@_oes_record_count_int
\clist_new:N \l_@@_oes_applicant_affiliation_clist

\cs_new_protected:Npn \@@_oes_resolve_person_fallbacks:
{
  \tl_if_blank:VF \l_@@_oes_person_tl
  {
    \DTLifdbexists{person}
    {
      \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{id}{person}{id}
        {\l_@@_oes_person_tl}
      \DTLifnullorempty{\l_tmpa_tl}
      {
        \msg_warning:nnee { dfg } { requested-staff-unresolved-person }
          { \pOESProject } { \l_@@_oes_person_tl }
      }
      {
        \tl_if_blank:VT \l_@@_oes_category_tl
        {
          \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{position}{person}{id}
            {\l_@@_oes_person_tl}
          \DTLifnullorempty{\l_tmpa_tl}
            { }
            { \tl_set:NV \l_@@_oes_category_tl \l_tmpa_tl }
        }
        \bool_lazy_all:nT
        {
          { \tl_if_blank_p:V \l_@@_oes_institutions_tl }
          { \tl_if_blank_p:V \l_@@_oes_affiliation_tl }
        }
        {
          \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{ref-institution-id}{person}{id}
            {\l_@@_oes_person_tl}
          \DTLifnullorempty{\l_tmpa_tl}
            { }
            { \tl_set:NV \l_@@_oes_institutions_tl \l_tmpa_tl }
          \tl_if_blank:VT \l_@@_oes_institutions_tl
          {
            \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{ref-affiliation-id}{person}{id}
              {\l_@@_oes_person_tl}
            \DTLifnullorempty{\l_tmpa_tl}
              { }
              { \tl_set:NV \l_@@_oes_affiliation_tl \l_tmpa_tl }
          }
        }
      }
    }
    {
      \msg_warning:nnee { dfg } { requested-staff-unresolved-person }
        { \pOESProject } { \l_@@_oes_person_tl }
    }
  }
}

\cs_new_protected:Npn \@@_oes_register_affiliation:n #1
{
  \tl_set:Ne \l_@@_oes_registered_affiliation_tl {#1}
  \tl_trim_spaces:N \l_@@_oes_registered_affiliation_tl
  \tl_if_blank:VF \l_@@_oes_registered_affiliation_tl
  {
    \seq_if_in:NVF \l_@@_oes_affiliation_seq
      \l_@@_oes_registered_affiliation_tl
    {
      \tl_clear:N \l_@@_oes_affiliation_name_tl
      \tl_clear:N \l_@@_oes_affiliation_abbreviation_tl
      \DTLifdbexists{affiliation}
      {
        \@@_getvalueforkey:Nnnnn{\l_@@_oes_affiliation_name_tl}
          {name}{affiliation}{id}{\l_@@_oes_registered_affiliation_tl}
        \DTLifnullorempty{\l_@@_oes_affiliation_name_tl}
        {
          \msg_warning:nnee { dfg } { requested-staff-unresolved-affiliation }
            { OverviewExistingStaff }
            { \l_@@_oes_registered_affiliation_tl }
          \tl_set:NV \l_@@_oes_affiliation_name_tl
            \l_@@_oes_registered_affiliation_tl
          \tl_set:NV \l_@@_oes_affiliation_abbreviation_tl
            \l_@@_oes_registered_affiliation_tl
        }
        {
          \@@_getvalueforkey:Nnnnn{\l_@@_oes_affiliation_abbreviation_tl}
            {abbreviation}{affiliation}{id}
            {\l_@@_oes_registered_affiliation_tl}
          \DTLifnullorempty{\l_@@_oes_affiliation_abbreviation_tl}
          {
            \msg_warning:nne { dfg } { requested-staff-missing-abbreviation }
              { \l_@@_oes_registered_affiliation_tl }
            \tl_set:NV \l_@@_oes_affiliation_abbreviation_tl
              \l_@@_oes_affiliation_name_tl
          }
          { }
        }
      }
      {
        \msg_warning:nnee { dfg } { requested-staff-unresolved-affiliation }
          { OverviewExistingStaff }
          { \l_@@_oes_registered_affiliation_tl }
        \tl_set:NV \l_@@_oes_affiliation_name_tl
          \l_@@_oes_registered_affiliation_tl
        \tl_set:NV \l_@@_oes_affiliation_abbreviation_tl
          \l_@@_oes_registered_affiliation_tl
      }
      \seq_put_right:NV \l_@@_oes_affiliation_seq
        \l_@@_oes_registered_affiliation_tl
      \prop_put:NVV \l_@@_oes_affiliation_name_prop
        \l_@@_oes_registered_affiliation_tl \l_@@_oes_affiliation_name_tl
      \prop_put:NVV \l_@@_oes_affiliation_abbreviation_prop
        \l_@@_oes_registered_affiliation_tl
        \l_@@_oes_affiliation_abbreviation_tl
    }
  }
}

\cs_new_protected:Npn \@@_oes_count_affiliation:n #1
{
  \tl_set:Ne \l_@@_oes_candidate_affiliation_tl {#1}
  \tl_trim_spaces:N \l_@@_oes_candidate_affiliation_tl
  \tl_if_blank:VF \l_@@_oes_candidate_affiliation_tl
  {
    \prop_if_in:NVF \l_@@_oes_row_affiliation_seen_prop
      \l_@@_oes_candidate_affiliation_tl
    {
      \prop_put:NVn \l_@@_oes_row_affiliation_seen_prop
        \l_@@_oes_candidate_affiliation_tl {1}
      \@@_oes_register_affiliation:n
        { \l_@@_oes_candidate_affiliation_tl }
      \tl_set:Nx \l_tmpb_tl
        { \l_@@_oes_category_tl / \l_@@_oes_candidate_affiliation_tl }
      \prop_get:NVNTF \l_@@_oes_count_prop \l_tmpb_tl \l_tmpc_tl
      { \int_set:Nn \l_tmpa_int { \l_tmpc_tl + 1 } }
      { \int_set:Nn \l_tmpa_int { 1 } }
      \prop_put:NVx \l_@@_oes_count_prop \l_tmpb_tl
        { \int_use:N \l_tmpa_int }
    }
  }
}

\cs_new_protected:Npn \@@_oes_collect_current:
{
  \DTLifnullorempty{\pOESPerson}
    { \tl_clear:N \l_@@_oes_person_tl }
    { \tl_set:Ne \l_@@_oes_person_tl {\pOESPerson} }
  \DTLifnullorempty{\pOESCategory}
    { \tl_clear:N \l_@@_oes_category_tl }
    { \tl_set:Ne \l_@@_oes_category_tl {\pOESCategory} }
  \DTLifnullorempty{\pOESInstitutions}
    { \tl_clear:N \l_@@_oes_institutions_tl }
    { \tl_set:Ne \l_@@_oes_institutions_tl {\pOESInstitutions} }
  \DTLifnullorempty{\pOESAffiliation}
    { \tl_clear:N \l_@@_oes_affiliation_tl }
    { \tl_set:Ne \l_@@_oes_affiliation_tl {\pOESAffiliation} }
  \@@_oes_resolve_person_fallbacks:
  \str_case:VnF \l_@@_oes_category_tl
  {
    { prof }        { \tl_set:Nn \l_@@_oes_category_tl { prof } }
    { prof-W2 }     { \tl_set:Nn \l_@@_oes_category_tl { prof } }
    { prof-W3 }     { \tl_set:Nn \l_@@_oes_category_tl { prof } }
    { groupLeader } { \tl_set:Nn \l_@@_oes_category_tl { groupLeader } }
    { postDoc }     { \tl_set:Nn \l_@@_oes_category_tl { postDoc } }
    { PhD }         { \tl_set:Nn \l_@@_oes_category_tl { PhD } }
    { medDoc }      { \tl_set:Nn \l_@@_oes_category_tl { research } }
    { research }    { \tl_set:Nn \l_@@_oes_category_tl { research } }
    { nonResearch } { \tl_set:Nn \l_@@_oes_category_tl { nonResearch } }
    { student }     { \tl_set:Nn \l_@@_oes_category_tl { student } }
    { assistant }   { \tl_set:Nn \l_@@_oes_category_tl { student } }
  }
  { \tl_clear:N \l_@@_oes_category_tl }
  \tl_if_blank:VF \l_@@_oes_category_tl
  {
    \int_incr:N \l_@@_oes_record_count_int
    \prop_clear:N \l_@@_oes_row_affiliation_seen_prop
    \tl_if_blank:VTF \l_@@_oes_institutions_tl
    {
      \tl_if_blank:VTF \l_@@_oes_affiliation_tl
      {
        \msg_warning:nne { dfg } { existing-staff-no-organisation }
          { \pOESProject / \pOESLastname }
      }
      { \@@_oes_count_affiliation:n { \l_@@_oes_affiliation_tl } }
    }
    {
      \clist_set:NV \l_tmpa_clist \l_@@_oes_institutions_tl
      \clist_map_inline:Nn \l_tmpa_clist
      {
        \tl_clear:N \l_tmpa_tl
        \DTLifdbexists{institution}
        {
          \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}
            {ref-affiliation-id}{institution}{id}{##1}
        }
        { }
        \DTLifnullorempty{\l_tmpa_tl}
        {
          \msg_warning:nnee { dfg } { requested-staff-unresolved-institution }
            { OverviewExistingStaff } {##1}
        }
        { \@@_oes_count_affiliation:n { \l_tmpa_tl } }
      }
    }
  }
}

\cs_new_protected:Npn \@@_oes_append_empty_cells:n #1
{
  \int_step_inline:nn {#1}
    { \tl_put_right:Nn \l_@@_oes_table_body_tl { & } }
}

\cs_new_protected:Npn \@@_oes_append_category:nn #1#2
{
  \tl_put_right:Nn \l_@@_oes_table_body_tl {#2}
  \seq_map_inline:Nn \l_@@_oes_affiliation_seq
  {
    \tl_set:Ne \l_@@_oes_lookup_key_tl { #1 / ##1 }
    \prop_get:NVNTF \l_@@_oes_count_prop
      \l_@@_oes_lookup_key_tl \l_tmpc_tl
    {
      \tl_put_right:Ne \l_@@_oes_table_body_tl
      {
        & \exp_not:N \dfgShowCalculatedTag{OverviewExistingStaffTable}
          {\exp_not:V \l_@@_oes_database_tl,person,institution,affiliation}
          {\exp_not:V \l_tmpc_tl}
      }
    }
    {
      \tl_put_right:Ne \l_@@_oes_table_body_tl
      {
        & \exp_not:N \dfgShowCalculatedTag{OverviewExistingStaffTable}
          {\exp_not:V \l_@@_oes_database_tl,person,institution,affiliation}{0}
      }
    }
  }
  \tl_put_right:Nn \l_@@_oes_table_body_tl { \\ }
}

\cs_new_protected:Npn \@@_oes_build_table_body:
{
  \int_set:Nn \l_@@_oes_affiliation_count_int
    { \seq_count:N \l_@@_oes_affiliation_seq }
  \int_set:Nn \l_@@_oes_other_affiliation_count_int
    {
      \l_@@_oes_affiliation_count_int
      - \l_@@_oes_applicant_affiliation_count_int
    }
  \tl_set:Nx \l_@@_oes_colspec_tl
    {
      X[l]~*{\int_use:N \l_@@_oes_affiliation_count_int}{Q[c]}
    }
  \tl_clear:N \l_@@_oes_table_body_tl
  \tl_put_right:Nx \l_@@_oes_table_body_tl
  {
    \exp_not:N \SetCell [r=3] {c} Category
    & \exp_not:N \SetCell
      [c=\int_use:N \l_@@_oes_affiliation_count_int] {c}
      {Number~of~persons}
  }
  \@@_oes_append_empty_cells:n
    { \l_@@_oes_affiliation_count_int - 1 }
  \tl_put_right:Nn \l_@@_oes_table_body_tl { \\ & }
  \int_compare:nNnTF
    { \l_@@_oes_applicant_affiliation_count_int } = {1}
  {
    \tl_put_right:Nn \l_@@_oes_table_body_tl
      { \SetCell{c} {at~the~applicant\\university} }
  }
  {
    \tl_put_right:Nx \l_@@_oes_table_body_tl
    {
      \exp_not:N \SetCell
        [c=\int_use:N \l_@@_oes_applicant_affiliation_count_int] {c}
        {at~the~applicant\\universities}
    }
    \@@_oes_append_empty_cells:n
      { \l_@@_oes_applicant_affiliation_count_int - 1 }
  }
  \int_compare:nNnT { \l_@@_oes_other_affiliation_count_int } > {0}
  {
    \tl_put_right:Nx \l_@@_oes_table_body_tl
    {
      & \exp_not:N \SetCell
        [c=\int_use:N \l_@@_oes_other_affiliation_count_int] {c}
        {at~other~participating\\institutions}
    }
    \@@_oes_append_empty_cells:n
      { \l_@@_oes_other_affiliation_count_int - 1 }
  }
  \tl_put_right:Nn \l_@@_oes_table_body_tl { \\ }
  \tl_put_right:Nn \l_@@_oes_table_body_tl { & }
  \seq_map_indexed_inline:Nn \l_@@_oes_affiliation_seq
  {
    \int_compare:nNnF {##1} = {1}
      { \tl_put_right:Nn \l_@@_oes_table_body_tl { & } }
    \tl_set:Nn \l_tmpa_tl {##2}
    \prop_get:NVN \l_@@_oes_affiliation_abbreviation_prop
      \l_tmpa_tl \l_tmpb_tl
    \tl_put_right:Ne \l_@@_oes_table_body_tl
    {
      \exp_not:N \dfgShowCalculatedTag{affiliationLabel}{affiliation}
        {\exp_not:V \l_tmpb_tl}
    }
  }
  \tl_put_right:Nn \l_@@_oes_table_body_tl { \\ }
  \@@_oes_append_category:nn { prof } { Professors }
  \@@_oes_append_category:nn { groupLeader }
    { {Junior~research~group\\leaders} }
  \@@_oes_append_category:nn { postDoc } { Postdoctoral~researchers }
  \@@_oes_append_category:nn { PhD } { Doctoral~researchers }
  \@@_oes_append_category:nn { research } { Other~research~staff }
  \@@_oes_append_category:nn { nonResearch } { Non-research~staff }
  \@@_oes_append_category:nn { student }
    { Student~and~graduate~assistants }
}

\cs_new_protected:Npn \@@_staff_abbreviation_note:n #1
{
  \par\smallskip\noindent
  \group_begin:
  \normalfont\footnotesize
  Abbreviations:\space #1.\par
  \group_end:
}

\cs_new_protected:Npn \@@_oes_print_legend:
{
  \@@_staff_abbreviation_note:n
  {
  \seq_map_indexed_inline:Nn \l_@@_oes_affiliation_seq
  {
    \int_compare:nNnF {##1} = {1} {;\space}
    \tl_set:Nn \l_tmpa_tl {##2}
    \prop_get:NVN \l_@@_oes_affiliation_abbreviation_prop
      \l_tmpa_tl \l_tmpb_tl
    \prop_get:NVN \l_@@_oes_affiliation_name_prop
      \l_tmpa_tl \l_tmpc_tl
    \dfgShowCalculatedTag{affiliationLabel}{affiliation}
      {\l_tmpb_tl}:~
    \dfgShowTag{##2}{name}{\l_tmpc_tl}[affiliation]
  }
  }
}

\cs_new_protected:Npn \@@_oes_typeset:n #1
{
  \begin{tblr}[
    theme=main,
    long,
    postsep=0pt,
    expand=\l_@@_oes_table_body_tl
  ]{
    colspec={#1},
    rowhead=3,
    row{4-Z}={valign=m},
    column{2-Z}={halign=c},
    row{1-3}={valign=m,font=\footnotesize\bfseries,
      fg=tableHeadingsFont,bg=tableHeadingsBG},
    hline{4}={wd=1pt,tableLines},
    vline{2}={wd=.75pt,tableLines}
  }
    \l_@@_oes_table_body_tl
  \end{tblr}
}

\cs_new_protected:Npn \@@_overview_existing_staff:n #1
{
  \group_begin:
  \tl_set:Nn \l_@@_oes_database_tl {#1}
  \seq_clear:N \l_@@_oes_affiliation_seq
  \prop_clear:N \l_@@_oes_affiliation_name_prop
  \prop_clear:N \l_@@_oes_affiliation_abbreviation_prop
  \prop_clear:N \l_@@_oes_count_prop
  \int_zero:N \l_@@_oes_record_count_int
  \tl_clear:N \l_@@_oes_applicant_affiliation_tl
  \DTLifdbexists{meta}
  {
    \@@_getvalueforkey:Nnnnn{\l_@@_oes_applicant_affiliation_tl}
      {ref-affiliation-id}{meta}{id}{crc}
  }
  { }
  \DTLifnullorempty{\l_@@_oes_applicant_affiliation_tl}
    { \tl_set:Nn \l_@@_oes_applicant_affiliation_tl { applicant } }
    { }
  \clist_set:NV \l_@@_oes_applicant_affiliation_clist
    \l_@@_oes_applicant_affiliation_tl
  \clist_map_inline:Nn \l_@@_oes_applicant_affiliation_clist
    { \@@_oes_register_affiliation:n {##1} }
  \int_set:Nn \l_@@_oes_applicant_affiliation_count_int
    { \seq_count:N \l_@@_oes_affiliation_seq }
  \DTLifdbexists{#1}
  {
    \DTLforeach*{#1}
    {
      \pOESProject=ref-project-id,
      \pOESStatus=funding-status,
      \pOESLastname=lastname,
      \pOESPerson=ref-person-id,
      \pOESCategory=category,
      \pOESInstitutions=ref-institution-id,
      \pOESAffiliation=ref-affiliation-id
    }
    {
      \DTLifnullorempty{\pOESStatus}
      { }
      {
        \tl_set:Ne \l_tmpa_tl { \pOESStatus }
        \str_if_eq:VnT \l_tmpa_tl { existing }
          { \@@_oes_collect_current: }
      }
    }
  }
  { \msg_warning:nnn { dfg } { database-not-found } {#1} }
  \int_compare:nNnT { \l_@@_oes_record_count_int } = {0}
    { \msg_warning:nnn { dfg } { existing-staff-no-data } {#1} }
  \@@_oes_build_table_body:
  \exp_args:NV \@@_oes_typeset:n \l_@@_oes_colspec_tl
  \@@_oes_print_legend:
  \group_end:
}

\NewDocumentCommand{\OverviewExistingStaffTable}
  { O{RequestedFundingStaffOverview} }
{
  \bool_if:NTF \l_@@_class_fastcompile_bool
    { \dfgItemSkipped{OverviewExistingStaffTable} }
    { \@@_overview_existing_staff:n {#1} }
}
%    \end{macrocode}
%
% \paragraph{\refCom{OverviewOfFundsRequestedForStaffTable}}
% Each body row is assembled by \cs{tl\_put\_right:Nx} into
% \cs{l\_tblr\_body\_tl} and contains twenty-five
% \refCom{getCountRequestedStaff} calls (five years $\times$ five
% categories) plus the leading \cs{getProject}\marg{project}; the
% foot row issues another twenty-five calls for the column totals.
%
% No indexing logic appears here: \refCom{addEntry} maintains the aggregate
% property list and \refCom{getCountRequestedStaff} encapsulates its lookup.
% The speed-up therefore applies transparently to every other consumer of the
% macro as well (marginalia, individual project tables, etc.).
%
% \begin{docCommand}{OverviewOfFundsRequestedForStaffTable}{\oarg{database}}
%   Emit the overview of requested staff funding.  \meta{database}
%   defaults to |RequestedFundingOverview|, which combines funding declared
%   before the document with project-local declarations restored from the
%   preceding run's auxiliary files.  The table contains five year
%   bands of five category columns (|postDoc|, |PhD|, |research|,
%   |nonResearch|, |student|), one body row per project, and a
%   \enquote{Total} foot row.
% \end{docCommand}
%    \begin{macrocode}
\NewDocumentCommand{\OverviewOfFundsRequestedForStaffTable}{ O{RequestedFundingOverview} }{%
 \def\tmpLocalDB{#1}
  \tl_set:Nn \l_@@_requested_staff_database_tl {#1}
  \DTLifdbexists{\tmpLocalDB}{%
	\tl_clear:N \l_tblr_body_tl
	\DTLsort{number}{project}
    \DTLforeach*[
      \not\DTLiseq{\tmpProjectStatus}{E}
      \and
      \not\DTLiseq{\tmpProjectConsiderForLists}{false}
    ]{project}{%
		\pProject               = number,
	    \tmpProjectStatus       = project-status,
	    \tmpProjectType         = project-type,
      \tmpProjectConsiderForLists = consider-for-lists,
	}{%
	\tl_put_right:Nx \l_tblr_body_tl
		{
			\getProject{\pProject}
			& \getCountRequestedStaff[\pProject]{1}{postDoc}
			& \getCountRequestedStaff[\pProject]{1}{PhD}
			& \getCountRequestedStaff[\pProject]{1}{research}
			& \getCountRequestedStaff[\pProject]{1}{nonResearch}
			& \getCountRequestedStaff[\pProject]{1}{student}

			& \getCountRequestedStaff[\pProject]{2}{postDoc}
			& \getCountRequestedStaff[\pProject]{2}{PhD}
			& \getCountRequestedStaff[\pProject]{2}{research}
			& \getCountRequestedStaff[\pProject]{2}{nonResearch}
			& \getCountRequestedStaff[\pProject]{2}{student}

			& \getCountRequestedStaff[\pProject]{3}{postDoc}
			& \getCountRequestedStaff[\pProject]{3}{PhD}
			& \getCountRequestedStaff[\pProject]{3}{research}
			& \getCountRequestedStaff[\pProject]{3}{nonResearch}
			& \getCountRequestedStaff[\pProject]{3}{student}

			& \getCountRequestedStaff[\pProject]{4}{postDoc}
			& \getCountRequestedStaff[\pProject]{4}{PhD}
			& \getCountRequestedStaff[\pProject]{4}{research}
			& \getCountRequestedStaff[\pProject]{4}{nonResearch}
			& \getCountRequestedStaff[\pProject]{4}{student}

			& \getCountRequestedStaff[\pProject]{5}{postDoc}
			& \getCountRequestedStaff[\pProject]{5}{PhD}
			& \getCountRequestedStaff[\pProject]{5}{research}
			& \getCountRequestedStaff[\pProject]{5}{nonResearch}
			& \getCountRequestedStaff[\pProject]{5}{student} \\
		}
     }

	\begin{tblr}[%
			theme=main,
			expand=\l_tblr_body_tl,
			long,
		]{%
			vspan=even,
			colspec = {*{1}{X[2,m]}
						*{24}{Q[c]}
				},
			rowhead = 2,
            row{1-2}={valign=m},
			colsep=4.5pt,
			vline{2,7,12,17,22}={tableLines,solid,wd=.75pt},
			vline{2,7,12,17,22}={3-Z}{tableLines,solid,wd=.75pt},
			hline{2}={wd=0pt},
			hline{3}={wd=1pt,tableLines},
			hline{Y}={wd=1pt,tableOuterLines},
			row{2} = {
				         fg={tableHeadingsFont},
				         bg={tableHeadingsBG},
				         halign={c}
			         },
			row{Z}= {font={\footnotesize\bfseries}}
		}
		 &
		\SetCell[c=5]{c} \dfgFundingYear{1}
		 & & & & &
		\SetCell[c=5]{c} \dfgFundingYear{2}
		 & & & & &
		\SetCell[c=5]{c} \dfgFundingYear{3}
		 & & & & &
		\SetCell[c=5]{c} \dfgFundingYear{4}
		 & & & & &
		\SetCell[c=5]{c} \dfgFundingYear{5}
		 & & & &
		\\
		\rotatebox{90}{Project} %
		 & \dfgRotate{postDoc}
		 & \dfgRotate{PhD}
		 & \dfgRotate{research}
		 & \dfgRotate{nonResearch}
		 & \dfgRotate{student}
		 & \dfgRotate{postDoc}
		 & \dfgRotate{PhD}
		 & \dfgRotate{research}
		 & \dfgRotate{nonResearch}
		 & \dfgRotate{student}
		 & \dfgRotate{postDoc}
		 & \dfgRotate{PhD}
		 & \dfgRotate{research}
		 & \dfgRotate{nonResearch}
		 & \dfgRotate{student}
		 & \dfgRotate{postDoc}
		 & \dfgRotate{PhD}
		 & \dfgRotate{research}
		 & \dfgRotate{nonResearch}
		 & \dfgRotate{student}
		 & \dfgRotate{postDoc}
		 & \dfgRotate{PhD}
		 & \dfgRotate{research}
		 & \dfgRotate{nonResearch}
		 & \dfgRotate{student}
		\\
		\l_tblr_body_tl
		Total
		 & \getCountRequestedStaff{1}{postDoc}
		 & \getCountRequestedStaff{1}{PhD}
		 & \getCountRequestedStaff{1}{research}
		 & \getCountRequestedStaff{1}{nonResearch}
		 & \getCountRequestedStaff{1}{student}
		 & \getCountRequestedStaff{2}{postDoc}
		 & \getCountRequestedStaff{2}{PhD}
		 & \getCountRequestedStaff{2}{research}
		 & \getCountRequestedStaff{2}{nonResearch}
		 & \getCountRequestedStaff{2}{student}
		 & \getCountRequestedStaff{3}{postDoc}
		 & \getCountRequestedStaff{3}{PhD}
		 & \getCountRequestedStaff{3}{research}
		 & \getCountRequestedStaff{3}{nonResearch}
		 & \getCountRequestedStaff{3}{student}
		 & \getCountRequestedStaff{4}{postDoc}
		 & \getCountRequestedStaff{4}{PhD}
		 & \getCountRequestedStaff{4}{research}
		 & \getCountRequestedStaff{4}{nonResearch}
		 & \getCountRequestedStaff{4}{student}
		 & \getCountRequestedStaff{5}{postDoc}
		 & \getCountRequestedStaff{5}{PhD}
		 & \getCountRequestedStaff{5}{research}
		 & \getCountRequestedStaff{5}{nonResearch}
		 & \getCountRequestedStaff{5}{student}
	\end{tblr}

}
  {
	Database~ \texttt{#1}~ missing.
	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
  \tl_set:Nn \l_@@_requested_staff_database_tl { RequestedFunding }
}
%    \end{macrocode}
%    \begin{macrocode}
\NewDocumentCommand{\getSumRequestedFundsInstrumentation}{som}{
  % #2: project
  % #3: year
  \IfNoValueTF{#2}
    { \@@_funding_sum_set:Nnnnn \SumFundsRequestedInstrumentation
        {RequestedFundingOverview}{__ALL__}{instrumentation}{#3} }
    { \@@_funding_sum_set:Nnnnn \SumFundsRequestedInstrumentation
        {RequestedFundingOverview}{#2}{instrumentation}{#3} }
  \@@_show_calculated_number:nnN
    {getSumRequestedFundsInstrumentation}
    {RequestedFundingOverview}
    \SumFundsRequestedInstrumentation
}
%    \end{macrocode}
% \paragraph{Requested instrumentation overview}
% The overview filters its database for |funding-type=instrumentation|.  When
% the filter yields no rows, the table is suppressed and a sentence names the
% proposed funding-period number instead.  This also covers a freshly created
% overview database on the first compilation pass.
% As in the existing-instrumentation list, body descriptions use native
% \cs{raggedright}; the two header rows retain their alignment.
%
% \begin{docCommand}{OverviewFundsRequestedInstrumentationTable}
%   {\oarg{database}}
%   Print the requested-instrumentation overview from \meta{database}, or state
%   that no instrumentation funds are requested for the current funding
%   period.  The database defaults to |RequestedFundingOverview|.
% \end{docCommand}
%    \begin{macrocode}
\NewDocumentCommand{\OverviewFundsRequestedInstrumentationTable} { O{RequestedFundingOverview} }{%
\def\tmpLocalDB{#1}
  \DTLifdbexists{\tmpLocalDB}{%
	\tl_clear:N \l_tblr_body_tl
	\DTLsort{ref-project-id}{\tmpLocalDB}
	\DTLforeach*[\DTLiseq{\pFundingType}{instrumentation}]{\tmpLocalDB}{%
		\pProject=ref-project-id,
        \pFundingType=type,
		\pDescription=category,
		\pSumYearOne=sum-year1,
		\pSumYearTwo=sum-year2,
		\pSumYearThree=sum-year3,
		\pSumYearFour=sum-year4,
		\pSumYearFive=sum-year5
	}{%
	\tl_put_right:Nx \l_tblr_body_tl
		{
			\getProject{\pProject}
			\printMarginalia{
				\getSumRequestedFundsInstrumentation[\pProject]{%
					sum-year1,
					sum-year2,
					sum-year3,
					sum-year4,
					sum-year5
				}
			}
      & \dfgShowTag{\pProject}{category}{\pDescription}[\tmpLocalDB]
      & \dfgShowTag{\pProject}{sum-year1}
          {\exp_not:N \@@_show_eur:n {\pSumYearOne}}[\tmpLocalDB]
      & \dfgShowTag{\pProject}{sum-year2}
          {\exp_not:N \@@_show_eur:n {\pSumYearTwo}}[\tmpLocalDB]
      & \dfgShowTag{\pProject}{sum-year3}
          {\exp_not:N \@@_show_eur:n {\pSumYearThree}}[\tmpLocalDB]
      & \dfgShowTag{\pProject}{sum-year4}
          {\exp_not:N \@@_show_eur:n {\pSumYearFour}}[\tmpLocalDB]
      & \dfgShowTag{\pProject}{sum-year5}
          {\exp_not:N \@@_show_eur:n {\pSumYearFive}}[\tmpLocalDB] \\
		}
     }
\tl_if_empty:VTF \l_tblr_body_tl
{
	\par\noindent
	No~funds~for~instrumentation~are~requested~for~funding~period~
	\dfgFundingPeriodNumeral.
	\par
}
{
\begin{tblr}[%
			theme=main,
			expand=\l_tblr_body_tl,
			long,
			remark{Note} = {Figures~ in~ EUR.}
		]{%
			vspan=even,
			row{Z} = {guard,font={\footnotesize\bfseries}},
			colspec = {
					*{1}{X[-1,t]}
						*{1}{X[2,l,t]}
						*{5}{X[-1,c,si={table-format=8}]}
				},
			rowhead = 2,
            row{1-2}={valign=m},

			column{3-7}={guard},
			%colsep=4.5pt,
			hline{2}={wd=0pt},
			hline{3}={wd=1pt,tableOuterLines},
			hline{Y}={wd=1pt,tableOuterLines},
			row{2} = {
				         fg={tableHeadingsFont},
				         bg={tableHeadingsBG},
				         halign={c},
				         guard,
			         },
		}
		Project
		 & {Description~of                                 \\ instrumentation}
		 & \SetCell[c=5]{c,guard} Funds~ requested~ for
		 &                                                                     % year 2
		 &                                                                     % year 3
		 &                                                                     % year 4
		 &                                                                     % year 5
		\\
		 &
		 & \dfgFundingYear{1}
		 & \dfgFundingYear{2}
		 & \dfgFundingYear{3}
		 & \dfgFundingYear{4}
		 & \dfgFundingYear{5}   \\

		\l_tblr_body_tl
		\SetCell[c=2]{l}Total
		\printMarginalia{
			\getSumRequestedFundsInstrumentation{%
				sum-year1,
				sum-year2,
				sum-year3,
				sum-year4,
				sum-year5
			}
		}
		 &
		 & \getSumRequestedFundsInstrumentation{sum-year1}
		 & \getSumRequestedFundsInstrumentation{sum-year2}
		 & \getSumRequestedFundsInstrumentation{sum-year3}
		 & \getSumRequestedFundsInstrumentation{sum-year4}
		 & \getSumRequestedFundsInstrumentation{sum-year5}   \\
	\end{tblr}
}
}
  {
	Database~ \texttt{#1}~ missing.
	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}

%    \end{macrocode}
%  Generic memoized \cs{DTLsumforkeys}
%    \begin{macrocode}
\prop_new:N \g_@@_dtlsum_cache_prop
%    \end{macrocode}
% Memoized form WITH filter:
%   |\@@_dtlsum_filtered:nnnnN {db}{filter-key}{filter-value}{cols}{result-cs}|
% This computes |\DTLsumforkeys[\DTLiseq{\pTmp}{value}][\pTmp=key]{db}{cols}{result}|
%    \begin{macrocode}

\cs_new_protected:Npn \@@_dtlsum_filtered:nnnnN #1#2#3#4#5 {
  \tl_set:Nx \l_tmpa_tl
  { #1 || \tl_to_str:n {#2} || \tl_to_str:n {#3} || \tl_to_str:n {#4} }
  \prop_get:NVNTF \g_@@_dtlsum_cache_prop \l_tmpa_tl \l_tmpb_tl
  { \cs_set_eq:NN #5 \l_tmpb_tl }
  {%
  	\DTLsumforkeys[\DTLiseq{\pCacheKey}{#3}][\pCacheKey=#2]{#1}{#4}{#5}%
  	\prop_gput:NVV \g_@@_dtlsum_cache_prop \l_tmpa_tl #5
  }
}

% Memoized form WITHOUT filter:
%   \@@_dtlsum_all:nnN {db}{cols}{result-cs}
\cs_new_protected:Npn \@@_dtlsum_all:nnN #1#2#3 {
  \tl_set:Nx \l_tmpa_tl
  { #1 || NOFILTER || \tl_to_str:n {#2} }
  \prop_get:NVNTF \g_@@_dtlsum_cache_prop \l_tmpa_tl \l_tmpb_tl
  { \cs_set_eq:NN #3 \l_tmpb_tl }
  {%
  	\DTLsumforkeys{#1}{#2}{#3}%
  	\prop_gput:NVV \g_@@_dtlsum_cache_prop \l_tmpa_tl #3
  }
}

% ============================================================
%  Drop-in replacements
% ============================================================

\providecommand{\SumPreviousRequestedFunding}{0}
\providecommand{\SumRequestedFunding}{0}

\NewDocumentCommand{\getSumPreviousRequestedFunding}{O{PreviousRequestedFunding}mm}{%
  \DTLifdbexists{#1}{%
  	\str_if_eq:nnTF {#2} {all}
  	{ \@@_dtlsum_all:nnN {#1} {#3} \SumPreviousRequestedFunding }
  	{ \@@_dtlsum_filtered:nnnnN {#1} {year} {#2} {#3} \SumPreviousRequestedFunding }%
    \@@_show_calculated_number:nnN
      {getSumPreviousRequestedFunding}{#1}
      \SumPreviousRequestedFunding
  }{%
  	\texttt{\color{error}XXX}%
  	\msg_warning:nne { dfg } { database-not-found } { #1 }%
  }%
}

\NewDocumentCommand{\getSumRequestedFunding}{O{RequestedFundingOverview}mm}{%
  \DTLifdbexists{#1}{%
  	\str_if_eq:nnTF {#2} {all}
    { \@@_funding_sum_set:Nnnnn \SumRequestedFunding {#1}
      {__ALL__}{#3}{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5} }
    { \@@_funding_sum_set:Nnnnn \SumRequestedFunding {#1}
      {__ALL__}{#3}{sum-year#2} }%
    \@@_show_calculated_number:nnN
      {getSumRequestedFunding}{#1}
      \SumRequestedFunding
  }{%
  	\texttt{\color{error}XXX}%
  	\msg_warning:nne { dfg } { database-not-found } { #1 }%
  }%
}

\NewDocumentCommand{\getTotalSumRequestedFunding}{O{RequestedFundingOverview}mm}{%
  \DTLifdbexists{#1}{%
    \tl_set:Nn \l_tmpa_tl {#3}
    \str_if_eq:nnT {#3} {all} { \tl_set:Nn \l_tmpa_tl {__ALL__} }
    \str_if_eq:nnTF {#2} {all}
      { \@@_funding_sum_set:Nnnnn \SumRequestedFunding {#1}
          {__ALL__}{\l_tmpa_tl}
          {sum-year1,sum-year2,sum-year3,sum-year4,sum-year5} }
      { \@@_funding_sum_set:Nnnnn \SumRequestedFunding {#1}
          {__ALL__}{\l_tmpa_tl}{sum-year#2} }%
    \@@_show_calculated_number:nnN
      {getTotalSumRequestedFunding}{#1}
      \SumRequestedFunding
  }{%
  	\texttt{\color{error}XXX}%
  	\msg_warning:nne { dfg } { database-not-found } { #1 }%
  }%
}

\NewDocumentCommand{\PreviousAndCurrentRequestedFundingTable}{O{PreviousRequestedFunding}}
{
  \def\tmpLocalDB{#1}
  \begin{tblr}[%
  		theme=main,
  		expand=\l_tblr_body_tl,
  		long,
		remark{Note} = {Figures~ in~ EUR.}
  	]{%
  		row{8,Z} = {guard,font={\footnotesize\bfseries}},
  		colspec = {
        *{1}{t{3.5cm}}@{}
        *{6}{X[-1,c,si={table-format=8}]}
      },
  		rowhead = 2,
		column{2-7}={guard},
  		%colsep=4.5pt,
  		hline{2}={wd=0pt},
  		hline{3}={wd=1pt,tableOuterLines},
  		% hline{Y}={wd=1pt,tableOuterLines},
  		row{1,2} = {
  			           fg={tableHeadingsFont},
  			           bg={tableHeadingsBG},
  			           halign={c},
                         valign={m},
  			           guard,
  		           },
  	}
    \SetCell[r=2]{m}{Financial~year/                         \\funding~period}
  	 & \SetCell[c=5]{c} Funding~ for                         % staff
  	 &                                                       % costs
  	 &                                                       % instrumentation
  	 &                                                       % fellowships
  	 &                                                       % globalfunds
     & \SetCell[r=2]{m} Total                                \\
  	 &
  	Staff
  	 & Direct~ costs
  	 & Instrumentation
  	 & Fellowships
  	 & Globalfunds
  	 &                                                       \\
	\dfgFundingYearPrevious{1}
    \printMarginalia{%
      \getSumPreviousRequestedFunding{1}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{1}{staff}             % staff
  	 & \getSumPreviousRequestedFunding{1}{costs}             % costs
  	 & \getSumPreviousRequestedFunding{1}{instrumentation}   % instrumentation
  	 & \getSumPreviousRequestedFunding{1}{fellowships}       % fellowships
  	 & \getSumPreviousRequestedFunding{1}{globalfunds}       % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{1}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total

	\dfgFundingYearPrevious{2}
    \printMarginalia{%
      \getSumPreviousRequestedFunding{2}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{2}{staff}             % staff
  	 & \getSumPreviousRequestedFunding{2}{costs}             % costs
  	 & \getSumPreviousRequestedFunding{2}{instrumentation}   % instrumentation
  	 & \getSumPreviousRequestedFunding{2}{fellowships}       % fellowships
  	 & \getSumPreviousRequestedFunding{2}{globalfunds}       % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{2}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total
	\dfgFundingYearPrevious{3}
    \printMarginalia{%
      \getSumPreviousRequestedFunding{3}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{3}{staff}             % staff
  	 & \getSumPreviousRequestedFunding{3}{costs}             % costs
  	 & \getSumPreviousRequestedFunding{3}{instrumentation}   % instrumentation
  	 & \getSumPreviousRequestedFunding{3}{fellowships}       % fellowships
  	 & \getSumPreviousRequestedFunding{3}{globalfunds}       % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{3}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total

	\dfgFundingYearPrevious{4}
    \printMarginalia{%
      \getSumPreviousRequestedFunding{4}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{4}{staff}             % staff
  	 & \getSumPreviousRequestedFunding{4}{costs}             % costs
  	 & \getSumPreviousRequestedFunding{4}{instrumentation}   % instrumentation
  	 & \getSumPreviousRequestedFunding{4}{fellowships}       % fellowships
  	 & \getSumPreviousRequestedFunding{4}{globalfunds}       % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{4}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total

	\dfgFundingYearPrevious{5}
    \printMarginalia{%
      \getSumPreviousRequestedFunding{5}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{5}{staff}             % staff
  	 & \getSumPreviousRequestedFunding{5}{costs}             % costs
  	 & \getSumPreviousRequestedFunding{5}{instrumentation}   % instrumentation
  	 & \getSumPreviousRequestedFunding{5}{fellowships}       % fellowships
  	 & \getSumPreviousRequestedFunding{5}{globalfunds}       % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{5}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total
  	\SetHline{-}{tableOuterLines,0.5pt}
  	\SetRow{belowsep=5pt}
    Ending~Funding~period
    \printMarginalia{%
      \getSumPreviousRequestedFunding{all}{%
        staff,costs,instrumentation,fellowships,globalfunds}%
    }
  	 & \getSumPreviousRequestedFunding{all}{staff}           % staff
  	 & \getSumPreviousRequestedFunding{all}{costs}           % costs
  	 & \getSumPreviousRequestedFunding{all}{instrumentation} % instrumentation
  	 & \getSumPreviousRequestedFunding{all}{fellowships}     % fellowships
  	 & \getSumPreviousRequestedFunding{all}{globalfunds}     % globalfunds
  	 &
  	\getSumPreviousRequestedFunding{all}{staff,costs,instrumentation,
  		fellowships,globalfunds}
  	\\ % Total

  	\SetHline{-}{tableOuterLines,1pt}
	\dfgFundingYear{1}
    \printMarginalia{\getTotalSumRequestedFunding{1}{all}}
  	 & \getSumRequestedFunding{1}{staff}
  	 & \getSumRequestedFunding{1}{costs}
  	 & \getSumRequestedFunding{1}{instrumentation}
  	 & \getSumRequestedFunding{1}{fellowships}
  	 & \getSumRequestedFunding{1}{globalfunds}
  	 & \getTotalSumRequestedFunding{1}{all}
  	\\
	\dfgFundingYear{2}
    \printMarginalia{\getTotalSumRequestedFunding{2}{all}}
  	 & \getSumRequestedFunding{2}{staff}
  	 & \getSumRequestedFunding{2}{costs}
  	 & \getSumRequestedFunding{2}{instrumentation}
  	 & \getSumRequestedFunding{2}{fellowships}
  	 & \getSumRequestedFunding{2}{globalfunds}
  	 & \getTotalSumRequestedFunding{2}{all}
  	\\

	\dfgFundingYear{3}
    \printMarginalia{\getTotalSumRequestedFunding{3}{all}}
  	 & \getSumRequestedFunding{3}{staff}
  	 & \getSumRequestedFunding{3}{costs}
  	 & \getSumRequestedFunding{3}{instrumentation}
  	 & \getSumRequestedFunding{3}{fellowships}
  	 & \getSumRequestedFunding{3}{globalfunds}
  	 & \getTotalSumRequestedFunding{3}{all}
  	\\
	\dfgFundingYear{4}
    \printMarginalia{\getTotalSumRequestedFunding{4}{all}}
  	 & \getSumRequestedFunding{4}{staff}
  	 & \getSumRequestedFunding{4}{costs}
  	 & \getSumRequestedFunding{4}{instrumentation}
  	 & \getSumRequestedFunding{4}{fellowships}
  	 & \getSumRequestedFunding{4}{globalfunds}
  	 & \getTotalSumRequestedFunding{4}{all}
  	\\
	\dfgFundingYear{5}
    \printMarginalia{\getTotalSumRequestedFunding{5}{all}}
  	 & \getSumRequestedFunding{5}{staff}
  	 & \getSumRequestedFunding{5}{costs}
  	 & \getSumRequestedFunding{5}{instrumentation}
  	 & \getSumRequestedFunding{5}{fellowships}
  	 & \getSumRequestedFunding{5}{globalfunds}
  	 & \getTotalSumRequestedFunding{5}{all}
  	\\

  	\SetHline{-}{tableOuterLines,0.5pt}
  	New~ Funding~period
    \printMarginalia{\getTotalSumRequestedFunding{all}{all}}
  	 & \getTotalSumRequestedFunding{all}{staff}              % staff
  	 & \getTotalSumRequestedFunding{all}{costs}              % costs
  	 & \getTotalSumRequestedFunding{all}{instrumentation}    % instrumentation
  	 & \getTotalSumRequestedFunding{all}{fellowships}        % fellowships
  	 & \getTotalSumRequestedFunding{all}{globalfunds}        % globalfunds
  	 &
  	\getTotalSumRequestedFunding{all}{all}
  	\\ % Total
  \end{tblr}
}
%    \end{macrocode}
%
% Section 2.1.1 reuses the project-level existing-funds declarations.  Both the
% stored values and the overview display use full euros.  The shared euro
% formatter adds thousands separators and rounds display values to whole euros
% (for example, |5000| is printed as |5,000|).
%
% |ref-affiliation-id| determines the column: every id listed in
% |meta/crc.ref-affiliation-id| is applicant core support, the sentinel
% |other-funds| selects other funding sources, and every other affiliation id
% is treated as another participating institution.  The descriptive
% |financed-by| value does not perform this classification.
%    \begin{macrocode}
\cs_new_protected:Npn
  \@@_get_sum_previous_requested_funding_eur:nnn #1#2#3
{
  \DTLifdbexists{#1}
  {
    \str_if_eq:nnTF {#2} {all}
      { \@@_dtlsum_all:nnN {#1} {#3} \SumPreviousRequestedFunding }
      { \@@_dtlsum_filtered:nnnnN
          {#1} {year} {#2} {#3} \SumPreviousRequestedFunding }
    \@@_show_calculated_number:nnN
      {getSumPreviousRequestedFunding}{#1}
      \SumPreviousRequestedFunding
  }
  {
    \texttt{\color{error}XXX}
    \msg_warning:nne { dfg } { database-not-found } {#1}
  }
}

\NewDocumentCommand{\getSumRequestedFundingDirectCosts}{
  O{RequestedAndExistingFundingDirectCostsOverview}
  m m }
{
  % #1: database
  % #2: year
  % #3: affiliation

  \str_if_eq:nnTF {#2}{all}
  {
  	\str_case:nn {#3}
  	{
		{applicant} {\DTLsumforkeys[\DTLisinlist{\pAffiliation}{\theApplicantID}]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  			{\SumRequestedFundingDirectCosts}}

  		{participant}{
  			\DTLsumforkeys[
				\not\DTLisinlist{\pAffiliation}{\theApplicantID}
  				\and
  				\not\DTLiseq{\pAffiliation}{other-funds}
  			]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  			{\SumRequestedFundingDirectCosts}}

  		{other-funds}{\DTLsumforkeys[\DTLiseq{\pAffiliation}{other-funds}]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  			{\SumRequestedFundingDirectCosts}}

  		{all}{\DTLsumforkeys{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  			{\SumRequestedFundingDirectCosts}}
  	}}
  {
  	\str_case:nn {#3}
  	{
		{applicant} {\DTLsumforkeys[\DTLisinlist{\pAffiliation}{\theApplicantID}]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year#2}
  			{\SumRequestedFundingDirectCosts}}

  		{participant}{
  			\DTLsumforkeys[
				\not\DTLisinlist{\pAffiliation}{\theApplicantID}
  				\and
  				\not\DTLiseq{\pAffiliation}{other-funds}
  			]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year#2}
  			{\SumRequestedFundingDirectCosts}}

  		{other-funds}{\DTLsumforkeys[\DTLiseq{\pAffiliation}{other-funds}]
  			[\pAffiliation=ref-affiliation-id]{#1}
  			{sum-year#2}
  			{\SumRequestedFundingDirectCosts}}

  		{all}{\DTLsumforkeys{#1}
  			{sum-year#2}
  			{\SumRequestedFundingDirectCosts}}
  	}}


  \@@_show_calculated_number:nnN
    {getSumRequestedFundingDirectCosts}{#1}
    \SumRequestedFundingDirectCosts
}

\NewDocumentCommand{\ExistingFundsDirectCostsTable}
  {O{RequestedAndExistingFundingDirectCostsOverview}}
{
  \DTLifdbexists{#1}{
  	\begin{tblr}[%
  			theme=main,
  			% expand=\l_tblr_body_tl,
  			long,
			remark{Note} = {Figures~ in~ EUR.}
  		]{%
  			row{7,Z} = {guard,font={\footnotesize\bfseries}},
			colspec = {
        *{1}{t{3.5cm}}
        *{4}{X[-1,c,si={table-format=9}]}
      },
  			% rowhead = 1,
			column{2-5}={guard},
  			%colsep=4.5pt,
  			% hline{3}={wd=1pt,tableOuterLines},
  			% hline{Y}={wd=1pt,tableOuterLines},
  			row{1} = {
  				         fg={tableHeadingsFont},
  				         bg={tableHeadingsBG},
  				         halign={c},
                         valign={m},
  				         guard,
  			         },
  		}
		 {Financial~year/                                                                         \\funding~period}
		 & {Core~ support~ provided~                                                             \\by~ applicant~
		   \dfgApplicantAffiliationsTF{university}{universities}}

  		 & {Core~ support~ provided~                                                             \\by~
  			   other~ participating~ institutions}
  		 & Other~ funds
  		 & Total                                                                                                              \\

		\dfgFundingYearPrevious{1}
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{1}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{1}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{1}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{1}{other-funds}}
		 &
		{\@@_get_sum_previous_requested_funding_eur:nnn
		    {PreviousExistingFundsDirectCosts}{1}{
				applicant,
				participant,
				other-funds}}                                                \\

		\dfgFundingYearPrevious{2}
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{2}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{2}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{2}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{2}{other-funds}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{2}{
				   applicant,
				   participant,
				   other-funds}}                                             \\

		\dfgFundingYearPrevious{3}
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{3}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{3}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{3}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{3}{other-funds}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{3}{
				   applicant,
				   participant,
				   other-funds}}                                             \\

		\dfgFundingYearPrevious{4}
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{4}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{4}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{4}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{4}{other-funds}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{4}{
				   applicant,
				   participant,
				   other-funds}}                                             \\

		\dfgFundingYearPrevious{5}
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{5}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{5}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{5}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{5}{other-funds}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{5}{
				   applicant,
				   participant,
				   other-funds}}                                             \\

  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{belowsep=5pt}
      Ending~Funding~period
      \printMarginalia{%
        \@@_get_sum_previous_requested_funding_eur:nnn
          {PreviousExistingFundsDirectCosts}{all}{%
          applicant,participant,other-funds}%
      }
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{all}{applicant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{all}{participant}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{all}{other-funds}}
		 & {\@@_get_sum_previous_requested_funding_eur:nnn
		      {PreviousExistingFundsDirectCosts}{all}{
				   applicant,
				   participant,
				   other-funds}}                                           \\

  		\SetHline{-}{tableOuterLines,1pt}
		\dfgFundingYear{1}
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{1}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{1}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{1}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{1}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{1}{all}                                                                         \\
		\dfgFundingYear{2}
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{2}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{2}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{2}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{2}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{2}{all}                                                                         \\
		\dfgFundingYear{3}
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{3}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{3}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{3}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{3}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{3}{all}                                                                         \\
		\dfgFundingYear{4}
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{4}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{4}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{4}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{4}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{4}{all}                                                                         \\
		\dfgFundingYear{5}
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{5}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{5}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{5}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{5}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{5}{all}                                                                         \\


  		\SetHline{-}{tableOuterLines,0.5pt}
		New~ Funding~period
      \printMarginalia{\getSumRequestedFundingDirectCosts[#1]{all}{all}}
		 & \getSumRequestedFundingDirectCosts[#1]{all}{applicant}
		 & \getSumRequestedFundingDirectCosts[#1]{all}{participant}
		 & \getSumRequestedFundingDirectCosts[#1]{all}{other-funds}
		 & \getSumRequestedFundingDirectCosts[#1]{all}{all}                                                                       \\
  	\end{tblr}
  }{
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}
%    \end{macrocode}
% The core part is definitely all about the projects.
%    \begin{macrocode}
\clist_new:N \l_tmp_research_area_clist
\bool_new:N  \l_@@_project_one_PI_bool
\bool_new:N  \g_@@_fast_project_started_bool
\bool_new:N  \l_@@_project_setup_scope_bool
\bool_new:N  \l_@@_project_setup_ending_bool
\tl_new:N    \l_@@_project_setup_status_tl
\tl_new:N    \l_@@_project_setup_pi_ids_tl
\tl_new:N    \l_@@_project_setup_aliases_tl

\cs_new_protected:Npn \@@_project_register_boldnames:n #1
{
  \bool_if:NT \l_@@_custom_emphasize_authors_bool
  {
    \DTLifdbexists{project}
    {
      \DTLifhaskey{project}{ref-person-id}
      {
        \@@_getvalueforkey:Nnnnn{\l_@@_project_setup_pi_ids_tl}
          {ref-person-id}{project}{id}{#1}
        \DTLifnullorempty{\l_@@_project_setup_pi_ids_tl}{}
        {
          \datatool_if_has_key:nnT {person} {name-alias}
          {
            \exp_args:NV \clist_map_inline:nn \l_@@_project_setup_pi_ids_tl
            {
              \@@_getvalueforkey:Nnnnn{\l_@@_project_setup_aliases_tl}
                {name-alias}{person}{id}{##1}
              \DTLifnullorempty{\l_@@_project_setup_aliases_tl}{}
                {\exp_args:NV \addboldnames \l_@@_project_setup_aliases_tl}
            }
          }
        }
      }{}
    }{}
  }
}

%    \end{macrocode}
% \paragraph{Recorded project-header space.}
% Normal rendering remains unboxed. At the first natural paragraph end after
% the header, a save-position node and delayed auxiliary write record the
% physical page span and final occupied height. The tuple also stores page
% depth, previous depth, trailing glue, section/subsection counters and text
% width/height. Removing and restoring trailing glue keeps KOMA's following
% heading spacing unchanged; delaying capture avoids forcing an extra paragraph.
% The shipout counter, rather than the printed page number, handles numbering
% resets. These records contain no metadata fields or formatted header strings.
%
% Focused mode emits fixed-height boxes and restores the recorded tail state.
% It writes the same record back so repeated fast builds retain it. Page width
% and height are the only automatic validity checks: data/font changes require
% a normal build. A marked fallback reserving half of \cs{textheight} keeps an unprimed build usable.
% The auxiliary no-op declaration lets an older class safely read new records.
% Both writers respect \cs{nofiles}; nothing is recorded when auxiliary output
% is disabled. Existing project-row loading for enabled plots is independent.
%    \begin{macrocode}
\prop_new:N \g_@@_project_header_geometry_prop
\int_new:N \g_@@_project_header_start_int
\box_new:N \l_@@_project_header_placeholder_box
\skip_new:N \l_@@_project_header_last_skip
\cs_new_protected:Npn \dfgRestoreProjectHeader #1#2
  {\exp_args:NNx \prop_gput:Nnn \g_@@_project_header_geometry_prop {#1}{#2}}
\cs_new_protected:Npn \@@_project_header_write:nn #1#2
  {\if@filesw
    \iow_now:Nx \@auxout
      {\token_to_str:N \providecommand\token_to_str:N \dfgRestoreProjectHeader [2]{}
       \token_to_str:N \dfgRestoreProjectHeader {#1}{\exp_not:n {#2}}}
   \fi}
\cs_new_protected:Npn \@@_project_header_record_start:
  {\int_gset:Nn \g_@@_project_header_start_int {\ReadonlyShipoutCounter}}
\cs_new_protected:Npn \@@_project_header_record:n #1
  {
    \mode_if_horizontal:TF
      {\AddToHookNext{para/after}{\@@_project_header_capture:n {#1}}}
      {\@@_project_header_capture:n {#1}}
  }
\cs_new_protected:Npn \@@_project_header_capture:n #1
  {
    \if@filesw
    \skip_set:Nn \l_@@_project_header_last_skip {\lastskip}
    \use:x
    {
      \skip_if_eq:nnF {\l_@@_project_header_last_skip}{0pt}
        {\skip_vertical:n {-\l_@@_project_header_last_skip}}
      \savepos
      \tex_write:D \exp_not:N \@auxout
      {
        \token_to_str:N \providecommand\token_to_str:N \dfgRestoreProjectHeader [2]{}
        \token_to_str:N \dfgRestoreProjectHeader {#1}
        {
          {\exp_not:N\int_eval:n
            {\exp_not:N\ReadonlyShipoutCounter-\int_use:N\g_@@_project_header_start_int-1}}
          {\exp_not:N\dim_eval:n
            {\dim_eval:n {\paperheight-1in-\voffset-\topmargin-\headheight-\headsep-\pagedepth+\l_@@_project_header_last_skip}
             -\exp_not:N\the\exp_not:N\lastypos sp}}
          {\dim_use:N \pagedepth}{\dim_use:N \prevdepth}{\skip_use:N \l_@@_project_header_last_skip}
          {\int_eval:n {\value{section}}}{\int_eval:n {\value{subsection}}}
          {\dim_use:N \textwidth}{\dim_use:N \textheight}
        }
      }
      \skip_if_eq:nnF {\l_@@_project_header_last_skip}{0pt}
        {\nobreak\skip_vertical:N \l_@@_project_header_last_skip}
    }
    \fi
  }
\cs_new_protected:Npn \@@_project_header_placeholder:nnn #1#2#3
  {
    \vbox_set_to_ht:Nnn \l_@@_project_header_placeholder_box {#2}
      {\hbox:n {\normalfont\dfgFastReference{#1}}\vss}
    \box_set_dp:Nn \l_@@_project_header_placeholder_box {#3}
    \nointerlineskip
    \box_use_drop:N \l_@@_project_header_placeholder_box
  }
\cs_new_protected:Npn \@@_project_header_replay:n #1
  {
    \exp_args:NNx \prop_get:NnNTF \g_@@_project_header_geometry_prop {#1} \l_tmpa_tl
      {
        \cs_set_protected:Npn \@@_project_header_replay_aux:nnnnnnnnn
          ##1##2##3##4##5##6##7##8##9
          {
            \@@_project_header_write:nn {#1}
              {{##1}{##2}{##3}{##4}{##5}{##6}{##7}{##8}{##9}}
            \bool_lazy_and:nnTF
              {\dim_compare_p:nNn {##8}={\textwidth}}
              {\dim_compare_p:nNn {##9}={\textheight}}
              {
                \int_step_inline:nn {##1}
                  {\@@_project_header_placeholder:nnn {#1-header}{\textheight}{0pt}\clearpage}
                \skip_set:Nn \l_@@_project_header_last_skip {##5}
                \@@_project_header_placeholder:nnn {#1-header}
                  {\dim_eval:n {##2-\l_@@_project_header_last_skip}}{##3}
                \skip_if_eq:nnF {\l_@@_project_header_last_skip}{0pt}
                  {\skip_vertical:N \l_@@_project_header_last_skip}
                \tex_prevdepth:D=##4\scan_stop:
                \setcounter{section}{##6}\setcounter{subsection}{##7}
              }
              {\@@_project_header_fallback:n {#1}}
          }
        \exp_after:wN \@@_project_header_replay_aux:nnnnnnnnn \l_tmpa_tl
      }
      {\@@_project_header_fallback:n {#1}}
  }
\cs_new_protected:Npn \@@_project_header_fallback:n #1
  {
    \PackageWarning{dfg-crc}{No~matching~normal~header~geometry~for~#1;~using~approximate~half~text~height~placeholder}
    \@@_project_header_placeholder:nnn {#1-header~(approximate~half~text~height)}{0.5\textheight}{0pt}
    \setcounter{section}{1}\setcounter{subsection}{0}
  }

\tl_new:N \l_@@_project_short_title_tl
% These selectors are expandable so a TOC write freezes this project's
% title and metadata field, rather than deferring the choice until TOC input.
\cs_new:Npn \@@_project_title_select:nnn #1#2#3
{
  \str_if_eq:eeTF
    {\tl_use:c {l_@@_custom_project_title_#1_tl}} {short}
    { \tl_if_empty:NTF \l_@@_project_short_title_tl {#3} {#2} }
    {#3}
}
\cs_new:Npn \@@_project_title_field:n #1
  { \@@_project_title_select:nnn {#1} {short-title} {name} }
\cs_new:Npn \@@_project_title:n #1
  { \@@_project_title_select:nnn {#1}
      {\l_@@_project_short_title_tl} {\tmpProjectTitle} }

% Read raw surnames once before the TOC write. Do not run formatted PI
% references (links, disambiguation or first-name preferences) in a PDF string.
% Hyperref supplies the project number through the existing numberline.
\tl_new:N \l_@@_project_bookmark_pis_tl
\tl_new:N \l_@@_project_bookmark_lastname_tl
\clist_new:N \l_@@_project_bookmark_ids_clist
\cs_new_protected:Npn \@@_project_bookmark_prepare:
  {
    \tl_clear:N \l_@@_project_bookmark_pis_tl
    \DTLifnullorempty{\tmpProjectPIids}{}
      {
        \clist_set:NV \l_@@_project_bookmark_ids_clist \tmpProjectPIids
        \clist_map_inline:Nn \l_@@_project_bookmark_ids_clist
          {
            \@@_getvalueforkey:Nnnnn \l_@@_project_bookmark_lastname_tl
              {lastname}{person}{id}{##1}
            \DTLifnullorempty{\l_@@_project_bookmark_lastname_tl}{}
              {
                \tl_if_blank:VF \l_@@_project_bookmark_lastname_tl
                  {
                    \tl_if_empty:NTF \l_@@_project_bookmark_pis_tl
                      {\tl_put_right:Nn \l_@@_project_bookmark_pis_tl {|~}}
                      {\tl_put_right:Nn \l_@@_project_bookmark_pis_tl {~-~}}
                    \tl_put_right:NV \l_@@_project_bookmark_pis_tl
                      \l_@@_project_bookmark_lastname_tl
                  }
              }
          }
      }
  }

\cs_new_protected:Npn \@@_print_project_head:n #1
{%
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \cleardoublepage
    \bool_if:NF \g_@@_fast_project_started_bool
    {
      \setcounter{page}{1}% Ignore page checkpoints restored by excluded files.
      \bool_gset_true:N \g_@@_fast_project_started_bool
    }
    \def\tmpLocalDB{project}%
    \setcounter{section}{0}%
    \setcounter{figure}{0}%
    \setcounter{table}{0}%
    \setcounter{secnumdepth}{2}%
    \restartlist{workpackages}%
    \tl_set:Nn \l__tmp_current_project_tl {#1}%
    \cs_set:Npn \tmpProjectNumber       {#1}%
    \cs_set:Npn \tmpProjectTitle        { }%
    \cs_set:Npn \tmpProjectStatus       { }%
    \cs_set:Npn \tmpProjectType         { }%
    \cs_set:Npn \tmpProjectResearchArea { }%
    \cs_set:Npn \tmpProjectPIids        { }%
    \bool_set_true:N \l_@@_project_one_PI_bool
    \renewcommand*{\theHpart}        {\thepart.#1}%
    \renewcommand*{\theHchapter}     {\thechapter.#1}%
    \renewcommand*{\theHsection}     {\thesection.#1}%
    \renewcommand*{\theHsubsection}  {\thesubsection.#1}%
    \renewcommand*{\theHsubsubsection}{\thesubsubsection.#1}%
    \renewcommand*{\theHfigure}      {\thefigure.#1}%
    \renewcommand*{\theHtable}       {\thetable.#1}%
    \renewcommand*{\theHfootnote}    {\thefootnote.#1}%
    \chead*{\textbf{Project~#1}\enspace|\enspace FAST~COMPILE~-~DRAFT}%
    \printThumbIndexOff
    \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
    {
      \@@_project_results_prepare:n {#1}%
      \citereset
      \begin{refsection}
    }
    \@@_project_header_replay:n {#1}
  }
  {
  % #1: project id
  \cleardoublepage
  \@@_project_header_record_start:
\phantomsection
  \def\tmpLocalDB{project}%
  \setcounter{section}{0}%
  \setcounter{figure}{0}%
  \setcounter{table}{0}%
  \setcounter{tocdepth}{0}%
  \restartlist{workpackages}%
  \tl_set:Nn \l__tmp_current_project_tl {#1}%
  \@@_project_results_prepare:n {#1}%

  \renewcommand*{\theHpart}        {\thepart.#1}%
  \renewcommand*{\theHchapter}     {\thechapter.#1}%
  \renewcommand*{\theHsection}     {\thesection.#1}%
  \renewcommand*{\theHsubsection}  {\thesubsection.#1}%
  \renewcommand*{\theHsubsubsection}{\thesubsubsection.#1}%
  \renewcommand*{\theHfigure}      {\thefigure.#1}%
  \renewcommand*{\theHtable}       {\thetable.#1}%
  \renewcommand*{\theHfootnote}    {\thefootnote.#1}%

  % --- single row scan for all project columns we need --------------------
  \getEntry*[\tmpLocalDB]{#1}{
  	\tmpProjectNumber       = number,
  	\tmpProjectTitle        = name,
  	\tmpProjectStatus       = project-status,
  	\tmpProjectType         = project-type,
  	\tmpProjectResearchArea = research-area,
  	\tmpProjectPIids        = ref-person-id
  }%

  % Optional column: old metadata need not define short-title at all.
  % Keep raw tokens; do not cache context-dependent formatted titles.
  \tl_clear:N \l_@@_project_short_title_tl
  \DTLifhaskey{project}{short-title}
  {
    \@@_getvalueforkey:Nnnnn \l_@@_project_short_title_tl
      {short-title}{project}{id}{#1}
    \DTLifnullorempty{\l_@@_project_short_title_tl}
      {\tl_clear:N \l_@@_project_short_title_tl}
      {\tl_if_blank:VT \l_@@_project_short_title_tl
        {\tl_clear:N \l_@@_project_short_title_tl}}
  }{}

  % --- precompute the few derived booleans we actually use ----------------
  \int_compare:nNnTF { \clist_count:N \tmpProjectPIids } > {1}
  	{ \bool_set_false:N \l_@@_project_one_PI_bool }
  	{ \bool_set_true:N  \l_@@_project_one_PI_bool }%

  \citereset
  \hypertarget{project:#1}{}%

  \use:x
  {
  	\exp_not:N \printThumbIndex
  	[ project \tl_head:n {#1} ]
  	{ \exp_not:n {#1} }
  }%

  \chead{\getPIofProject{#1}[\space\cdot\space]%
    \space|\space
    \dfgShowTag{#1}{\@@_project_title_field:n {runningHead}}
      {\@@_project_title:n {runningHead}}[project]}%

 

 % --- toc entry ----------------------------------------------------------
  \@@_project_bookmark_prepare:
  \addtocentrydefault{section}{
    \texorpdfstring
      { \dfgShowTag{#1}{number}{\tmpProjectNumber}[project] }
      { \tmpProjectNumber }
    \str_if_eq:eeF {\tmpProjectStatus} {C}
      {
        \texorpdfstring
          {\space\dfgShowTag{#1}{project-status}{\tmpProjectStatus}[project]}
          {}
      }%
  }
  {
    \texorpdfstring{\dfgShowTag{#1}{\@@_project_title_field:n {toc}}
      {\@@_project_title:n {toc}}[project]}{\l_@@_project_bookmark_pis_tl}%
  }% 
  \setcounter{secnumdepth}{2}%
  \addtocontents{toc}{\protect\setcounter{tocdepth}{0}}%
  \hypersetup{bookmarksdepth=0}%
  \begin{refsection}

  \section{%
    General~information~about~Project~%
    \texorpdfstring
    {
      \getProject{#1}%
      \str_if_eq:eeF {\tmpProjectStatus} {C}
        { \c_space_tl
          \dfgShowTag{#1}{project-status}{\tmpProjectStatus}[project] }%
    }
    {\tmpProjectNumber}%
   }
 \subsection{Project~title:~
   \texorpdfstring
     {\dfgShowTag{#1}{\@@_project_title_field:n {projectStart}}
       {\@@_project_title:n {projectStart}}[project]}
     {\@@_project_title:n {projectStart}}}

  % --- research areas (for active research and service projects) ----------
  \str_if_eq:eeF {\tmpProjectStatus} {E}
  {
   \bool_lazy_or:nnT
   { \str_if_eq_p:ee {\tmpProjectType} {research} }
   { \str_if_eq_p:ee {\tmpProjectType} {service}  }
   {%
  	\clist_clear:N \l_tmp_research_area_clist
    \clist_set:NV \tmpProjectResearchArea \tmpProjectResearchArea
  	\clist_sort:Nn \tmpProjectResearchArea
  	{ \fp_compare:nTF {##1 < ##2} {\sort_return_swapped:} {\sort_return_same:} }%
  	\clist_map_inline:Nn \tmpProjectResearchArea
  	{ \clist_put_right:Nn \l_tmp_research_area_clist { \dfgResearchAreasList{##1} } }%
    \subsection{Research~area
      \int_compare:nNnT { \clist_count:N \tmpProjectResearchArea } > {1}
        {s}
      :~
      \texorpdfstring
        {\dfgShowTag{#1}{research-area}
          {\clist_use:Nn \l_tmp_research_area_clist {,~}}[project]}
        {\clist_use:Nn \l_tmp_research_area_clist {,~}}}%
   }
  }

  \bool_if:NTF \l_@@_project_one_PI_bool
  { \subsection{Project~leader}  }
  { \subsection{Project~leaders} }

  \getPersonInformation{\tmpProjectPIids}\par
  \vspace*{1em}

  % --- contract information (skip for admin / ending) ---------------------
  \bool_lazy_or:nnF
  { \str_if_eq_p:ee {\tmpProjectType}   {admin} }
  { \str_if_eq_p:ee {\tmpProjectStatus} {E}     }
  {%
  	\begin{contractinformation}
  		\clist_map_inline:nn {C1,C2,C3,C4}
  		{ \dfgPIcontractInformation{##1} }%
  	\end{contractinformation}
  }

  % --- legal issues (skip for admin / mgk / ending) -----------------------
  % Use footnote-sized text, no extra row gap, and left-aligned numbers.
  % Keep follow-up answers on separate rows under their parent question.
  \bool_lazy_any:nF
  {
  	{ \str_if_eq_p:ee {\tmpProjectType}   {admin} }
  	{ \str_if_eq_p:ee {\tmpProjectType}   {mgk}   }
  	{ \str_if_eq_p:ee {\tmpProjectStatus} {E}     }
  }
  {%
  	\subsection{Legal~issues}%
  	\def\tmpLocalDB{project}%
	{\footnotesize This~project~includes}\\

  	\tl_clear:N \l_mytblr_body_tl
  	\tl_put_right:Ne \l_mytblr_body_tl
	{ 1. & research~requiring~compliance~with~discipline-specific~research~ethics~guidelines. & \checkYesNo{L1} \\ }%
  	\compareEntry{#1}{L1}{yes}
  	{
  		\tl_put_right:Ne \l_mytblr_body_tl
	{ & A~statement~from~the~responsible~ethics~committee~is~required~and~will~be~obtained~before~funding~starts. & \checkYesNo{L1a} \\ }%
  	}
  	{}%
  	\tl_put_right:Ne \l_mytblr_body_tl
  	{ 2. & clinical~trials & \checkYesNo{L2} \\ }%
  	\compareEntry{#1}{L2}{yes}
  	{
  		\tl_put_right:Ne \l_mytblr_body_tl
  		{ & A~copy~of~the~studies'~registration~is~included~with~the~proposal. & \checkYesNo{L2a} \\ }%
  	}
  	{}%
  	\tl_put_right:Ne \l_mytblr_body_tl
  	{
  		3. & experiments~involving~vertebrates. & \checkYesNo{L3} \\
  		4. & experiments~involving~recombinant~DNA. & \checkYesNo{L4} \\
  		5. & research~involving~human~embryonic~stem~cells. & \checkYesNo{L5} \\
  	}
  	\compareEntry{#1}{L5}{yes}
  	{
  		\tl_put_right:Ne \l_mytblr_body_tl
  		{ & Legal~authorization~has~been~obtained. & \checkYesNo{L5a} \\ }%
  	}
  	{}%
  	\tl_put_right:Ne \l_mytblr_body_tl
  	{
		6. & research~concerning~the~Convention~on~Biological~Diversity. & \checkYesNo{L6} \\
  		7. & investigations~involving~dual~use~research~of~concern. & \checkYesNo{L7} \\
  	}
  	\compareEntry{#1}{L7}{yes}
  	{
  		\tl_put_right:Ne \l_mytblr_body_tl
  		{ & A~copy~of~the~statement~by~the~institution's~research~ethics~committee~is~included~with~the~proposal. & \checkYesNo{L7a} \\ }%
  	}
  	{}%
  	\begin{tblr}[
  			theme  = plain,
  			expand = \l_mytblr_body_tl,
  		]{
			rowhead   = {0},
			rowsep    = {0pt},
  			hline{2}  = {0pt},
			rows      = {bg=white, halign=l, font=\footnotesize},
			cells     = {font=\footnotesize},
			column{1} = {halign=l},
			colspec   = {t{.3cm}@{}X[t]t{.85cm}}
  		}
  		\tl_use:N \l_mytblr_body_tl
  	\end{tblr}%
  }
    \@@_project_header_record:n {#1}
  }
}
%    \end{macrocode}
%    \begin{macrocode}
\NewDocumentCommand{\checkYesNo}{O{\tmpProjectNumber} m}
{%
  \compareEntry{#1}%        current project ID
  {#2}%                   which cell
  {yes}%                 if cell value is 'yes'
  {\dfgShowTag{#1}{#2}{{\bfseries\color{green}\faCheck}\,yes}[project]}%
  {\dfgShowTag{#1}{#2}{{\bfseries\color{red}\faTimes}\space no}[project]}%
}
%    \end{macrocode}
% Another helper command retrieves the PI contract information. The complete
% list, including conditional dates and funding sources, uses
% \cs{footnotesize}; the surrounding list environment scopes the font change.
%    \begin{macrocode}
% --------------------------------------------------------------------------
% PI contract information
% --------------------------------------------------------------------------

\seq_new:N   \l_@@_contract_pi_ids_seq
\seq_new:N   \l_@@_contract_true_pi_ids_seq
\seq_new:N   \l_@@_contract_false_pi_ids_seq
\clist_new:N \l_@@_contract_answers_clist
\tl_new:N    \l_@@_contract_answer_tl
\tl_new:N    \l_@@_contract_field_list_tl

\NewDocumentCommand{\dfgPIcontractInformation}{ o m }
 {
  % #1: optional comma-separated PI ids
  %     If omitted, use the current value of \tmpProjectPIids.
  % #2: question id, e.g. C1 / C2 / C3 / C4
  \IfNoValueTF {#1}
   {
    \@@_pi_contract_information:Vn \tmpProjectPIids {#2}
   }
   {
    \@@_pi_contract_information:nn {#1} {#2}
   }
 }

\cs_new_protected:Npn \@@_pi_contract_information:nn #1#2
 {
  % #1: comma-separated PI ids
  % #2: question id, e.g. C1 / C2 / C3 / C4
  \footnotesize
  \def\tmpLocalDB{person}%
  \seq_set_from_clist:Nn \l_@@_contract_pi_ids_seq {#1}

  \str_case:nn {#2}
   {
    {C1}
     {
      \item
      Is~the~employment~of~the~
      \bool_if:NTF \l_@@_project_one_PI_bool
       { project~leader~at~the~institution~ }
       { project~leaders~at~the~institutions~ }%
      indicated~contractually~secured~for~the~duration~of~
      the~proposed~funding~period?\space
      \@@_pi_contract_yes_no:n {#2}%
     }

    {C2}
     {
      \item
      \bool_if:NTF \l_@@_project_one_PI_bool
       { Does~the~above~mentioned~person~hold~a~fixed-term~position? }
       { Do~any~of~the~above~mentioned~persons~hold~fixed-term~positions? }%
      \space
      \@@_pi_contract_yes_no:n {#2}%

      \clist_if_in:NnT \l_@@_contract_answers_clist {yes}
       {
        \begin{contractinformation}
          \item End~date~of~fixed-term~contract:\space
          \@@_pi_contract_field_list:nN {C2a} \l_@@_contract_true_pi_ids_seq

          \item Further~employment~is~planned~until:\space
          \@@_pi_contract_field_list:nN {C2b} \l_@@_contract_true_pi_ids_seq
        \end{contractinformation}
       }
     }

    {C3}
     {
      \item
      \bool_if:NTF \l_@@_project_one_PI_bool
       { Will~the~above~mentioned~person~ }
       { Will~one~or~more~of~the~above-mentioned~persons~ }%
      retire~during~the~proposed~funding~period?\space
      \@@_pi_contract_yes_no:n {#2}%

      \clist_if_in:NnT \l_@@_contract_answers_clist {yes}
       {
        \begin{contractinformation}
          \item Anticipated~retirement~date:\space
          \@@_pi_contract_field_list:nN {C3a} \l_@@_contract_true_pi_ids_seq
        \end{contractinformation}
       }
     }

    {C4}
     {
      \item
      Funding~for~the~position~of~the~
      \bool_if:NTF \l_@@_project_one_PI_bool
       { project~leader~at~the~institution~ }
       { project~leaders~at~the~institutions~ }%
      indicated~is~covered~by~core~support~(state~funds~or~similar):\space
      \@@_pi_contract_yes_no:n {#2}%

      \clist_if_in:NnT \l_@@_contract_answers_clist {no}
       {
        \begin{contractinformation}
          \item Type~and~source~of~funding:\space
          \@@_pi_contract_field_list:nN {C4a} \l_@@_contract_false_pi_ids_seq
        \end{contractinformation}
       }
     }
   }
 }

\cs_generate_variant:Nn \@@_pi_contract_information:nn { Vn }


\cs_new_protected:Npn \@@_pi_contract_yes_no:n #1
 {
  % #1: question id, e.g. C1 / C2 / C3 / C4

  \clist_clear:N \l_@@_contract_answers_clist
  \seq_clear:N   \l_@@_contract_true_pi_ids_seq
  \seq_clear:N   \l_@@_contract_false_pi_ids_seq
  \tl_clear:N    \l_@@_contract_answer_tl

  \bool_set_true:N \l_tmpa_bool

  \seq_map_inline:Nn \l_@@_contract_pi_ids_seq
   {
    \bool_if:NTF \l_tmpa_bool
     { \bool_set_false:N \l_tmpa_bool }
     { \tl_put_right:Nn \l_@@_contract_answer_tl {,~} }%

    \@@_getvalueforkey:Nnnnn{\theLastName}{lastname}{person}{id}{##1}%

    \compareEntry{##1}{#1}{yes}
     {
      \tl_put_right:Nn \l_@@_contract_answer_tl
        { \dfgShowTag{##1}{#1}{\textbf{yes}}[person] }%
      \clist_put_right:Nn \l_@@_contract_answers_clist {yes}%
      \seq_put_right:Nn   \l_@@_contract_true_pi_ids_seq {##1}%
     }
     {
      \tl_put_right:Nn \l_@@_contract_answer_tl
        { \dfgShowTag{##1}{#1}{\textbf{no}}[person] }%
      \clist_put_right:Nn \l_@@_contract_answers_clist {no}%
      \seq_put_right:Nn   \l_@@_contract_false_pi_ids_seq {##1}%
     }

    \bool_if:NF \l_@@_project_one_PI_bool
     {
      \tl_put_right:Nx \l_@@_contract_answer_tl
       {
        \exp_not:n {~(}
        \exp_not:N \dfgShowTag{##1}{lastname}
          {\exp_not:V \theLastName}[person]
        \exp_not:n {)}
       }%
     }
   }

  \tl_use:N \l_@@_contract_answer_tl
 }


\cs_new_protected:Npn \@@_pi_contract_field_list:nN #1#2
 {
  % #1: field id, e.g. C2a / C2b / C3a / C4a
  % #2: sequence variable containing the PI ids for which the field is relevant

  \tl_clear:N \l_@@_contract_field_list_tl
  \bool_set_true:N \l_tmpa_bool

  \seq_map_inline:Nn #2
   {
    \bool_if:NTF \l_tmpa_bool
     { \bool_set_false:N \l_tmpa_bool }
     { \tl_put_right:Nn \l_@@_contract_field_list_tl {,~} }%

    \getEntry*[person]{##1}
     {
      \theFieldValue = #1,
      \theLastName   = lastname
     }%

    \tl_put_right:Nx \l_@@_contract_field_list_tl
     {
      \exp_not:N \textbf
      {
        \exp_not:N \dfgShowTag{##1}{#1}
          {\exp_not:V \theFieldValue}[person]
      }
      \int_compare:nNnT { \seq_count:N #2 } > {1}
       {
        \exp_not:n {~(}
        \exp_not:N \dfgShowTag{##1}{lastname}
          {\exp_not:V \theLastName}[person]
        \exp_not:n {)}
       }
     }%
   }

  \tl_use:N \l_@@_contract_field_list_tl
 }


\cs_new_protected:Npn \__pi_question_field_list:nn #1#2
{%
  \tl_clear:N \l_tmpa_tl
  \bool_set_true:N \l_tmpa_bool   % first-iteration flag
  \seq_map_inline:Nn #2
  {%
  	\bool_if:NTF \l_tmpa_bool
  	{ \bool_set_false:N \l_tmpa_bool }
  	{ \tl_put_right:Nn \l_tmpa_tl {,~} }%
  	\getEntry*[person]{##1}{
  		\theFieldValue = #1,
  		\theLastName   = lastname
  	}%
  	\tl_put_right:Nx \l_tmpa_tl
  	{
		\exp_not:N \textbf
    {
      \exp_not:N \dfgShowTag{##1}{#1}
        {\exp_not:V \theFieldValue}[person]
    }
  		\int_compare:nNnT { \seq_count:N #2 } > {1}
      {
        \exp_not:n {\space(}
        \exp_not:N \dfgShowTag{##1}{lastname}
          {\exp_not:V \theLastName}[person]
        \exp_not:n {)}
      }
  	}%
  }%
  \tl_use:N \l_tmpa_tl
}

\tl_new:N \l_@@_yes_names_tl
\tl_new:N \l_@@_no_names_tl

\cs_new_protected:Npn \tmp_person_question_yes_no:n #1
{%
  \clist_clear:N \l_tmpc_clist
  \seq_clear:N   \l_tmpd_seq
  \seq_clear:N   \l_tmpe_seq
  \tl_clear:N    \l_tmpa_tl
  \bool_set_true:N \l_tmpa_bool   % first-iteration flag
  \seq_map_inline:Nn \l_tmpa_seq
  {%
  	\bool_if:NTF \l_tmpa_bool
  	{ \bool_set_false:N \l_tmpa_bool }
  	{ \tl_put_right:Nn \l_tmpa_tl {,~} }%
    \@@_getvalueforkey:Nnnnn{\theLastName}{lastname}{person}{id}{##1}%
  	\compareEntry{##1}{#1}{yes}
  	{%
    \tl_put_right:Nn \l_tmpa_tl
      { \dfgShowTag{##1}{#1}{\textbf{yes}}[person] }%
  		\clist_put_right:Nn \l_tmpc_clist {yes}%
  		\seq_put_right:Nn   \l_tmpd_seq   {##1}%
  	}
  	{%
    \tl_put_right:Nn \l_tmpa_tl
      { \dfgShowTag{##1}{#1}{\textbf{no}}[person] }%
  		\clist_put_right:Nn \l_tmpc_clist {false}%
  		\seq_put_right:Nn   \l_tmpe_seq   {##1}%
  	}%
  	\bool_if:NF \l_@@_project_one_PI_bool
  	{%
    \tl_put_right:Nx \l_tmpa_tl
    {
      \exp_not:n {\space(}
      \exp_not:N \dfgShowTag{##1}{lastname}
        {\exp_not:V \theLastName}[person]
      \exp_not:n {)}
    }%
  	}%
  }%
  \tl_use:N \l_tmpa_tl
}
%    \end{macrocode}
% Ending projects report three distinct kinds of published results.  Each
% populated list is cited in its own reference segment.  The combined list is
% persisted in the auxiliary file so a preceding project-report bibliography
% can omit entries that are printed again in the result lists.
%    \begin{macrocode}
\clist_new:N \l_@@_project_results_quality_assured_clist
\clist_new:N \l_@@_project_results_other_clist
\clist_new:N \l_@@_project_results_patents_clist
\clist_new:N \l_@@_project_results_all_clist
\clist_new:N \l_@@_project_results_excluded_clist
\prop_new:N  \g_@@_project_results_aux_prop

\NewDocumentCommand{\dfgProjectResultsAux}{mm}
{
  \prop_gput:Nnn \g_@@_project_results_aux_prop {#1} {#2}
}

\cs_new_protected:Npn \@@_project_results_prepare:n #1
{
  \clist_clear:N \l_@@_project_results_excluded_clist
  \prop_get:NnNT \g_@@_project_results_aux_prop {#1} \l_tmpa_tl
  {
    \clist_set:NV \l_@@_project_results_excluded_clist \l_tmpa_tl
  }
}

\cs_new_protected:Npn \@@_project_results_collect:N #1
{
  \clist_map_inline:Nn #1
  {
    \str_if_eq:nnF {##1} {none}
    { \clist_put_right:Nn \l_@@_project_results_all_clist {##1} }
  }
}

\cs_new_protected:Npn \@@_project_results_register:
{
  \clist_clear:N \l_@@_project_results_all_clist
  \@@_project_results_collect:N \l_@@_project_results_quality_assured_clist
  \@@_project_results_collect:N \l_@@_project_results_other_clist
  \@@_project_results_collect:N \l_@@_project_results_patents_clist
  \clist_remove_duplicates:N \l_@@_project_results_all_clist
  \clist_set_eq:NN
    \l_@@_project_results_excluded_clist
    \l_@@_project_results_all_clist
  \iow_now:Ne \@auxout
  {
    \exp_not:N \dfgProjectResultsAux
    { \exp_not:V \l__tmp_current_project_tl }
    { \exp_not:V \l_@@_project_results_all_clist }
  }
}

\cs_new_protected:Npn \@@_project_results_skip_if_listed:
{
  \clist_map_inline:Nn \l_@@_project_results_excluded_clist
  {
    \str_if_eq:eeT {##1} { \strfield{entrykey} }
    {
      \skipentry
      \clist_map_break:
    }
  }
}

\defbibcheck{dfg-project-report}
{ \@@_project_results_skip_if_listed: }

\defbibheading{dfg-project-report-references}
{ \subsubsection{References} }

\NewDocumentCommand{\projectPublicationsHeading}{}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  { \subsection{Project-~and~subject-related~list~of~publications} }
}

\NewDocumentCommand{\projectNocite}{m}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  { \nocite{#1} }
}

% The frame wrapper retains the configured bibliography font. Clear the
% local selector first so disabled emphasis cannot inherit an outer selector.
\NewDocumentCommand{\printFrameBibliography}{o}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  {
    \group_begin:
    \tl_clear:N \l_@@_bibentry_highlight_keyword_tl
    \bool_if:NT \l_@@_custom_emphasize_entries_bool
      { \tl_set:Nn \l_@@_bibentry_highlight_keyword_tl {frametext-highlight} }
    \IfNoValueTF{#1}
    { \printbibliography }
    { \printbibliography[#1] }
    \group_end:
  }
}

\NewDocumentCommand{\printProjectBibliography}{o}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  {
    \group_begin:
    % biblatex applies \bibfont when it starts the bibliography list.
    \renewcommand*{\bibfont}{\normalfont\footnotesize}%
    \bool_if:NT \l_@@_custom_emphasize_entries_bool
    {
      \tl_if_blank:VF \l__tmp_current_project_tl
      {
        \tl_set:Ne \l_@@_bibentry_highlight_keyword_tl
          {\l__tmp_current_project_tl-highlight}
      }
    }
    \IfNoValueTF{#1}
    { \printbibliography }
    { \printbibliography[#1] }
    \group_end:
  }
}

\NewDocumentEnvironment{projectReport}{}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  { \begin{refsegment} }
}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  {
    \printProjectBibliography[
      segment = \therefsegment,
      check   = dfg-project-report,
      heading = dfg-project-report-references
    ]
    \end{refsegment}
  }
}

\keys_define:nn { dfg / project-results }
{
  quality-assured .clist_set:N = \l_@@_project_results_quality_assured_clist,
  quality-assured .value_required:n = true,
  other .clist_set:N = \l_@@_project_results_other_clist,
  other .value_required:n = true,
  patents .clist_set:N = \l_@@_project_results_patents_clist,
  patents .value_required:n = true,
  unknown .code:n = { \msg_warning:nnn { dfg } { unknown-key } {#1} }
}

\cs_new_protected:Npn \@@_project_results_print:Nn #1#2
{
  \clist_if_empty:NTF #1
  {#2}
  {
    \str_if_eq:eeTF { \clist_use:Nn #1 {,} } { none }
    { None. }
    {
      \begin{refsegment}
        \exp_args:Ne \nocite { \clist_use:Nn #1 {,} }
        \printProjectBibliography[segment=\therefsegment, heading=none]
      \end{refsegment}
    }
  }
}

\NewDocumentCommand{\printProjectResults}{m}
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
  {
  \FloatBarrier
  \group_begin:
    \clist_clear:N \l_@@_project_results_quality_assured_clist
    \clist_clear:N \l_@@_project_results_other_clist
    \clist_clear:N \l_@@_project_results_patents_clist
    \keys_set:nn { dfg / project-results } {#1}
    \@@_project_results_register:
    \setbibpreamble{}

    \subsubsection{Publications~with~scientific~quality~assurance}
    \@@_project_results_print:Nn
      \l_@@_project_results_quality_assured_clist
      { List~publications~with~scientific~quality~assurance. }

    \subsubsection{Other~publications~and~published~results}
    \@@_project_results_print:Nn
      \l_@@_project_results_other_clist
      { List~datasets,~software,~preprints,~protocols,~or~other~relevant~
        published~results~that~are~not~included~above. }

    \subsubsection{Patents}
    \@@_project_results_print:Nn
      \l_@@_project_results_patents_clist
      { List~patents~and~patent~applications,~or~state~that~none~resulted~
        from~the~project. }
  \group_end:
  }
}
%    \end{macrocode}
%    \begin{macrocode}
\NewDocumentCommand{\printProjectTail}{}{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \bool_if:NT \l_@@_class_fastcompile_project_show_publications_bool
    {
      \end{refsection}
      \resetboldnames
    }
  }
  {
    \end{refsection}
    \resetboldnames%
    \clearpage
    \addtocontents{toc}{\protect\setcounter{tocdepth}{1}}%
    \hypersetup{bookmarksdepth = 3}
    \colorlet{thumbIndexBG}{\l_@@_custom_thumbIndexBG_tl}
  }
  % Close the refsection and ship the project's last page before restoring
  % setup assignments. Fast project mode normally leaves that page pending.
  \bool_if:NT \l_@@_project_setup_scope_bool
  {
    \bool_if:NT \l_@@_class_fastcompile_project_bool { \clearpage }
    % Keep the next thumb-index slot across the setup group, just as with an
    % ordinary head. Customization values themselves remain group-local.
    \use:x
    {
      \exp_not:N \group_end:
      \exp_not:N \int_set:Nn \exp_not:N \l_thumb_index_int
        {\int_use:N \l_thumb_index_int}
    }
  }
}

\cs_new_protected:Npn \@@_project_setup_begin:
{
  \clearpage
  \group_begin:
  \bool_set_true:N \l_@@_project_setup_scope_bool
}

\cs_new_protected:Npn \@@_print_project_head_setup:nn #1#2
{
  \bool_if:NTF \l_@@_project_setup_scope_bool
  {
    \PackageError{dfg-crc}
      {A~project~setup~scope~is~already~open}
      {Finish~the~current~project~with~\string\printProject{{Tail}}~before~starting~another.}
  }
  {
    \bool_set_false:N \l_@@_project_setup_ending_bool
    \DTLifdbexists{project}
    {
      \DTLifhaskey{project}{project-status}
      {
        \@@_getvalueforkey:Nnnnn{\l_@@_project_setup_status_tl}
          {project-status}{project}{id}{#2}
        \DTLifnullorempty{\l_@@_project_setup_status_tl}{}
        {
          \str_if_eq:eeT {\l_@@_project_setup_status_tl} {E}
            {\bool_set_true:N \l_@@_project_setup_ending_bool}
        }
      }{}
    }{}
    \IfNoValueTF{#1}
      {\bool_if:NT \l_@@_project_setup_ending_bool {\@@_project_setup_begin:}}
      {\@@_project_setup_begin:}
    \bool_if:NT \l_@@_project_setup_ending_bool
    {
      \changeSettings{emphasizeAuthors=true,emphasizeEntries=false}
    }
    \IfNoValueF{#1}{#1}
    \@@_project_register_boldnames:n {#2}
    \@@_print_project_head:n {#2}
  }
}

\NewDocumentCommand{\printProjectHead}{+o m}
{
  \tl_if_blank:nTF {#2}
    {\@@_print_project_error:n {Head}}
    {\@@_print_project_head_setup:nn {#1}{#2}}
}

\cs_new_protected:Npn \@@_print_project_error:n #1
{
  \PackageError{dfg-crc}
    {Invalid~project~part~'#1'}
    {Use~\string\printProject{{Head}{project-id}}~or~\string\printProject{{Tail}}.}
}

\cs_new_protected:Npn \@@_print_project_dispatch:nnw #1#2#3 \q_stop
{
  \str_case:nnF {#2}
  {
    {Head}
    {
      \tl_if_blank:nTF {#3}
        { \@@_print_project_error:n {Head} }
        {
          \IfNoValueTF{#1}
            {\printProjectHead{#3}}
            {\printProjectHead[#1]{#3}}
        }
    }
    {Tail}
    {
      \tl_if_blank:nTF {#3}
        {
          \IfNoValueTF{#1}
            { \printProjectTail }
            {
              \PackageError{dfg-crc}
                {Optional~project~setup~code~is~only~valid~for~Head}
                {Put~setup~code~on~the~project's~Head;~use~\string\printProject{{Tail}}~to~finish~it.}
            }
        }
        { \@@_print_project_error:n {Tail} }
    }
  }
  { \@@_print_project_error:n {#2} }
}

\NewDocumentCommand{\printProject}{+o m}
{ \@@_print_project_dispatch:nnw {#1} #2 \q_stop }
%    \end{macrocode}
% To get the interim sum printed in the margin area we use a custom command.
% Table rows are denser than the package's default collision distance, so these
% notes use fixed placement with no collision padding. This keeps every total
% on its row anchor instead of accumulating a downward displacement.  The
% leader is placed before the value in the right margin and after the value in
% the left margin, keeping it adjacent to the table on both page sides. You can
% switch the notes off using the customization section.
%    \begin{macrocode}
\NewDocumentCommand{\printMarginalia}{O{\hrulefill}m}
{
  \bool_if:NT \l_@@_class_showmarginalia_bool
  {\bool_set_false:N \g_@@_tblr_inside_bool
	\bool_set_true:N \l_@@_show_tag_leftward_bool
    \marginalia[type=fixed,ysep=0pt]
    {
      \int_if_odd:nTF { \marginaliapage }
        { #1#2 }
        { #2#1 }
    }
	\bool_set_false:N \l_@@_show_tag_leftward_bool
  	\bool_set_true:N \g_@@_tblr_inside_bool
  }
}
%    \end{macrocode}
%
%    \begin{macrocode}
\tl_new:N \l__tmp_body_staff_tl
\tl_new:N \l__tmp_body_costs_tl
\tl_new:N \l__tmp_body_fellowships_tl
\tl_new:N \l__tmp_body_globalfunds_tl
\tl_new:N \l__tmp_body_instrumentation_tl
\cs_new_protected:Npn \@@_requested_funding_append_nonstaff:N #1
{
  \DTLaddall{\tmpHorizontalSum}{
    \pSumYearOne,
    \pSumYearTwo,
    \pSumYearThree,
    \pSumYearFour,
    \pSumYearFive
  }
  \tl_put_right:Ne #1
  {
    \dfgShowTag{\pProject/\pCategory}{category}{\pCategory}[\tmpLocalDB]
    \printMarginalia{\dfgShowCalculatedTag{RequestedFundingTable}{\tmpLocalDB}
      {\@@_show_eur:n{\tmpHorizontalSum}}}
    & & \dfgShowTag{\pProject/\pCategory}{sum-year1}
          {\@@_show_eur:n{\pSumYearOne}}[\tmpLocalDB]
    & & \dfgShowTag{\pProject/\pCategory}{sum-year2}
          {\@@_show_eur:n{\pSumYearTwo}}[\tmpLocalDB]
    & & \dfgShowTag{\pProject/\pCategory}{sum-year3}
          {\@@_show_eur:n{\pSumYearThree}}[\tmpLocalDB]
    & & \dfgShowTag{\pProject/\pCategory}{sum-year4}
          {\@@_show_eur:n{\pSumYearFour}}[\tmpLocalDB]
    & & \dfgShowTag{\pProject/\pCategory}{sum-year5}
          {\@@_show_eur:n{\pSumYearFive}}[\tmpLocalDB] \\
  }
}
\NewDocumentCommand{\RequestedFundingTable}{m}
{
  \group_begin:
  \sisetup{drop-zero-decimal=true}
  % #1: project
  \def\tmpLocalDB{RequestedFunding}%
  \DTLifdbexists{\tmpLocalDB}{%
  % Older funding entries may omit positionText; keep it an optional column.
  \DTLifhaskey{\tmpLocalDB}{positionText}{}{\DTLaddcolumn{\tmpLocalDB}{positionText}}
  	\tl_clear:N \l__tmp_body_staff_tl
  	\tl_clear:N \l__tmp_body_costs_tl
  	\tl_clear:N \l__tmp_body_fellowships_tl
  	\tl_clear:N \l__tmp_body_globalfunds_tl
  	\tl_clear:N \l__tmp_body_instrumentation_tl
  	\tl_put_right:Nn \l__tmp_body_staff_tl {

  		\SetRow{tableHeadingsBGalt}
  		\SetCell{font=\footnotesize\bfseries,halign=l}
		Staff
		& Qty & \SetCell{c} Sum
		& Qty & \SetCell{c} Sum
		& Qty & \SetCell{c} Sum
		& Qty & \SetCell{c} Sum
		& Qty & \SetCell{c} Sum \\
  	}

  	\tl_put_right:Nn \l__tmp_body_costs_tl {
  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{tableHeadingsBGalt}
  		\SetCell{font=\footnotesize\bfseries,halign=l}
		Direct~ Costs
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum  \\
  	}
  	\tl_put_right:Nn \l__tmp_body_fellowships_tl {
  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{tableHeadingsBGalt}
  		\SetCell{font=\footnotesize\bfseries,halign=l}
		Fellowships
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum \\
  	}
  	\tl_put_right:Nn \l__tmp_body_globalfunds_tl {
  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{tableHeadingsBGalt}
  		\SetCell{font=\footnotesize\bfseries,halign=l}
		Globalfunds
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum  \\
  	}
  	\tl_put_right:Nn \l__tmp_body_instrumentation_tl {
  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{tableHeadingsBGalt}
  		\SetCell{font=\footnotesize\bfseries,halign=l}
		Instrumentation
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum
		& & \SetCell{c} Sum  \\
  	}


	% One filtered traversal is enough: dispatch each matching row to the
	% token list for its funding type.  The previous implementation traversed
	% the complete, growing database once for every type.
	\DTLforeach[\DTLiseq{#1}{\pProject}]{\tmpLocalDB}{
  			\pProject           =ref-project-id,
  			\pType              =type,
  			\pCategory          =category,
  			\pPercentage        =percentage,
  			\pPositionText      =positionText,
  			\pQuantityYearOne   =quantity-year1,
  			\pQuantityYearTwo   =quantity-year2,
  			\pQuantityYearThree =quantity-year3,
  			\pQuantityYearFour  =quantity-year4,
  			\pQuantityYearFive  =quantity-year5,
  			\pSumYearOne        =sum-year1,
  			\pSumYearTwo        =sum-year2,
  			\pSumYearThree      =sum-year3,
  			\pSumYearFour       =sum-year4,
  			\pSumYearFive       =sum-year5
  		}{

  			\str_case:enF {\pType}
  			{
				{staff} {
          % Use the category only when no custom position label is supplied.
          \DTLifnullorempty{\pPositionText}
            {
              \tl_set:Ne \l_tmpa_tl
                { \dfgShowTag{\pProject/\pCategory}{category}
                    {\dfgCategoryName{\pCategory}}[\tmpLocalDB] }
            }
            {
              \tl_set:Ne \l_tmpa_tl
                { \dfgShowTag{\pProject/\pCategory}{positionText}
                    {\exp_not:V \pPositionText}[\tmpLocalDB] }
            }
					\DTLaddall{\tmpHorizontalSum}{
  						\pSumYearOne,
  						\pSumYearTwo,
  						\pSumYearThree,
  						\pSumYearFour,
  						\pSumYearFive
  					}
  					\tl_put_right:Ne \l__tmp_body_staff_tl
  					{

            \exp_not:V \l_tmpa_tl
            ,~
            \dfgShowTag{\pProject/\pCategory}{percentage}
              {\qty{\pPercentage}{\percent}}[\tmpLocalDB]
						\printMarginalia{\dfgShowCalculatedTag{RequestedFundingTable}
              {\tmpLocalDB}{\@@_show_eur:n{\tmpHorizontalSum}}}
						& \dfgShowTag{\pProject/\pCategory}{quantity-year1}
                {\@@_show_table_number:n{\pQuantityYearOne}}[\tmpLocalDB]
						& \dfgShowTag{\pProject/\pCategory}{sum-year1}
                {\@@_show_eur:n{\pSumYearOne}}[\tmpLocalDB]
						& \dfgShowTag{\pProject/\pCategory}{quantity-year2}
                {\@@_show_table_number:n{\pQuantityYearTwo}}[\tmpLocalDB] % year2
						& \dfgShowTag{\pProject/\pCategory}{sum-year2}
                {\@@_show_eur:n{\pSumYearTwo}}[\tmpLocalDB]
						& \dfgShowTag{\pProject/\pCategory}{quantity-year3}
                {\@@_show_table_number:n{\pQuantityYearThree}}[\tmpLocalDB] % year3
						& \dfgShowTag{\pProject/\pCategory}{sum-year3}
                {\@@_show_eur:n{\pSumYearThree}}[\tmpLocalDB]
						& \dfgShowTag{\pProject/\pCategory}{quantity-year4}
                {\@@_show_table_number:n{\pQuantityYearFour}}[\tmpLocalDB] % year4
						& \dfgShowTag{\pProject/\pCategory}{sum-year4}
                {\@@_show_eur:n{\pSumYearFour}}[\tmpLocalDB]
						& \dfgShowTag{\pProject/\pCategory}{quantity-year5}
                {\@@_show_table_number:n{\pQuantityYearFive}}[\tmpLocalDB] % year5
						& \dfgShowTag{\pProject/\pCategory}{sum-year5}
                {\@@_show_eur:n{\pSumYearFive}}[\tmpLocalDB]
  						\\
  					}
				}
        {costs}
          {\@@_requested_funding_append_nonstaff:N \l__tmp_body_costs_tl}
        {fellowships}
          {\@@_requested_funding_append_nonstaff:N \l__tmp_body_fellowships_tl}
        {globalfunds}
          {\@@_requested_funding_append_nonstaff:N \l__tmp_body_globalfunds_tl}
        {instrumentation}
          {\@@_requested_funding_append_nonstaff:N \l__tmp_body_instrumentation_tl}
			}
      { }
	}
  	\tl_put_right:Ne \l__tmp_body_staff_tl
  	{
  		\SetRow{belowsep=5pt}
  		\SetHline{-}{tableOuterLines,0.5pt}
  		Total~
  		\printMarginalia{%
  			\getSumRequestedFunds{#1}{staff}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  		}
  		& \SetCell{bg=tableNoValue}
  		& \getSumRequestedFunds{#1}{staff}{sum-year1}
  		& \SetCell{bg=tableNoValue}
  		& \getSumRequestedFunds{#1}{staff}{sum-year2}
  		& \SetCell{bg=tableNoValue}
  		& \getSumRequestedFunds{#1}{staff}{sum-year3}
  		& \SetCell{bg=tableNoValue}
  		& \getSumRequestedFunds{#1}{staff}{sum-year4}
  		& \SetCell{bg=tableNoValue}
  		& \getSumRequestedFunds{#1}{staff}{sum-year5}
  		\\
  	}

  	\clist_map_inline:nn {
  		costs,fellowships,globalfunds,instrumentation
  	}{

  		\tl_put_right:ce { l__tmp_body_##1_tl }
  		{
  			\SetRow{belowsep=5pt}
  			\SetHline{-}{tableLines,0.5pt}
  			Total
  			\printMarginalia{%
  				\getSumRequestedFunds{#1}{##1}
  				{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  			}
  			& &
  			\getSumRequestedFunds{#1}{##1}{sum-year1}
  			& &
  			\getSumRequestedFunds{#1}{##1}{sum-year2}
  			& &
  			\getSumRequestedFunds{#1}{##1}{sum-year3}
  			& &
  			\getSumRequestedFunds{#1}{##1}{sum-year4}
  			& &
  			\getSumRequestedFunds{#1}{##1}{sum-year5}
  			\\
  		}}

  	% delete when zero
  	\dfgCheckIfZeroShowCategory{#1}{staff}
  	\dfgCheckIfZeroShowCategory{#1}{costs}
  	\dfgCheckIfZeroShowCategory{#1}{fellowships}
  	\dfgCheckIfZeroShowCategory{#1}{globalfunds}
  	\dfgCheckIfZeroShowCategory{#1}{instrumentation}

  	\begin{tblr}[
  			theme=main,
  			long,
  			expand=
  			\l__tmp_body_staff_tl
  			\l__tmp_body_costs_tl
  			\l__tmp_body_fellowships_tl
  			\l__tmp_body_globalfunds_tl
  			\l__tmp_body_instrumentation_tl,
			remark{Note}={Figures~ in~ EUR.},
  		]{
  			colsep=3pt,
			colspec = {
					*{1}{X[3.1,l,t]}
					*{5}{
						@{}X[0.75,c,si={table-format=1}]
						@{}X[1.2,c,si={table-format=7}]
					}
  					% *{1}{X[2,t]}
  					% *{10}{@{}X[c, si={table-format=4}]}
  				},
  			rows = {bg=white},
			column{2-Z}={guard},
        row{1}= {valign=m,bg=tableHeadingsBG},
  			row{1,2}= {guard},
  		}
		Funding~for
		 & \SetCell[c=2]{c} \dfgFundingYear{1}
  		 &
		 & \SetCell[c=2]{c} \dfgFundingYear{2}
  		 &
		 & \SetCell[c=2]{c} \dfgFundingYear{3}
  		 &
		 & \SetCell[c=2]{c} \dfgFundingYear{4}
  		 &
		 & \SetCell[c=2]{c} \dfgFundingYear{5}
  		 &                                           \\

  		\l__tmp_body_staff_tl
  		\l__tmp_body_costs_tl
  		\l__tmp_body_fellowships_tl
  		\l__tmp_body_globalfunds_tl
  		\l__tmp_body_instrumentation_tl

  		\SetHline{-}{tableOuterLines,.75pt}
  		\SetCell{font=\bfseries\footnotesize}
  		Total
  		\printMarginalia{%
  			\getTotalSumRequestedFunds{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  		}
  		 &
  		 & \getTotalSumRequestedFunds{#1}{sum-year1}
  		 &
  		 & \getTotalSumRequestedFunds{#1}{sum-year2}
  		 &
  		 & \getTotalSumRequestedFunds{#1}{sum-year3}
  		 &
  		 & \getTotalSumRequestedFunds{#1}{sum-year4}
  		 &
  		 & \getTotalSumRequestedFunds{#1}{sum-year5} \\
  	\end{tblr}
  }{
  	Database~ \texttt{#1}~ missing.
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
  \group_end:
}
%    \end{macrocode}

% \paragraph{\refCom{RequestedFundingStaffTable}}
% The DFG staff roster uses one database and one project-filtered traversal.
% Rows are first dispatched, in declaration order, to four sequences.  The
% sequences are then rendered in the official order (existing research,
% existing non-research, requested research, requested non-research), which
% also assigns the continuous sequence numbers used by the descriptions.
% When both staff types occur within a funding-status block, a horizontal rule
% separates the research and non-research groups without repeating their
% row-spanning labels.  Category values and the emphasized job-description
% headings are left aligned for easier scanning.
% Person, institution, and affiliation references are resolved during this
% assembly phase,
% before tabularray measures any cells.  Thus neither measuring passes nor page
% breaks repeat Datatool queries.
% The roster uses the shared |presep|, like the other long tables.
% No heading-specific spacing override is needed.
%
% \begin{docCommand}{RequestedFundingStaffTable}{\marg{project}}
%   Print the official DFG requested-funding staff roster, the institution and
%   parent-affiliation legend, and both applicable job-description blocks for
%   \meta{project}.  The data source is always |RequestedFundingStaff|.  For
%   an ending project (|project-status=E|), rows declared with
%   |funding-status=requested| are automatically labelled as staff funded with
%   approved grant money; this matches the terminology of the ending-project
%   report while retaining the same two-value data model.
% \end{docCommand}
%    \begin{macrocode}
\seq_new:N \l_@@_rfs_existing_research_seq
\seq_new:N \l_@@_rfs_existing_nonresearch_seq
\seq_new:N \l_@@_rfs_requested_research_seq
\seq_new:N \l_@@_rfs_requested_nonresearch_seq
\seq_new:N \l_@@_rfs_institution_seq
% Cache all resolved affiliations for the final abbreviation list.
\seq_new:N \l_@@_rfs_affiliation_seq
\prop_new:N \l_@@_rfs_duplicate_prop
\prop_new:N \l_@@_rfs_institution_name_prop
\prop_new:N \l_@@_rfs_institution_abbreviation_prop
\prop_new:N \l_@@_rfs_institution_affiliation_id_prop
\prop_new:N \l_@@_rfs_affiliation_abbreviation_prop
\prop_new:N \l_@@_rfs_affiliation_name_prop
\tl_new:N \l_@@_rfs_table_body_tl
\tl_new:N \l_@@_rfs_existing_descriptions_tl
\tl_new:N \l_@@_rfs_requested_descriptions_tl
\tl_new:N \l_@@_rfs_project_tl
\tl_new:N \l_@@_rfs_project_status_tl
\tl_new:N \l_@@_rfs_existing_group_label_tl
\tl_new:N \l_@@_rfs_requested_group_label_tl
\tl_new:N \l_@@_rfs_existing_description_heading_tl
\tl_new:N \l_@@_rfs_requested_description_heading_tl
\tl_new:N \l_@@_rfs_ref_person_tl
\tl_new:N \l_@@_rfs_firstname_tl
\tl_new:N \l_@@_rfs_lastname_tl
\tl_new:N \l_@@_rfs_degree_tl
\tl_new:N \l_@@_rfs_position_tl
\tl_new:N \l_@@_rfs_field_tl
\tl_new:N \l_@@_rfs_ref_institution_tl
\tl_new:N \l_@@_rfs_ref_affiliation_tl
\tl_new:N \l_@@_rfs_department_tl
\tl_new:N \l_@@_rfs_funding_status_tl
\tl_new:N \l_@@_rfs_staff_type_tl
\tl_new:N \l_@@_rfs_commitment_tl
\tl_new:N \l_@@_rfs_category_tl
\tl_new:N \l_@@_rfs_funding_source_tl
\tl_new:N \l_@@_rfs_description_tl
\tl_new:N \l_@@_rfs_name_cell_tl
\tl_new:N \l_@@_rfs_plain_name_tl
\tl_new:N \l_@@_rfs_description_name_tl
\tl_new:N \l_@@_rfs_field_cell_tl
\tl_new:N \l_@@_rfs_department_cell_tl
\tl_new:N \l_@@_rfs_commitment_cell_tl
\tl_new:N \l_@@_rfs_category_cell_tl
\tl_new:N \l_@@_rfs_funding_source_cell_tl
\tl_new:N \l_@@_rfs_group_cell_tl
\tl_new:N \l_@@_rfs_institution_name_tl
\tl_new:N \l_@@_rfs_institution_abbreviation_tl
\tl_new:N \l_@@_rfs_institution_affiliation_tl
\tl_new:N \l_@@_rfs_affiliation_name_tl
\tl_new:N \l_@@_rfs_affiliation_abbreviation_tl
\int_new:N \l_@@_rfs_display_number_int
\int_new:N \l_@@_rfs_record_count_int
\bool_new:N \l_@@_rfs_person_resolved_bool
\bool_new:N \l_@@_rfs_name_incomplete_bool

\keys_define:nn { dfg / requested-funding-staff-row }
{
  ref-person-id .tl_set:N = \l_@@_rfs_ref_person_tl,
  firstname .tl_set:N = \l_@@_rfs_firstname_tl,
  lastname .tl_set:N = \l_@@_rfs_lastname_tl,
  academic-degree .tl_set:N = \l_@@_rfs_degree_tl,
  positionText .tl_set:N = \l_@@_rfs_position_tl,
  position .tl_set:N = \l_@@_rfs_position_tl,
  field-of-research .tl_set:N = \l_@@_rfs_field_tl,
  ref-institution-id .tl_set:N = \l_@@_rfs_ref_institution_tl,
  ref-affiliation-id .tl_set:N = \l_@@_rfs_ref_affiliation_tl,
  department .tl_set:N = \l_@@_rfs_department_tl,
  funding-status .tl_set:N = \l_@@_rfs_funding_status_tl,
  staff-type .tl_set:N = \l_@@_rfs_staff_type_tl,
  commitment .tl_set:N = \l_@@_rfs_commitment_tl,
  category .tl_set:N = \l_@@_rfs_category_tl,
  funding-source .tl_set:N = \l_@@_rfs_funding_source_tl,
  description .tl_set:N = \l_@@_rfs_description_tl,
  unknown .code:n = { }
}

\cs_new:Npn \@@_rfs_missing_text:n #1
{
  \bool_if:NTF \l_@@_class_fastcompile_bool
    { \@@_rfs_error_text:n {#1} }
    { \textcolor{tableNoValue!55!black}{\emph{not~provided}} }
}

\cs_new:Npn \@@_rfs_error_text:n #1
{ \textcolor{error}{\texttt{<#1>}} }

%    \end{macrocode}
% \changes{0.3.2}{2026-10-21}{Identify the funding status in staff missing-field warnings and explain why existing staff need commitment while requested staff do not.}
%    \begin{macrocode}
\cs_new_protected:Npn \@@_rfs_warn_missing:n #1
{
  \str_if_eq:nnTF {#1} { commitment }
  {
    \msg_warning:nnee { dfg } { existing-staff-missing-commitment }
      { \l_@@_rfs_project_tl }
      { \int_use:N \l_@@_rfs_display_number_int }
  }
  {
    \msg_warning:nneeee { dfg } { requested-staff-missing-field }
      { \l_@@_rfs_project_tl }
      { \int_use:N \l_@@_rfs_display_number_int }
      { \l_@@_rfs_funding_status_tl } {#1}
  }
}

\cs_new_protected:Npn \@@_rfs_row_clear:
{
  \tl_clear:N \l_@@_rfs_ref_person_tl
  \tl_clear:N \l_@@_rfs_firstname_tl
  \tl_clear:N \l_@@_rfs_lastname_tl
  \tl_clear:N \l_@@_rfs_degree_tl
  \tl_clear:N \l_@@_rfs_position_tl
  \tl_clear:N \l_@@_rfs_field_tl
  \tl_clear:N \l_@@_rfs_ref_institution_tl
  \tl_clear:N \l_@@_rfs_ref_affiliation_tl
  \tl_clear:N \l_@@_rfs_department_tl
  \tl_clear:N \l_@@_rfs_funding_status_tl
  \tl_clear:N \l_@@_rfs_staff_type_tl
  \tl_clear:N \l_@@_rfs_commitment_tl
  \tl_clear:N \l_@@_rfs_category_tl
  \tl_clear:N \l_@@_rfs_funding_source_tl
  \tl_clear:N \l_@@_rfs_description_tl
}

\cs_new_protected:Npn \@@_rfs_store:N #1
{
  \seq_put_right:Ne #1
  {
    ref-person-id = { \exp_not:V \pRFSRefPerson },
    firstname = { \exp_not:V \pRFSFirstname },
    lastname = { \exp_not:V \pRFSLastname },
    academic-degree = { \exp_not:V \pRFSDegree },
    positionText = { \exp_not:V \pRFSPosition },
    field-of-research = { \exp_not:V \pRFSField },
    ref-institution-id = { \exp_not:V \pRFSRefInstitution },
    ref-affiliation-id = { \exp_not:V \pRFSRefAffiliation },
    department = { \exp_not:V \pRFSDepartment },
    funding-status = { \exp_not:V \pRFSFundingStatus },
    staff-type = { \exp_not:V \pRFSStaffType },
    commitment = { \exp_not:V \pRFSCommitment },
    category = { \exp_not:V \pRFSCategory },
    funding-source = { \exp_not:V \pRFSFundingSource },
    description = { \exp_not:V \pRFSDescription }
  }
}

\cs_new_protected:Npn \@@_rfs_collect_current:
{
  % Preserve the null marker for an omitted position until person lookup.
  \clist_map_inline:nn
  {
    \pRFSRefPerson, \pRFSFirstname, \pRFSLastname, \pRFSDegree,
    \pRFSField, \pRFSRefInstitution,
    \pRFSRefAffiliation, \pRFSDepartment, \pRFSCommitment,
    \pRFSCategory, \pRFSFundingSource, \pRFSDescription
  }
  { \DTLifnullorempty{##1}{\cs_set:Npn ##1 {}}{} }
  \tl_if_blank:VTF \pRFSRefPerson
  {
    \str_if_eq:VnTF \pRFSLastname { TBA }
    {
      \tl_set:Ne \l_tmpa_tl
      {
        \exp_not:V \pRFSProject / \exp_not:V \pRFSFundingStatus /
        \exp_not:V \pRFSStaffType / vacancy /
        \exp_not:V \pRFSCategory / \exp_not:V \pRFSPosition /
        \exp_not:V \pRFSField / \exp_not:V \pRFSRefInstitution /
        \exp_not:V \pRFSDepartment
      }
    }
    {
      \tl_set:Ne \l_tmpa_tl
      {
        \exp_not:V \pRFSProject / \exp_not:V \pRFSFundingStatus /
        \exp_not:V \pRFSStaffType / name /
        \exp_not:V \pRFSLastname / \exp_not:V \pRFSFirstname
      }
    }
  }
  {
    \tl_set:Ne \l_tmpa_tl
    {
      \exp_not:V \pRFSProject / \exp_not:V \pRFSFundingStatus /
      \exp_not:V \pRFSStaffType / person / \exp_not:V \pRFSRefPerson
    }
  }
  \prop_get:NVNTF \l_@@_rfs_duplicate_prop \l_tmpa_tl \l_tmpb_tl
  { \msg_warning:nne { dfg } { requested-staff-duplicate } { \l_tmpa_tl } }
  { \prop_put:NVn \l_@@_rfs_duplicate_prop \l_tmpa_tl { 1 } }
  \tl_set:Ne \l_tmpa_tl
    { \pRFSFundingStatus / \pRFSStaffType }
  \str_case:VnF \l_tmpa_tl
  {
    { existing/research }
      { \@@_rfs_store:N \l_@@_rfs_existing_research_seq }
    { existing/nonResearch }
      { \@@_rfs_store:N \l_@@_rfs_existing_nonresearch_seq }
    { requested/research }
      { \@@_rfs_store:N \l_@@_rfs_requested_research_seq }
    { requested/nonResearch }
      { \@@_rfs_store:N \l_@@_rfs_requested_nonresearch_seq }
  }
  { }
}

\cs_new_protected:Npn \@@_rfs_use_fallback:NN #1#2
{
  \tl_if_blank:VT #1
  { \DTLifnullorempty{#2}{ }{ \tl_set:NV #1 #2 } }
}

\cs_new_protected:Npn \@@_rfs_resolve_person:
{
  \bool_set_false:N \l_@@_rfs_person_resolved_bool
  \tl_if_blank:VF \l_@@_rfs_ref_person_tl
  {
    \DTLifdbexists{person}
    {
      \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{lastname}{person}{id}
        {\l_@@_rfs_ref_person_tl}
      \DTLifnullorempty{\l_tmpa_tl}
      {
        \msg_warning:nnee { dfg } { requested-staff-unresolved-person }
          { \l_@@_rfs_project_tl } { \l_@@_rfs_ref_person_tl }
      }
      {
        \bool_set_true:N \l_@@_rfs_person_resolved_bool
        \@@_rfs_use_fallback:NN \l_@@_rfs_lastname_tl \l_tmpa_tl
        \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{firstname}{person}{id}
          {\l_@@_rfs_ref_person_tl}
        \@@_rfs_use_fallback:NN \l_@@_rfs_firstname_tl \l_tmpa_tl
        \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{academicdegree}{person}{id}
          {\l_@@_rfs_ref_person_tl}
        \@@_rfs_use_fallback:NN \l_@@_rfs_degree_tl \l_tmpa_tl
        % Only a missing database value inherits; an explicit empty value wins.
        \DTLifnull{\l_@@_rfs_position_tl}
        {
          \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{positionText}{person}{id}
            {\l_@@_rfs_ref_person_tl}
          % An empty inherited position has no custom text to override the
          % category; an explicitly empty roster value never enters here.
          \DTLifnullorempty{\l_tmpa_tl}
            { \tl_set_eq:NN \l_@@_rfs_position_tl \DTLstringnull }
            { \tl_set:NV \l_@@_rfs_position_tl \l_tmpa_tl }
        }
        { }
        \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{position}{person}{id}
          {\l_@@_rfs_ref_person_tl}
        \@@_rfs_use_fallback:NN \l_@@_rfs_category_tl \l_tmpa_tl
        \bool_lazy_all:nT
        {
          { \tl_if_blank_p:V \l_@@_rfs_department_tl }
          { \tl_if_blank_p:V \l_@@_rfs_ref_institution_tl }
          { \tl_if_blank_p:V \l_@@_rfs_ref_affiliation_tl }
        }
        {
          \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{ref-institution-id}{person}{id}
            {\l_@@_rfs_ref_person_tl}
          \@@_rfs_use_fallback:NN \l_@@_rfs_ref_institution_tl \l_tmpa_tl
          \tl_if_blank:VT \l_@@_rfs_ref_institution_tl
          {
            \@@_getvalueforkey:Nnnnn{\l_tmpa_tl}{ref-affiliation-id}{person}{id}
              {\l_@@_rfs_ref_person_tl}
            \@@_rfs_use_fallback:NN \l_@@_rfs_ref_affiliation_tl \l_tmpa_tl
          }
        }
      }
    }
    {
      \msg_warning:nnee { dfg } { requested-staff-unresolved-person }
        { \l_@@_rfs_project_tl } { \l_@@_rfs_ref_person_tl }
    }
  }
  \DTLifnull{\l_@@_rfs_position_tl}
  {
    % Resolve only the omitted position at rendering time. Custom text and
    % explicit empty overrides keep their original meaning in either mode.
    \@@_category_name_get:nNTF {\l_@@_rfs_category_tl}
      \l_@@_rfs_position_tl
      { }
      { \tl_clear:N \l_@@_rfs_position_tl }
  }
  { }
}

\cs_new_protected:Npn \@@_rfs_register_affiliation:n #1
{
  \tl_set:Ne \l_tmpa_tl {#1}
  \tl_clear:N \l_@@_rfs_affiliation_name_tl
  \tl_clear:N \l_@@_rfs_affiliation_abbreviation_tl
  \DTLifdbexists{affiliation}
  {
    \@@_getvalueforkey:Nnnnn{\l_@@_rfs_affiliation_name_tl}
      {name}{affiliation}{id}{\l_tmpa_tl}
    \DTLifnullorempty{\l_@@_rfs_affiliation_name_tl}
    {
      \msg_warning:nnee { dfg } { requested-staff-unresolved-affiliation }
        { \l_@@_rfs_project_tl } { \l_tmpa_tl }
      \tl_clear:N \l_@@_rfs_affiliation_name_tl
    }
    {
      \@@_getvalueforkey:Nnnnn{\l_@@_rfs_affiliation_abbreviation_tl}
        {abbreviation}{affiliation}{id}{\l_tmpa_tl}
      \DTLifnullorempty{\l_@@_rfs_affiliation_abbreviation_tl}
      {
        \msg_warning:nne { dfg } { requested-staff-missing-abbreviation }
          { \l_tmpa_tl }
        \tl_set:NV \l_@@_rfs_affiliation_abbreviation_tl
          \l_@@_rfs_affiliation_name_tl
      }
      { }
      \seq_if_in:NVF \l_@@_rfs_affiliation_seq \l_tmpa_tl
      {
        \seq_put_right:NV \l_@@_rfs_affiliation_seq \l_tmpa_tl
        \prop_put:NVV \l_@@_rfs_affiliation_abbreviation_prop
          \l_tmpa_tl \l_@@_rfs_affiliation_abbreviation_tl
        \prop_put:NVV \l_@@_rfs_affiliation_name_prop
          \l_tmpa_tl \l_@@_rfs_affiliation_name_tl
      }
    }
  }
  {
    \msg_warning:nnee { dfg } { requested-staff-unresolved-affiliation }
      { \l_@@_rfs_project_tl } { \l_tmpa_tl }
  }
}

\cs_new_protected:Npn \@@_rfs_resolve_organisation:
{
  \tl_if_blank:VT \l_@@_rfs_department_tl
  {
    \tl_if_blank:VTF \l_@@_rfs_ref_institution_tl
    {
      % Compatibility fallback for roster declarations written before the
      % institution-level key was introduced.
      \tl_if_blank:VTF \l_@@_rfs_ref_affiliation_tl
      {
        \@@_rfs_warn_missing:n { department~or~ref-institution-id }
        \tl_set:Nn \l_@@_rfs_department_tl
          { \SetCell{bg=tableNoValue}\@@_rfs_missing_text:n {department} }
      }
      {
        \@@_rfs_register_affiliation:n { \l_@@_rfs_ref_affiliation_tl }
        \tl_if_blank:VTF \l_@@_rfs_affiliation_name_tl
        {
          \tl_set:Ne \l_@@_rfs_department_tl
          {
            \exp_not:N \SetCell { bg=tableNoValue }
            \exp_not:N \@@_rfs_error_text:n
              { \exp_not:V \l_@@_rfs_ref_affiliation_tl }
          }
        }
        {
          \tl_set:NV \l_@@_rfs_department_tl
            \l_@@_rfs_affiliation_abbreviation_tl
        }
      }
    }
    {
      \tl_clear:N \l_@@_rfs_department_tl
      \DTLifdbexists{institution}
      {
        \clist_set:NV \l_tmpa_clist \l_@@_rfs_ref_institution_tl
        \bool_set_true:N \l_tmpa_bool
        \clist_map_inline:Nn \l_tmpa_clist
        {
          \bool_if:NTF \l_tmpa_bool
            { \bool_set_false:N \l_tmpa_bool }
            { \tl_put_right:Nn \l_@@_rfs_department_tl {,~} }
          \@@_getvalueforkey:Nnnnn{\l_@@_rfs_institution_affiliation_tl}
            {ref-affiliation-id}{institution}{id}{##1}
          \DTLifnullorempty{\l_@@_rfs_institution_affiliation_tl}
          {
            \msg_warning:nnee { dfg } { requested-staff-unresolved-institution }
              { \l_@@_rfs_project_tl } {##1}
            \tl_put_right:Ne \l_@@_rfs_department_tl
              { \exp_not:N \@@_rfs_error_text:n { \exp_not:n {##1} } }
          }
          {
            \@@_getvalueforkey:Nnnnn{\l_@@_rfs_institution_name_tl}
              {name}{institution}{id}{##1}
            \@@_institution_abbreviation_or_name:nN
              {##1} \l_@@_rfs_institution_abbreviation_tl
            \@@_rfs_register_affiliation:n
              { \l_@@_rfs_institution_affiliation_tl }
            \DTLifnullorempty{\l_@@_rfs_institution_name_tl}
            {
              \tl_set:NV \l_@@_rfs_institution_name_tl
                \l_@@_rfs_affiliation_name_tl
            }
            { }
            \DTLifnullorempty{\l_@@_rfs_institution_abbreviation_tl}
            {
              \tl_set:NV \l_@@_rfs_institution_abbreviation_tl
                \l_@@_rfs_affiliation_abbreviation_tl
            }
            { }
            \tl_put_right:NV \l_@@_rfs_department_tl
              \l_@@_rfs_institution_abbreviation_tl
            \tl_set:Nn \l_tmpa_tl {##1}
            \seq_if_in:NVF \l_@@_rfs_institution_seq \l_tmpa_tl
            {
              \seq_put_right:NV \l_@@_rfs_institution_seq \l_tmpa_tl
              \prop_put:NVV \l_@@_rfs_institution_name_prop
                \l_tmpa_tl \l_@@_rfs_institution_name_tl
              \prop_put:NVV \l_@@_rfs_institution_abbreviation_prop
                \l_tmpa_tl \l_@@_rfs_institution_abbreviation_tl
              \prop_put:NVV
                \l_@@_rfs_institution_affiliation_id_prop
                \l_tmpa_tl \l_@@_rfs_institution_affiliation_tl
            }
          }
        }
      }
      {
        \msg_warning:nnee { dfg } { requested-staff-unresolved-institution }
          { \l_@@_rfs_project_tl } { \l_@@_rfs_ref_institution_tl }
        \tl_set:Ne \l_@@_rfs_department_tl
        {
          \exp_not:N \SetCell { bg=tableNoValue }
          \exp_not:N \@@_rfs_error_text:n
            { \exp_not:V \l_@@_rfs_ref_institution_tl }
        }
      }
    }
  }
}

\cs_new_protected:Npn \@@_rfs_make_cell:NnN #1#2#3
{
  \tl_if_blank:VTF #1
  {
    \@@_rfs_warn_missing:n {#2}
    \tl_set:Nn #3 { \SetCell{bg=tableNoValue}\@@_rfs_missing_text:n {#2} }
  }
  { \tl_set:NV #3 #1 }
}

\cs_new_protected:Npn \@@_rfs_make_field_cell:
{
  \bool_lazy_all:nTF
  {
    { \str_if_eq_p:Vn \l_@@_rfs_staff_type_tl { nonResearch } }
    { \tl_if_blank_p:V \l_@@_rfs_field_tl }
  }
  { \tl_set:Nn \l_@@_rfs_field_cell_tl { \SetCell{bg=tableNoValue} } }
  {
    \@@_rfs_make_cell:NnN \l_@@_rfs_field_tl
      { field-of-research } \l_@@_rfs_field_cell_tl
  }
}

\cs_new_protected:Npn \@@_rfs_make_name_cell:
{
  \bool_set_false:N \l_@@_rfs_name_incomplete_bool
  \str_if_eq:VnTF \l_@@_rfs_lastname_tl { TBA }
  {
    \tl_set:Nn \l_@@_rfs_plain_name_tl { TBA }
    \tl_set:Nn \l_@@_rfs_description_name_tl { TBA }
    \tl_set:Nn \l_tmpa_tl { TBA }
  }
  {
    \tl_if_blank:VT \l_@@_rfs_lastname_tl
    {
      \@@_rfs_warn_missing:n { lastname~or~resolvable~ref-person-id }
      \tl_set:Nn \l_@@_rfs_lastname_tl
      {
        \bool_if:NTF \l_@@_class_fastcompile_bool
          { \@@_rfs_error_text:n {lastname} }
          { \@@_rfs_error_text:n {name} }
      }
      \bool_set_true:N \l_@@_rfs_name_incomplete_bool
    }
    \tl_if_blank:VT \l_@@_rfs_firstname_tl
    {
      \@@_rfs_warn_missing:n { firstname }
      \tl_set:Nn \l_@@_rfs_firstname_tl { \@@_rfs_missing_text:n {firstname} }
      \bool_set_true:N \l_@@_rfs_name_incomplete_bool
    }
    \tl_set:Ne \l_@@_rfs_plain_name_tl
      {
        \exp_not:V \l_@@_rfs_lastname_tl,\exp_not:N \space
        \exp_not:V \l_@@_rfs_firstname_tl
      }
    \tl_set:Ne \l_@@_rfs_description_name_tl
    {
      \exp_not:V \l_@@_rfs_firstname_tl \exp_not:N \space
      \exp_not:V \l_@@_rfs_lastname_tl
    }
    \tl_set:NV \l_tmpa_tl \l_@@_rfs_plain_name_tl
    \tl_if_blank:VF \l_@@_rfs_degree_tl
    {
      \tl_put_right:Ne \l_tmpa_tl
        { ,\exp_not:N \space \exp_not:V \l_@@_rfs_degree_tl }
    }
    \bool_if:NT \l_@@_rfs_person_resolved_bool
    {
      \str_if_eq:VnT \l_@@_rfs_funding_status_tl { existing }
      {
        \tl_set:Ne \l_tmpa_tl
        {
          \exp_not:N \textbf { \exp_not:V \l_@@_rfs_lastname_tl },
          \exp_not:N \space \exp_not:V \l_@@_rfs_firstname_tl
        }
        \tl_if_blank:VF \l_@@_rfs_degree_tl
        {
          \tl_put_right:Ne \l_tmpa_tl
            { ,\exp_not:N \space \exp_not:V \l_@@_rfs_degree_tl }
        }
      }
    }
  }
  \tl_if_blank:VF \l_@@_rfs_position_tl
  {
    \tl_put_right:Ne \l_tmpa_tl
    {
      \exp_not:N \newline
      (\exp_not:V \l_@@_rfs_position_tl)
    }
  }
  \bool_if:NF \l_@@_rfs_person_resolved_bool
  {
    \tl_if_blank:VF \l_@@_rfs_ref_person_tl
    {
      \bool_set_true:N \l_@@_rfs_name_incomplete_bool
      \tl_put_right:Ne \l_tmpa_tl
      {
        \exp_not:N \space
        \exp_not:N \@@_rfs_error_text:n
          { \exp_not:V \l_@@_rfs_ref_person_tl }
      }
    }
  }
  \tl_clear:N \l_@@_rfs_name_cell_tl
  \bool_if:NT \l_@@_rfs_name_incomplete_bool
  { \tl_put_right:Nn \l_@@_rfs_name_cell_tl { \SetCell{bg=tableNoValue} } }
  \bool_if:NTF \l_@@_rfs_person_resolved_bool
  {
    \tl_put_right:Ne \l_@@_rfs_name_cell_tl
    {
      \exp_not:N \hyperlink { pi:\exp_not:V \l_@@_rfs_ref_person_tl }
      {
        \exp_not:N \textcolor { referencePI }
        {
          \exp_not:N \dfgShowCalculatedTag{RequestedFundingStaffTable}
            {RequestedFundingStaff,person}
            {\exp_not:V \l_tmpa_tl}
        }
      }
    }
  }
  {
    \tl_put_right:Ne \l_@@_rfs_name_cell_tl
    {
      \exp_not:N \dfgShowCalculatedTag{RequestedFundingStaffTable}
        {RequestedFundingStaff,person}
        {\exp_not:V \l_tmpa_tl}
    }
  }
}

\cs_new_protected:Npn \@@_rfs_render_row:nnnN #1#2#3#4
{
  \int_incr:N \l_@@_rfs_display_number_int
  \@@_rfs_resolve_person:
  \@@_rfs_resolve_organisation:
  \@@_rfs_make_name_cell:
  \@@_rfs_make_field_cell:
  \tl_if_blank:VF \l_@@_rfs_field_tl
  {
    \tl_set:Ne \l_@@_rfs_field_cell_tl
    {
      \exp_not:N \dfgShowTag
        {\exp_not:V \l_@@_rfs_project_tl/
         \int_use:N \l_@@_rfs_display_number_int}
        {field-of-research}{\exp_not:V \l_@@_rfs_field_cell_tl}
        [RequestedFundingStaff]
    }
  }
  \tl_set:NV \l_@@_rfs_department_cell_tl \l_@@_rfs_department_tl
  \tl_if_in:VnF \l_@@_rfs_department_cell_tl { \SetCell }
  {
    \tl_set:Ne \l_@@_rfs_department_cell_tl
    {
      \exp_not:N \dfgShowCalculatedTag{RequestedFundingStaffTable}
        {RequestedFundingStaff,person,institution,affiliation}
        {\exp_not:V \l_@@_rfs_department_cell_tl}
    }
  }
  \str_if_eq:VnTF \l_@@_rfs_funding_status_tl { requested }
  {
    \tl_set:Nn \l_@@_rfs_commitment_cell_tl
      { \SetCell{bg=tableNoValue} }
    \tl_set:Nn \l_@@_rfs_funding_source_cell_tl
      { \SetCell{bg=tableNoValue} }
  }
  {
    \@@_rfs_make_cell:NnN \l_@@_rfs_commitment_tl
      { commitment } \l_@@_rfs_commitment_cell_tl
    \@@_rfs_make_cell:NnN \l_@@_rfs_funding_source_tl
      { funding-source } \l_@@_rfs_funding_source_cell_tl
    \tl_if_blank:VF \l_@@_rfs_commitment_tl
    {
      \tl_set:Ne \l_@@_rfs_commitment_cell_tl
      {
        \exp_not:N \dfgShowTag
          {\exp_not:V \l_@@_rfs_project_tl/
           \int_use:N \l_@@_rfs_display_number_int}
          {commitment}{\exp_not:V \l_@@_rfs_commitment_cell_tl}
          [RequestedFundingStaff]
      }
    }
    \tl_if_blank:VF \l_@@_rfs_funding_source_tl
    {
      \tl_set:Ne \l_@@_rfs_funding_source_cell_tl
      {
        \exp_not:N \dfgShowTag
          {\exp_not:V \l_@@_rfs_project_tl/
           \int_use:N \l_@@_rfs_display_number_int}
          {funding-source}{\exp_not:V \l_@@_rfs_funding_source_cell_tl}
          [RequestedFundingStaff]
      }
    }
  }
  \str_if_eq:VnTF \l_@@_rfs_funding_status_tl { existing }
  {
    \tl_set:Nn \l_@@_rfs_category_cell_tl
      { \SetCell{bg=tableNoValue} }
  }
  {
    \tl_if_blank:VTF \l_@@_rfs_category_tl
    {
      \@@_rfs_warn_missing:n { category }
      \tl_set:Nn \l_@@_rfs_category_cell_tl
        { \SetCell{bg=tableNoValue}\@@_rfs_missing_text:n {category} }
    }
    {
      \@@_category_name_get:nNTF
        {\l_@@_rfs_category_tl} \l_@@_rfs_category_cell_tl
      { }
      {
        \tl_set:Ne \l_@@_rfs_category_cell_tl
          { \exp_not:N \@@_rfs_error_text:n { \exp_not:V \l_@@_rfs_category_tl } }
      }
    }
  }
  \tl_if_in:VnF \l_@@_rfs_category_cell_tl { \SetCell }
  {
    \tl_set:Ne \l_@@_rfs_category_cell_tl
    {
      \exp_not:N \dfgShowCalculatedTag{RequestedFundingStaffTable}
        {RequestedFundingStaff,person}
        {\exp_not:V \l_@@_rfs_category_cell_tl}
    }
  }
  \int_compare:nNnTF {#1} = {1}
  {
    \tl_set:Ne \l_@@_rfs_group_cell_tl
    {
      \exp_not:N \SetCell [ r=#2 ] { l }
      { \exp_not:n {#3} } &
    }
  }
  { \tl_set:Nn \l_@@_rfs_group_cell_tl { & } }
  \tl_put_right:Ne \l_@@_rfs_table_body_tl
  {
    \exp_not:V \l_@@_rfs_group_cell_tl
    \int_use:N \l_@@_rfs_display_number_int .
    & \exp_not:V \l_@@_rfs_name_cell_tl
    & \exp_not:V \l_@@_rfs_field_cell_tl
    & \exp_not:V \l_@@_rfs_department_cell_tl
    & \exp_not:V \l_@@_rfs_commitment_cell_tl
    & \exp_not:V \l_@@_rfs_category_cell_tl
    & \exp_not:V \l_@@_rfs_funding_source_cell_tl
    \\
  }
  \tl_if_blank:VT \l_@@_rfs_description_tl
  {
    \@@_rfs_warn_missing:n { description }
    \tl_set:Nn \l_@@_rfs_description_tl
      { \textcolor{error}{Description~not~provided.} }
  }
  \tl_put_right:Ne #4
  {
    \exp_not:N \item
      [\exp_not:N \textbf
        { \int_use:N \l_@@_rfs_display_number_int. }]
    \exp_not:N \textbf
      { \exp_not:N \dfgShowCalculatedTag{RequestedFundingStaffTable}
          {RequestedFundingStaff,person}
          {\exp_not:V \l_@@_rfs_description_name_tl} }
    \space
    \exp_not:N \dfgShowTag
      {\exp_not:V \l_@@_rfs_project_tl/
       \int_use:N \l_@@_rfs_display_number_int}
      {description}{\exp_not:V \l_@@_rfs_description_tl}
      [RequestedFundingStaff]
  }
}

\cs_new_protected:Npn \@@_rfs_render_group:NnN #1#2#3
{
  \seq_map_indexed_inline:Nn #1
  {
    \@@_rfs_row_clear:
    \keys_set:nn { dfg / requested-funding-staff-row } {##2}
    \@@_rfs_render_row:nnnN {##1} { \seq_count:N #1 } {#2} #3
  }
}

\cs_new_protected:Npn \@@_rfs_render_status:NNnN #1#2#3#4
{
  \int_compare:nNnT { \seq_count:N #1 + \seq_count:N #2 } > {0}
  {
    \tl_put_right:Nn \l_@@_rfs_table_body_tl
    {
      \SetRow{bg=tableHeadingsBGalt,font=\footnotesize\bfseries}
      \SetCell[c=8]{l} #3 & & & & & & & \\*
    }
    \@@_rfs_render_group:NnN #1 { Research~staff } #4
    \seq_if_empty:NF #1
    {
      \seq_if_empty:NF #2
      {
        \tl_put_right:Nn \l_@@_rfs_table_body_tl
          { \SetHline{-}{tableOuterLines,0.5pt} }
      }
    }
    \@@_rfs_render_group:NnN #2 { Non-research~staff } #4
  }
}

\cs_new_protected:Npn \@@_rfs_print_legend:
{
  \bool_lazy_or:nnT
    { ! \seq_if_empty_p:N \l_@@_rfs_institution_seq }
    { ! \seq_if_empty_p:N \l_@@_rfs_affiliation_seq }
  {
    \@@_staff_abbreviation_note:n
    {
    \seq_map_indexed_inline:Nn \l_@@_rfs_institution_seq
    {
      \int_compare:nNnF {##1} = {1} {;\space}
      \prop_get:NnN \l_@@_rfs_institution_name_prop
        {##2} \l_@@_rfs_institution_name_tl
      \prop_get:NnN \l_@@_rfs_institution_abbreviation_prop
        {##2} \l_@@_rfs_institution_abbreviation_tl
      \prop_get:NnN \l_@@_rfs_institution_affiliation_id_prop
        {##2} \l_@@_rfs_institution_affiliation_tl
      \prop_get:NVNF \l_@@_rfs_affiliation_abbreviation_prop
        \l_@@_rfs_institution_affiliation_tl
        \l_@@_rfs_affiliation_abbreviation_tl
      {
        \tl_set:Ne \l_@@_rfs_affiliation_abbreviation_tl
        {
          \exp_not:N \@@_rfs_error_text:n
            { \exp_not:V \l_@@_rfs_institution_affiliation_tl }
        }
      }
      \dfgShowCalculatedTag{institutionLabel}{institution}
        {\l_@@_rfs_institution_abbreviation_tl}:~
      \dfgShowTag{##2}{name}{\l_@@_rfs_institution_name_tl}[institution]
      \space
      (\dfgShowCalculatedTag{affiliationLabel}{affiliation}
        {\l_@@_rfs_affiliation_abbreviation_tl})
    }
    \seq_if_empty:NF \l_@@_rfs_institution_seq
    {
      \seq_if_empty:NF \l_@@_rfs_affiliation_seq {;\space}
    }
    \seq_map_indexed_inline:Nn \l_@@_rfs_affiliation_seq
    {
      \int_compare:nNnF {##1} = {1} {;\space}
      \prop_get:NnN \l_@@_rfs_affiliation_abbreviation_prop
        {##2} \l_@@_rfs_affiliation_abbreviation_tl
      \prop_get:NnN \l_@@_rfs_affiliation_name_prop
        {##2} \l_@@_rfs_affiliation_name_tl
      \dfgShowCalculatedTag{affiliationLabel}{affiliation}
        {\l_@@_rfs_affiliation_abbreviation_tl}:~
      \dfgShowTag{##2}{name}{\l_@@_rfs_affiliation_name_tl}[affiliation]
    }
    }
  }
}

\cs_new_protected:Npn \@@_rfs_no_data:n #1
{
  \msg_warning:nnn { dfg } { requested-staff-no-data } {#1}
  \par\noindent
  \textcolor{tableNoValue!55!black}
    {No~staff~data~have~been~provided~for~this~project.}
  \par
}

\NewDocumentCommand{\RequestedFundingStaffTable}{m}
{
  \group_begin:
  \tl_set:Nn \l_@@_rfs_project_tl {#1}
  \tl_clear:N \l_@@_rfs_project_status_tl
  \DTLifdbexists{project}
  {
    \@@_getvalueforkey:Nnnnn{\l_@@_rfs_project_status_tl}
      {project-status}{project}{id}{#1}
  }
  { }
  \str_if_eq:VnTF \l_@@_rfs_project_status_tl { E }
  {
    \tl_set:Nn \l_@@_rfs_existing_group_label_tl {Existing~staff}
    \tl_set:Nn \l_@@_rfs_requested_group_label_tl
      {Staff~funded~with~approved~grant~money}
    \tl_set:Nn \l_@@_rfs_existing_description_heading_tl
      {Job~descriptions~of~staff~(supported~through~existing~funds):}
    \tl_set:Nn \l_@@_rfs_requested_description_heading_tl
      {Job~descriptions~of~staff~(funded~with~approved~grant~money):}
  }
  {
    \tl_set:Nn \l_@@_rfs_existing_group_label_tl {Existing~staff}
    \tl_set:Nn \l_@@_rfs_requested_group_label_tl {Requested~staff}
    \tl_set:Nn \l_@@_rfs_existing_description_heading_tl
      {Job~descriptions~of~staff~for~the~proposed~funding~period~
        (supported~through~existing~funds):}
    \tl_set:Nn \l_@@_rfs_requested_description_heading_tl
      {Job~descriptions~of~staff~for~the~proposed~funding~period~
        (requested~funds):}
  }
  \seq_clear:N \l_@@_rfs_existing_research_seq
  \seq_clear:N \l_@@_rfs_existing_nonresearch_seq
  \seq_clear:N \l_@@_rfs_requested_research_seq
  \seq_clear:N \l_@@_rfs_requested_nonresearch_seq
  \seq_clear:N \l_@@_rfs_institution_seq
  \seq_clear:N \l_@@_rfs_affiliation_seq
  \prop_clear:N \l_@@_rfs_duplicate_prop
  \prop_clear:N \l_@@_rfs_institution_name_prop
  \prop_clear:N \l_@@_rfs_institution_abbreviation_prop
  \prop_clear:N \l_@@_rfs_institution_affiliation_id_prop
  \prop_clear:N \l_@@_rfs_affiliation_abbreviation_prop
  \prop_clear:N \l_@@_rfs_affiliation_name_prop
  \tl_clear:N \l_@@_rfs_table_body_tl
  \tl_clear:N \l_@@_rfs_existing_descriptions_tl
  \tl_clear:N \l_@@_rfs_requested_descriptions_tl
  \DTLifdbexists{RequestedFundingStaff}
  {
    \DTLforeach[\DTLiseq{#1}{\pRFSProject}]
      {RequestedFundingStaff}
    {
      \pRFSProject=ref-project-id,
      \pRFSFundingStatus=funding-status,
      \pRFSStaffType=staff-type,
      \pRFSRefPerson=ref-person-id,
      \pRFSFirstname=firstname,
      \pRFSLastname=lastname,
      \pRFSDegree=academic-degree,
      \pRFSPosition=positionText,
      \pRFSField=field-of-research,
      \pRFSRefInstitution=ref-institution-id,
      \pRFSRefAffiliation=ref-affiliation-id,
      \pRFSDepartment=department,
      \pRFSCommitment=commitment,
      \pRFSCategory=category,
      \pRFSFundingSource=funding-source,
      \pRFSDescription=description
    }
    { \@@_rfs_collect_current: }
    \int_set:Nn \l_@@_rfs_record_count_int
    {
      \seq_count:N \l_@@_rfs_existing_research_seq
      + \seq_count:N \l_@@_rfs_existing_nonresearch_seq
      + \seq_count:N \l_@@_rfs_requested_research_seq
      + \seq_count:N \l_@@_rfs_requested_nonresearch_seq
    }
    \int_compare:nNnTF { \l_@@_rfs_record_count_int } = {0}
    { \@@_rfs_no_data:n {#1} }
    {
      \int_zero:N \l_@@_rfs_display_number_int
      \@@_rfs_render_status:NNnN
        \l_@@_rfs_existing_research_seq
        \l_@@_rfs_existing_nonresearch_seq
        {\tl_use:N \l_@@_rfs_existing_group_label_tl}
        \l_@@_rfs_existing_descriptions_tl
      \@@_rfs_render_status:NNnN
        \l_@@_rfs_requested_research_seq
        \l_@@_rfs_requested_nonresearch_seq
        {\tl_use:N \l_@@_rfs_requested_group_label_tl}
        \l_@@_rfs_requested_descriptions_tl
      \begin{tblr}[
        theme=requestedFundingStaff,
        long,
        postsep=0pt,
        expand=\l_@@_rfs_table_body_tl
      ]{
        colsep=2pt,
        width=\textwidth,
        hline{1,Z}={1pt,fg=tableOuterLines},
        hline{2}={1pt,fg=tableOuterLines},
        stretch=.8,
        rowsep=.500pt,
        colspec={X[1.1,l]
                 X[.42,c] % no
                 X[2.18,l] % Name
                 X[1.4,l] % field
                 X[1.5,c] % department
                 X[1.05,c] % proj com.
                 X[1.1,c] % category
                 X[.95,c] % funding
                 },
        column{1}={font=\footnotesize\bfseries,valign=m},
        column{2}={halign=c},
        rows={font=\footnotesize,valign=t},
        rowhead=1,
        row{1}={bg=tableHeadingsBG,fg=tableHeadingsFont,
          font=\scriptsize\bfseries,guard},
        cell{1}{1-8}={halign=c,valign=m}
      }
        & {No.}
        & {Name,~academic\\degree,~position}
        & {Field~of\\research}
        & {Departm.~of\\(non-)univers.\\institution}
        & {Project\\commitm.~(h/wk)}
        & Category
        & {Funding\\source} \\
        \l_@@_rfs_table_body_tl
      \end{tblr}
      \@@_rfs_print_legend:
      \tl_if_empty:NF \l_@@_rfs_existing_descriptions_tl
      {
        \par\medskip\noindent
        {\tl_use:N \l_@@_rfs_existing_description_heading_tl}\par\nobreak
        {\normalfont\normalsize\setlength{\parskip}{0pt}
          \begin{itemize}[
            label={},
            labelindent=0pt,
            labelwidth=1.5em,
            labelsep=.5em,
            leftmargin=2em,
            align=left,
            beginpenalty=10000]
            \tl_use:N \l_@@_rfs_existing_descriptions_tl
          \end{itemize}}
      }
      \tl_if_empty:NF \l_@@_rfs_requested_descriptions_tl
      {
        %\par\medskip\noindent
        {\tl_use:N \l_@@_rfs_requested_description_heading_tl}\par\nobreak
        {\normalfont\normalsize\setlength{\parskip}{0pt}
          \begin{itemize}[
            label={},
            labelindent=0pt,
            labelwidth=1.5em,
            labelsep=.5em,
            leftmargin=2em,
            align=left,
            beginpenalty=10000]
            \tl_use:N \l_@@_rfs_requested_descriptions_tl
          \end{itemize}}
      }
    }
  }
  { \@@_rfs_no_data:n {#1} }
  \group_end:
}
%    \end{macrocode}
%    \begin{macrocode}

\NewDocumentCommand{\getTotalSumRequestedFunds}{O{RequestedFunding}mm}{
  % #1: database
  % #2: project
  % #3: year
  \def\tmpLocalDB{#1}%
  \DTLifdbexists{\tmpLocalDB}{%
    \@@_funding_sum_set:Nnnnn \TotalSumRequestedFunds
      {#1}{#2}{__ALL__}{#3}
    \@@_show_calculated_number:nnN
      {getTotalSumRequestedFunds}{#1}
      \TotalSumRequestedFunds
  }{
  	\texttt{\color{error}XXX}
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}


\NewDocumentCommand{\getSumExistingFunds}{O{RequestedAndExistingFundingDirectCosts}mm}{
  % #1: database
  % #2: project
  % #3: year
  \def\tmpLocalDB{#1}%
  \DTLifdbexists{\tmpLocalDB}{
    \@@_funding_sum_set:Nnnnn \SumExistingFunds
      {#1}{#2}{__ALL__}{#3}

    \@@_show_calculated_number:nnN
      {getSumExistingFunds}{#1}
      \SumExistingFunds
  }{
  	\texttt{\color{error}XXX}
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}


\providecommand{\SumRequestedFunds}{0}

\NewDocumentCommand{\getSumRequestedFunds}{ O{RequestedFunding} m m m }{%
  \DTLifdbexists{#1}{%
    \@@_funding_sum_set:Nnnnn \SumRequestedFunds {#1}{#2}{#3}{#4}%
    \@@_show_calculated_number:nnN
      {getSumRequestedFunds}{#1}
      \SumRequestedFunds
  }{%
  	\texttt{\color{error}XXX}%
  	\msg_warning:nne { dfg } { database-not-found } { #1 }%
  }%
}
\NewDocumentCommand{\dfgCheckIfZeroShowCategory}{ O{RequestedFunding} m m }
{
  % #1: database
  % #2: project
  % #3: category/type
  \def\tmpLocalDB{#1}
  \DTLifdbexists{\tmpLocalDB}{
    \@@_funding_sum_set:Nnnnn \SumRequestedFunds {#1}{#2}{#3}
      {sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  	\fp_compare:nNnT { \SumRequestedFunds } = {0}
  	{ \tl_clear:c {l__tmp_body_#3_tl }}
  }
  {
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}
%    \end{macrocode}
% This is for |Requested funding for direct costs fo the new funding period| and
% is partially data from new key-values and partially it has to be reused.
%    \begin{macrocode}
\NewDocumentCommand{\RequestedAndExistingFundingDirectCostsTable}{m}
{
  % #1: project
  \def\tmpLocalDB{RequestedAndExistingFundingDirectCosts}%
  \DTLifdbexists{\tmpLocalDB}{%
  	\tl_clear:N \l__tmp_body_costs_tl
  	\DTLforeach[\DTLiseq{\pProject}{#1}]{\tmpLocalDB}{
  		\pProject=ref-project-id,
  		\pAffiliation=ref-affiliation-id,
  		\pFinancedBy=financed-by,
  		\pSumYearOne=sum-year1,
  		\pSumYearTwo=sum-year2,
  		\pSumYearThree=sum-year3,
  		\pSumYearFour=sum-year4,
  		\pSumYearFive=sum-year5
  	}{
		\DTLaddall{\tmpHorizontalSum}{
  			\pSumYearOne,
  			\pSumYearTwo,
  			\pSumYearThree,
  			\pSumYearFour,
  			\pSumYearFive
  		}

  		\tl_put_right:Ne \l__tmp_body_costs_tl
  		{
  			\str_if_eq:VnTF { \pAffiliation }  { other-funds }
  			{ Other }
      { \getEntry[affiliation]{\pAffiliation}{abbreviation} : } ~
      existing~ funds~ from~
      % Freeze the database value without expanding commands such as \RWTH,
      % whose trailing \xspace must only run when the completed cell is typeset.
      \dfgShowTag{\pProject/\pAffiliation}{financed-by}
        {\exp_not:V \pFinancedBy}[\tmpLocalDB]
      \printMarginalia{\dfgShowCalculatedTag
        {RequestedAndExistingFundingDirectCostsTable}{\tmpLocalDB}
        {\@@_show_eur:n{\tmpHorizontalSum}}}
      & \dfgShowTag{\pProject/\pAffiliation}{sum-year1}
          {\@@_show_eur:n{\pSumYearOne}}[\tmpLocalDB]
      & \dfgShowTag{\pProject/\pAffiliation}{sum-year2}
          {\@@_show_eur:n{\pSumYearTwo}}[\tmpLocalDB]
      & \dfgShowTag{\pProject/\pAffiliation}{sum-year3}
          {\@@_show_eur:n{\pSumYearThree}}[\tmpLocalDB]
      & \dfgShowTag{\pProject/\pAffiliation}{sum-year4}
          {\@@_show_eur:n{\pSumYearFour}}[\tmpLocalDB]
      & \dfgShowTag{\pProject/\pAffiliation}{sum-year5}
          {\@@_show_eur:n{\pSumYearFive}}[\tmpLocalDB] \\
  		}
  	}
  	\tl_put_right:Ne \l__tmp_body_costs_tl
  	{
  		\SetHline{-}{tableOuterLines,0.5pt}
  		\SetRow{belowsep=5pt}
  		Sum~ of~ existing~ funds
  		\printMarginalia{%
  			\getSumExistingFunds{#1}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  		}
  		& \getSumExistingFunds{#1}{sum-year1}
  		& \getSumExistingFunds{#1}{sum-year2}
  		& \getSumExistingFunds{#1}{sum-year3}
  		& \getSumExistingFunds{#1}{sum-year4}
  		& \getSumExistingFunds{#1}{sum-year5} \\
  	}

  	\begin{tblr}[
  			theme=main,
  			long,
  			expand=
  			\l__tmp_body_costs_tl,
			remark{Note}={Figures~ in~ EUR.},
  		]{
  			% colsep=3pt,
  			colspec = {
  					*{1}{X[4,t]}
  						*{5}{
							@{}X[c,si={table-format=8}]
  						}},
  			rows = {bg=white},
			column{2-6}={guard},
        row{1}= {valign=m,guard,bg=tableHeadingsBG},
  			row{Y,Z}= {
  				          %bg=tableHeadingsBGalt,
  				          font={\footnotesize\bfseries}},
  		}

		 & \dfgFundingYear{1}
		 & \dfgFundingYear{2}
		 & \dfgFundingYear{3}
		 & \dfgFundingYear{4}
		 & \dfgFundingYear{5}                                \\

  		\l__tmp_body_costs_tl

  		\SetHline{-}{tableOuterLines,.75pt}
  		%\SetCell{font=\bfseries\footnotesize}
  		Sum~ of~ requested~ funds
  		\printMarginalia{%
  			\getSumRequestedFunds{#1}{costs}
  			{sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  		}
  		 & \getSumRequestedFunds{#1}{costs}{sum-year1}
  		 & \getSumRequestedFunds{#1}{costs}{sum-year2}
  		 & \getSumRequestedFunds{#1}{costs}{sum-year3}
  		 & \getSumRequestedFunds{#1}{costs}{sum-year4}
  		 & \getSumRequestedFunds{#1}{costs}{sum-year5} \\
  	\end{tblr}
  }{
  	Database~ \texttt{#1}~ missing.
  	\msg_warning:nne { dfg } { database-not-found }{ #1 }
  }
}
%    \end{macrocode}
% \subsection{Boxes}
%    \begin{macrocode}
\RequirePackage[breakable,fitting,skins,most]{tcolorbox}

\tcbset{
  PIbox/.style={
  		%enhanced, breakable,
  		colback=white, colframe=white,
  		coltitle=black,
  		boxrule=0pt, %arc=2pt,
  		before~ skip=0pt, after~ skip=7pt,
		before~ title=\raggedright,
		before~ upper=\raggedright,
  		boxsep=0pt,
  		left=0pt, right=0pt, top=7pt, bottom=0pt,
  	},
}

\bool_if:NTF \l_@@_class_final_bool
{\newcommand{\dfgcomment}[2][]{}}
{\NewTotalTColorBox{\dfgcomment}{ O{} m }
  {%
  	nobeforeafter,
  	colupper=black!50!white,
  	coltitle=black!75!white,
  	fonttitle=\fontsize{7}{9}\selectfont\bfseries,
  	colback=black!5!white,
  	colframe=black!15!white,
  	width=\linewidth,
  	%  text height=4cm,
  	breakable,
  	enhanced,
  	left=0pt,right=0pt,
  	top=0pt,bottom=0pt,
  	% text width=\linewidth,
  	fontupper=\fontsize{7}{9}\selectfont,
  	title={Anmerkung~der~DFG},
  	#1
  }{#2}}
%    \end{macrocode}
% defining standard for boxes
%    \begin{macrocode}
\tcbset{
  dfgStyle/.style={%
  		enhanced~ jigsaw,
  		colback       =white,
  		colbacktitle  =tableHeadingsBG,
  		coltitle      =tableHeadingsFont,
  		colframe      =tableOuterLines,
  		%colupper      =tableHeadingsFont,
  		fontupper     =\sffamily,
  		fonttitle     =\bfseries,
  		% after skip   =1em,
  		before        ={\pagebreak[0]},
  		after         ={\nopagebreak},
  		% fonttitle    =\bfseries,
  		%boxrule      =0.5pt,
  		sharp~ corners,
  		toprule      =1pt,
  		rightrule    =0mm,
  		leftrule     =0mm,
  		% drop shadow =rwthGrey,
  		%drop large lifted shadow,
  		width         =\linewidth,
  		bottomrule    =1pt,
  		% draft,
  		left          =2mm,
  		bottom        =0mm,
  		top           =0mm,
  		capture       =minipage,
  	}}
%    \end{macrocode}
%
%    \begin{macrocode}
\NewTotalTColorBox{\dfgBox}{ O{} +m }
{%
  dfgStyle,
  nobeforeafter,
  left=0pt,right=0pt,
  top=0pt,bottom=0pt,
  #1
}{#2}
%    \end{macrocode}
% A handy box to aggregate important points, \refEnv{dfgSummaryBox}.
%    \begin{macrocode}
\newtcolorbox{dfgSummaryBox}[1][]{
  dfgStyle,
  top=1mm,
  left=1mm,
  bottom=1mm,
  before={\par},
  after={\par},
  before~ upper={\begin{itemize}[leftmargin=.5cm]%
  		\renewcommand{\labelitemi}{\dfgTargetPoint}%
  		\hypersetup{linkcolor=tableHeadingsFont}%
  		\colorlet{referencePI}{tableHeadingsFont}
  		\colorlet{referenceWP}{tableHeadingsFont}
  		\colorlet{referenceAim}{tableHeadingsFont}
  	},
  after~ upper={\end{itemize}},
  %  height=2.5cm,
  fontupper=\rmfamily,
  % ------ title below.
  width=\linewidth,
  rounded~ corners,
  toprule=1pt,
  rightrule=1pt,
  leftrule=1pt,
  bottomrule=1pt,
  % attach boxed title to bottom center,
  boxed~ title~ style={empty,boxrule=1pt},
  varwidth~ boxed~ title=0.5\linewidth,
  #1
}
%    \end{macrocode}
% Box for anything like the aims section.
%    \begin{macrocode}
\newtcolorbox{dfgBoxEnv}[1][]{
  dfgStyle,
  % top=-1.5mm,
  % left=1mm,
  before={\par},
  #1
}
%    \end{macrocode}
% \subsection{New Commands}
% Providing further commands that can and will be used throughout the document
%    \begin{macrocode}
\providecommand{\crc}{Collaborative~ Research~ Centre\xspace}

% getting the main logo of the CRC
% the filename needs to be adjusted or make this more generic.
\providecommand{\crcLogoPath}{\tl_use:N \l_@@_custom_crc_logo_path_tl}
\providecommand{\affiliationLogoPath}
  {\tl_use:N \l_@@_custom_affiliation_logo_path_tl}

\NewDocumentCommand{\crcLogo}{O{1cm}}{%
  \includegraphics[#1]{\crcLogoPath}}

% same for the affiliation.
\NewDocumentCommand{\affiliationLogo}{O{1cm}}{%
  \includegraphics[#1]{\affiliationLogoPath}}

\keys_define:nn { hrule }
{
  color     .tl_set:N   = \l__hrule_color_tl,
  color     .initial:n  = color@tags@line,
  above     .dim_set:N  = \l__hrule_above_dim,
  above     .initial:n  = 0pt,
  below     .dim_set:N  = \l__hrule_below_dim,
  below     .initial:n  = 0pt,
  thickness .dim_set:N  = \l__hrule_thickness_dim,
  thickness .initial:n  = 0.4pt,
}

\ProvideDocumentCommand{\Hrule}{O{}}
{%
  \group_begin:
  \keys_set:nn { hrule } {#1}%
  \par
  \addvspace{ \l__hrule_above_dim }%
  {\color{ \l__hrule_color_tl }\hrule height \l__hrule_thickness_dim}%
  \addvspace{ \l__hrule_below_dim }%
  \group_end:
}

% remodeling for the titlepage where we use some center-environments
\AtBeginEnvironment{center}{
  % \vspace*{-1em}
}
%    \end{macrocode}

%    \begin{macrocode}
\seq_new:N \l_@@_sig_pairs_seq
\tl_new:N  \l_@@_sig_id_tl
\tl_new:N  \l_@@_sig_desc_tl
%    \end{macrocode}
%
% \begin{macro}{\printSignature}
%   |\printSignature[<db>]{ {<id>}{<desc>} {<id>}{<desc>} ... }| --
%   one signature block per |{id}{desc}| pair. |<db>| defaults to
%   |person|. Inside |<desc>| you may use |\theAffiliationOfRoleID|,
%   which is set to the person's |ref-institution-id| before the
%   description is typeset.
%    \begin{macrocode}
\NewDocumentCommand{\printSignature}{ O{person} m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \par
    \seq_set_split:Nnn \l_@@_sig_pairs_seq { } {#2}
    \int_compare:nNnT { \seq_count:N \l_@@_sig_pairs_seq } > { 0 }
    { \@@_signature_consume_pairs:n {#1} }
  }
}

\tl_new:N \l_@@_signature_role_id_tl
\tl_new:N \l_@@_signature_role_tl
\tl_new:N \l_@@_signature_role_period_tl

\NewDocumentCommand{\printSignaturesWithRole}{ O{person} m m }
{
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \DTLifdbexists{#1}
    {
      \DTLforeach*[
        \DTLisinlist{\theFundingPeriodNumeral}{\l_@@_signature_role_period_tl}
        \and
        \DTLisinlist{#2}{\l_@@_signature_role_tl}
      ]{#1}{
        \l_@@_signature_role_id_tl     = id,
        \l_@@_signature_role_tl        = role,
        \l_@@_signature_role_period_tl = period
      }{
        \@@_signature_block:nnn
          {#1}{\l_@@_signature_role_id_tl}{#3}
      }
    }
    { \msg_warning:nne { dfg } { database-not-found } {#1} }
  }
}
%    \end{macrocode}
% \end{macro}
%
%   Pops |{id}{desc}| pairs off |\l_@@_sig_pairs_seq| until empty,
%   typesetting one block per pair.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_signature_consume_pairs:n #1
{
  \seq_pop_left:NN \l_@@_sig_pairs_seq \l_@@_sig_id_tl
  \seq_pop_left:NNTF \l_@@_sig_pairs_seq \l_@@_sig_desc_tl
  {
  	\@@_signature_block:nVV {#1} \l_@@_sig_id_tl \l_@@_sig_desc_tl
  	\seq_if_empty:NF \l_@@_sig_pairs_seq
  	{ \@@_signature_consume_pairs:n {#1} }
  }
  {
  	\msg_warning:nnn { crc-proposal } { signature-odd-args } {#1}
  }
}
\msg_new:nnn { crc-proposal } { signature-odd-args }
{ \printSignature\ in\ db\ '#1':\ odd\ number\ of\ tokens,\ %
  expected\ {id}{desc}\ pairs. }
%    \end{macrocode}
%   Typesets a single signature block for person |#2| in db |#1|
%   with description |#3|. Sets |\theAffiliationOfRoleID| from the
%   row's |ref-institution-id| before expanding |#3|.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_signature_block:nnn #1 #2 #3
{
  \@@_getvalueforkey:Nnnnn{\theAffiliationOfRoleID}{ref-affiliation-id}{#1}{id}{#2}
  \@@_getvalueforkey:Nnnnn{\@@tmpDegree}   {academicdegree}{#1}{id}{#2}
  \@@_getvalueforkey:Nnnnn{\@@tmpFirst}    {firstname}     {#1}{id}{#2}
  \@@_getvalueforkey:Nnnnn{\@@tmpLast}     {lastname}      {#1}{id}{#2}
  \begin{tblr}{
  	            width=\linewidth,
  	            colspec={@{}b{3cm}b{1cm}X[b]@{}},
              }
              {\theCRCaffiliationLocation \\ \dfgDate} &  & \faFileSignature                                       \\
              \SetHline{3-3}{tableOuterLines,1pt}
                                                       &  & {
                                                            \dfgShowTag{#2}{academicdegree}{\@@tmpDegree}[#1]\space
                                                              \textcolor{referencePI}{
                                                              \dfgShowTag{#2}{firstname}{\@@tmpFirst}[#1]\space
                                                              \dfgShowTag{#2}{lastname}{\@@tmpLast}[#1]} \\
  	                                                          #3 } \\
  \end{tblr}
  \par\bigskip
}
\cs_generate_variant:Nn \@@_signature_block:nnn { nVV }
%    \end{macrocode}
% If there are multiple institutions mentioned we want to have a list of all of
% them with their affiliation.
% We are getting the possible list of institutions into one command
% Loop over your list and build the sequence.1
%    \begin{macrocode}
\bool_new:N \l_@@_narrow_bool
\bool_new:N \l_@@_institution_abbreviation_bool
\bool_new:N \l_@@_noaddr_bool
\bool_new:N \l_@@_nozip_bool
\bool_new:N \l_@@_noloc_bool
\bool_new:N \l_@@_has_country_bool
\seq_new:N  \l_@@_inst_ids_seq
\tl_new:N   \l_@@_sep_tl
\tl_new:N   \l_@@_inst_sep_tl

\cs_generate_variant:Nn \seq_set_from_clist:Nn { NV }

\keys_define:nn { @@ / institution-list }
{
  abbreviation .bool_set:N = \l_@@_institution_abbreviation_bool,
  narrow .bool_set:N = \l_@@_narrow_bool,
  noaddress .bool_set:N = \l_@@_noaddr_bool,
  nozip .bool_set:N = \l_@@_nozip_bool,
  nolocation .bool_set:N = \l_@@_noloc_bool,
}

\NewDocumentCommand{\InstitutionsList}{O{} m O{}}
{
  \group_begin:
    \@@_list_options:n {#1}
    \tl_put_left:Nn \l_@@_list_options_tl {#3,}
    \exp_args:NVnV \@@_institutions_list:nnn
      \l_@@_list_database_tl {#2} \l_@@_list_options_tl
  \group_end:
}

\cs_new_protected:Npn \@@_institutions_list:nnn #1#2#3
{
 \bool_if:NTF \l_@@_class_fastcompile_project_bool
 { \dfgFastReference{#2} }
 {
 \DTLifdbexists{#1}{
  % Parse key names rather than comparing tokens: options forwarded by
  % keys_set_known may have string catcodes. Boolean values also allow a
  % leading setting to override an older trailing flag.
  \bool_set_false:N \l_@@_institution_abbreviation_bool
  \bool_set_false:N \l_@@_narrow_bool
  \bool_set_false:N \l_@@_noaddr_bool
  \bool_set_false:N \l_@@_nozip_bool
  \bool_set_false:N \l_@@_noloc_bool
  \keys_set:nn { @@ / institution-list } {#3}
  \bool_if:NTF \l_@@_narrow_bool
  {
    \tl_set:Nn \l_@@_sep_tl {,~}
    \tl_set:Nn \l_@@_inst_sep_tl {;~}
  }
  {
    \tl_set:Nn \l_@@_sep_tl {\newline}
    \tl_set:Nn \l_@@_inst_sep_tl {\par\medskip}
  }
  \datatool_if_has_key:nnTF {affiliation}{country}
  { \bool_set_true:N \l_@@_has_country_bool }
  { \bool_set_false:N \l_@@_has_country_bool }

  % --- get list of institution ids for this person --------------------
  \@@_getvalueforkey:Nnnnn{\theInstitutionListValue}{ref-institution-id}{#1}{id}{#2}
  \seq_set_from_clist:NV \l_@@_inst_ids_seq \theInstitutionListValue

  % --- iterate --------------------------------------------------------
  \bool_set_true:N \l_tmpa_bool
  \seq_map_inline:Nn \l_@@_inst_ids_seq
  {
  	\bool_if:NTF \l_tmpa_bool
  	{ \bool_set_false:N \l_tmpa_bool }
  	{ \tl_use:N \l_@@_inst_sep_tl }
  	\_@@_one_institution:n {##1}
  }
}
   {
     Database~ \texttt{#1}~ missing.
     \msg_warning:nne { dfg } { database-not-found }{ #1 }
   }
 }
}

% Compatibility spelling for older proposal sources.
\cs_new_eq:NN \dfgInstitutionList \InstitutionsList

\cs_new_protected:Npn \_@@_one_institution:n #1
{
 \DTLifdbexists{institution}{ \@@_getvalueforkey:Nnnnn{\theAffiliationIDValue}{ref-affiliation-id}{institution}{id}{#1}

  \bool_if:NTF \l_@@_institution_abbreviation_bool
  {
    \@@_institution_abbreviation_or_name:nN
      {#1} \l_tmpa_tl
    \cs_set:Npx \theInstitutionNameValue { \exp_not:V \l_tmpa_tl }
  }
  { \@@_getvalueforkey:Nnnnn{\theInstitutionNameValue}{name}{institution}{id}{#1} }
  \DTLifnullorempty{\theInstitutionNameValue}{}
  {
    \dfgShowTag{#1}{\l_@@_institution_label_field_tl}
      {\theInstitutionNameValue}[institution]
  	\tl_use:N \l_@@_sep_tl
  }

  \@@_getvalueforkey:Nnnnn{\theAffiliationNameValue}{name}{affiliation}{id}{\theAffiliationIDValue}
  \dfgShowTag{\theAffiliationIDValue}{name}
    {\theAffiliationNameValue}[affiliation]

  \bool_if:NF \l_@@_noaddr_bool
  {
  	\tl_use:N \l_@@_sep_tl
    \@@_getvalueforkey:Nnnnn{\theAffiliationStreetValue}{addressStreet}{affiliation}{id}{\theAffiliationIDValue}
    \dfgShowTag{\theAffiliationIDValue}{addressStreet}
      {\theAffiliationStreetValue}[affiliation]
  }

  \bool_if:NF \l_@@_nozip_bool
  {
  	,~
    \@@_getvalueforkey:Nnnnn{\theAffiliationZIPValue}{addressZIP}{affiliation}{id}{\theAffiliationIDValue}
    \dfgShowTag{\theAffiliationIDValue}{addressZIP}
      {\theAffiliationZIPValue}[affiliation]
  	\bool_if:NF \l_@@_noloc_bool { ~ }
  }

  \bool_if:NF \l_@@_noloc_bool
  {
  	\bool_if:NT \l_@@_nozip_bool { ,~ }
    \@@_getvalueforkey:Nnnnn{\theAffiliationLocationValue}{location}{affiliation}{id}{\theAffiliationIDValue}
    \dfgShowTag{\theAffiliationIDValue}{location}
      {\theAffiliationLocationValue}[affiliation]
  	\bool_if:NT \l_@@_has_country_bool
  	{
      \@@_getvalueforkey:Nnnnn{\theAffiliationCountryValue}{country}{affiliation}{id}{\theAffiliationIDValue}
  		\DTLifnullorempty{\theAffiliationCountryValue}{}
      { ~(\dfgShowTag{\theAffiliationIDValue}{country}
          {\theAffiliationCountryValue}[affiliation]) }
  	}
  }
}
   {
     Database~ \texttt{institution}~ missing.
     \msg_warning:nne { dfg } { database-not-found }{ institution }
   }
}
%    \end{macrocode}
% get all the PIs who have a certain role in the crc this can be e.g.
% 'spokesperson', 'steering-committee-member'. The leading options include
% database (person by default) and raster settings. Trailing raster options
% remain supported for older documents.
%    \begin{macrocode}
\keys_define:nn { @@ / pi-role-list }
{
  academicdegree-below .bool_set:N = \l_@@_pi_academicdegree_below_bool,
}

\NewDocumentCommand{\getPIsWithRole}{O{} m O{}}
{
  \group_begin:
    \bool_set_false:N \l_@@_pi_academicdegree_below_bool
    \@@_list_options:n {#1}
    \tl_put_left:Nn \l_@@_list_options_tl {#3,}
    \exp_args:NnV \keys_set_known:nnN { @@ / pi-role-list }
      \l_@@_list_options_tl \l_@@_list_options_tl
    \exp_args:NVnV \@@_get_pis_with_role:nnn
      \l_@@_list_database_tl {#2} \l_@@_list_options_tl
  \group_end:
}

\cs_new_protected:Npn \@@_get_pis_with_role:nnn #1#2#3
{%
  \bool_if:NTF \l_@@_class_fastcompile_bool
  { \dfgItemSkipped{dfgPIsWithRole:~#2} }
  {%
    \DTLifdbexists{#1}
    {
      \def\tmpLocalDB{#1}%
      \DTLsort*{lastname}{#1}%
      \begin{tcbraster}[
          raster~ valign=top,
          raster~ columns=3,
          raster~ equal~ height=rows,
          raster~ column~ skip=12pt,
          raster~ row~ skip=20pt,
          raster~ after~ skip=20pt,
          PIbox,
          #3
        ]
        \DTLforeach*[
          \DTLisinlist{\theFundingPeriodNumeral}{\period}
          \and
          \DTLisinlist{#2}{\role}
        ]{#1}{
          \id     = id,
          \role   = role,
          \period = period
        }{%
          \__getperson_one:n {\id}%
        }%
      \end{tcbraster}
    }
    {
      Database~ \texttt{#1}~ missing.
      \msg_warning:nne { dfg } { database-not-found }{ #1 }
    }
  }
}
%    \end{macrocode}
% In the text you can reference to a PI with the following command.
% The name is highlighted and referenced.
%    \begin{macrocode}
\cs_new_protected:Npn \@@_pi_reference_seq_use:N #1
{
  \bool_if:NTF \g_@@_tblr_inside_bool
    { \seq_use:Nn #1 {\addnbthinspace/\addthinspace} }
    { \seq_use:Nnnn #1 {~and~} {,~} {,~and~} }
}

\NewDocumentCommand{\getPI}{s m o} {
  % #1: starred version -> firstname
  % #2: id of PI / person
  % #3: optional text, but reference linked to PI 
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \IfNoValueTF{#3}{\dfgFastReference{#2}}{#3} }
  {
  \seq_clear:N \l_tmpa_seq
  \seq_set_from_clist:Nn \l_tmpa_seq {#2}%
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq {
  	\exp_not:n {
  		\group_begin:
      \@@_getvalueforkey:Nnnnn{\thePersonName}{lastname}{person}{id}{##1}
      \@@_getvalueforkey:Nnnnn{\thePersonFirstName}{firstname}{person}{id}{##1}
  		\datatool_if_null:NTF {\thePersonName}
  		{ \getEntry[person]{##1}{lastname} %<- just to get the error message 
  			\textcolor{error}{\texttt{<##1>}}
  		}
  		{
          \tl_if_eq:NnF \l_@@_custom_referencePI_tl {current}
            { \color{referencePI} }
          \bfseries
  			\IfNoValueTF{#3}%

              {\hyperlink{pi:##1}{\@@_pi_reference_name:nn {#1}{##1}}}
  			{\hyperlink{pi:##1}{#3}}}
  		\group_end:
  	}}
  \@@_pi_reference_seq_use:N \l_tmpb_seq
  }
}
%    \end{macrocode}
% Unstarred PI references disambiguate shared surnames across all PI records
% with the first given-name initial, for example K.~Schneider and C.~Schneider.
% If that initial is shared as well, use the full given name. Starred references
% and explicit display text retain their existing behavior, as do unique names.
% Project-first references inherit this formatting through \cs{getPI}.
% Reuse surname and initial indexes while the raw metadata is unchanged.
% Macro-valued names and roles retain the original scan so redefinitions are
% reflected immediately; formatting and hyperlinks are never cached.
% The snapshot covers the raw person database and its header definitions, so
% additions, direct edits, sorting, and scoped changes rebuild both frequency
% lists. PI and Co-PI roles are included. The reference formatter still chooses
% the surname, initial, or full given name separately for each output context.
%    \begin{macrocode}
\tl_new:N \l_@@_pi_lastname_tl
\tl_new:N \l_@@_pi_firstname_tl
\tl_new:N \l_@@_pi_initial_tl
\tl_new:N \l_@@_pi_candidate_lastname_tl
\tl_new:N \l_@@_pi_candidate_firstname_tl
\tl_new:N \l_@@_pi_candidate_initial_tl
\clist_new:N \l_@@_pi_candidate_roles_clist
\bool_new:N \l_@@_pi_candidate_is_pi_bool
\int_new:N \l_@@_pi_same_lastname_int
\int_new:N \l_@@_pi_same_initial_int

% Count matching PI surnames and first initials across the current metadata.
\prop_new:N \g_@@_pi_lastname_counts_prop
\prop_new:N \g_@@_pi_initial_counts_prop
\tl_new:N \g_@@_pi_index_snapshot_tl
\tl_new:N \l_@@_pi_index_snapshot_tl
\tl_new:N \l_@@_pi_index_key_tl
\tl_new:N \l_@@_pi_index_value_tl
\tl_new:N \l_@@_pi_index_source_tl
\bool_new:N \g_@@_pi_index_literal_bool

\cs_new_protected:Npn \@@_pi_index_increment:NN #1#2
{
  \prop_get:NVNTF #1 #2 \l_@@_pi_index_value_tl
    { \prop_gput:NVx #1 #2 { \int_eval:n {\l_@@_pi_index_value_tl + 1} } }
    { \prop_gput:NVn #1 #2 {1} }
}

\cs_new_protected:Npn \@@_pi_index_check_literal:N #1
{
  \DTLifnullorempty{#1}{}
  {
    \tl_set:No \l_@@_pi_index_source_tl {#1}
    \tl_set:Ne \l_@@_pi_index_source_tl
      { \tl_to_str:V \l_@@_pi_index_source_tl }
    \exp_args:NnV \regex_match:nnT {\\} \l_@@_pi_index_source_tl
      { \bool_gset_false:N \g_@@_pi_index_literal_bool }
  }
}

\cs_new_protected:Npn \@@_pi_index_build:
{
  \prop_gclear:N \g_@@_pi_lastname_counts_prop
  \prop_gclear:N \g_@@_pi_initial_counts_prop
  \bool_gset_true:N \g_@@_pi_index_literal_bool
  \DTLforeach*{person}
  {
    \dfgDisambiguationName=lastname,
    \dfgDisambiguationFirstname=firstname,
    \dfgDisambiguationRoles=role
  }
  {
    % Macro-valued names/roles may change without a database edit. Keep the
    % original scan for those datasets; literal names can use the index.
    \@@_pi_index_check_literal:N \dfgDisambiguationName
    \@@_pi_index_check_literal:N \dfgDisambiguationFirstname
    \@@_pi_index_check_literal:N \dfgDisambiguationRoles
    \clist_set:Nx \l_@@_pi_candidate_roles_clist {\dfgDisambiguationRoles}
    \bool_set_false:N \l_@@_pi_candidate_is_pi_bool
    \clist_if_in:NnT \l_@@_pi_candidate_roles_clist {PI}
      {\bool_set_true:N \l_@@_pi_candidate_is_pi_bool}
    \clist_if_in:NnT \l_@@_pi_candidate_roles_clist {Co-PI}
      {\bool_set_true:N \l_@@_pi_candidate_is_pi_bool}
    \bool_if:NT \l_@@_pi_candidate_is_pi_bool
    {
      \tl_set:Nx \l_@@_pi_candidate_lastname_tl {\dfgDisambiguationName}
      \tl_set:Nx \l_@@_pi_candidate_firstname_tl {\dfgDisambiguationFirstname}
      \tl_trim_spaces:N \l_@@_pi_candidate_firstname_tl
      \tl_set:Nx \l_@@_pi_candidate_initial_tl
        {\tl_head:V \l_@@_pi_candidate_firstname_tl}
      \@@_pi_index_increment:NN \g_@@_pi_lastname_counts_prop
        \l_@@_pi_candidate_lastname_tl
      \tl_set:Ne \l_@@_pi_index_key_tl
      {
        {\exp_not:V \l_@@_pi_candidate_lastname_tl}
        {\exp_not:V \l_@@_pi_candidate_initial_tl}
      }
      \@@_pi_index_increment:NN \g_@@_pi_initial_counts_prop
        \l_@@_pi_index_key_tl
    }
  }
}

\cs_new_protected:Npn \@@_pi_count_name_matches:
{
  \@@_database_snapshot:nN {person} \l_@@_pi_index_snapshot_tl
  \tl_if_eq:NNF \l_@@_pi_index_snapshot_tl \g_@@_pi_index_snapshot_tl
  {
    \@@_pi_index_build:
    \tl_gset_eq:NN \g_@@_pi_index_snapshot_tl \l_@@_pi_index_snapshot_tl
  }
  \bool_if:NTF \g_@@_pi_index_literal_bool
  {
    \int_zero:N \l_@@_pi_same_lastname_int
    \int_zero:N \l_@@_pi_same_initial_int
    \prop_get:NVNT \g_@@_pi_lastname_counts_prop \l_@@_pi_lastname_tl
      \l_@@_pi_index_value_tl
      { \int_set:Nn \l_@@_pi_same_lastname_int {\l_@@_pi_index_value_tl} }
    \tl_set:Ne \l_@@_pi_index_key_tl
    {
      {\exp_not:V \l_@@_pi_lastname_tl}
      {\exp_not:V \l_@@_pi_initial_tl}
    }
    \prop_get:NVNT \g_@@_pi_initial_counts_prop \l_@@_pi_index_key_tl
      \l_@@_pi_index_value_tl
      { \int_set:Nn \l_@@_pi_same_initial_int {\l_@@_pi_index_value_tl} }
  }
  { \@@_pi_count_name_matches_uncached: }
}

\cs_new_protected:Npn \@@_pi_count_name_matches_uncached:
  {
    \int_zero:N \l_@@_pi_same_lastname_int
    \int_zero:N \l_@@_pi_same_initial_int
    \DTLforeach*{person}
      {
        \dfgDisambiguationName=lastname,
        \dfgDisambiguationFirstname=firstname,
        \dfgDisambiguationRoles=role
      }
      {
        \clist_set:Nx \l_@@_pi_candidate_roles_clist {\dfgDisambiguationRoles}
        \bool_set_false:N \l_@@_pi_candidate_is_pi_bool
        \clist_if_in:NnT \l_@@_pi_candidate_roles_clist {PI}
          {\bool_set_true:N \l_@@_pi_candidate_is_pi_bool}
        \clist_if_in:NnT \l_@@_pi_candidate_roles_clist {Co-PI}
          {\bool_set_true:N \l_@@_pi_candidate_is_pi_bool}
        \bool_if:NT \l_@@_pi_candidate_is_pi_bool
          {
            \tl_set:Nx \l_@@_pi_candidate_lastname_tl {\dfgDisambiguationName}
            \tl_if_eq:NNT \l_@@_pi_lastname_tl \l_@@_pi_candidate_lastname_tl
              {
                \int_incr:N \l_@@_pi_same_lastname_int
                \tl_set:Nx \l_@@_pi_candidate_firstname_tl {\dfgDisambiguationFirstname}
                \tl_trim_spaces:N \l_@@_pi_candidate_firstname_tl
                \tl_set:Nx \l_@@_pi_candidate_initial_tl
                  {\tl_head:V \l_@@_pi_candidate_firstname_tl}
                \tl_if_eq:NNT \l_@@_pi_initial_tl \l_@@_pi_candidate_initial_tl
                  {\int_incr:N \l_@@_pi_same_initial_int}
              }
          }
      }
  }

% Render the name inside the PI hyperlink. #1 is the star, #2 the person ID.
% The caller has already fetched and validated the name fields.
\cs_new_protected:Npn \@@_pi_reference_name:nn #1#2
  {
    \group_begin:
    \IfBooleanTF{#1}
      {\dfgShowTag{#2}{firstname}{\thePersonFirstName}[person]\space}
      {
        \tl_set:Nx \l_@@_pi_lastname_tl {\thePersonName}
        \tl_set:Nx \l_@@_pi_firstname_tl {\thePersonFirstName}
        \tl_trim_spaces:N \l_@@_pi_firstname_tl
        \tl_set:Nx \l_@@_pi_initial_tl {\tl_head:V \l_@@_pi_firstname_tl}
        \@@_pi_count_name_matches:
        \int_compare:nNnTF {\l_@@_pi_same_lastname_int} > {1}
          {
            \int_compare:nNnTF {\l_@@_pi_same_initial_int} > {1}
              {\dfgShowTag{#2}{firstname}{\thePersonFirstName}[person]}
              {\tl_use:N \l_@@_pi_initial_tl.}
            \nobreakspace
          }
          {
            \bool_if:NT \l_@@_custom_pi_reference_firstname_bool
              {\dfgShowTag{#2}{firstname}{\thePersonFirstName}[person]\space}
          }
      }
    \dfgShowTag{#2}{lastname}{\thePersonName}[person]
    \group_end:
  }
%    \end{macrocode}
% Very similarly, we want to get a list of the projects.
%    \begin{macrocode}
\NewDocumentCommand \getProjectColor { m }
{
  \exp_args:Nx \color { project \tl_head:n { #1 } }
}
\tl_new:N \l_@@_project_reference_only_tl

\prg_new_protected_conditional:Npnn \@@_project_if_reference_only:n #1
  { T,F,TF }
{
  \@@_getvalueforkey:Nnnnn{\l_@@_project_reference_only_tl}
    {reference-only}{project}{id}{#1}
  \str_if_eq:VnTF \l_@@_project_reference_only_tl { true }
    { \prg_return_true: }
    { \prg_return_false: }
}

\cs_new_protected:Npn \@@_project_reference_only_indicator:
{
  \bool_if:NTF \l_@@_former_project_compact_bool
  {
    \bool_gset_true:N \g_@@_former_project_seen_bool
    {\normalfont\normalcolor\textsuperscript{*}}
  }
  {
    \nobreakspace
    {\normalfont\normalcolor(former~project)}
  }
}

% Project references read naturally in prose but need a compact delimiter in
% narrow table cells.  Keep the two container variants centralized so
% \cs{getProject}, \cs{getProjectPI}, and focused-project fallbacks cannot
% diverge.
\bool_new:N \l_@@_project_newline_separator_bool
\bool_new:N \l_@@_project_custom_text_bool
\cs_new_protected:Npn \@@_project_reference_seq_use:N #1
{
  \bool_if:NTF \l_@@_project_newline_separator_bool
    { \seq_use:Nn #1 {\\} }
    {
      \bool_if:NTF \g_@@_tblr_inside_bool
        { \seq_use:Nn #1 {\addnbthinspace/\addthinspace} }
        { \seq_use:Nnnn #1 {~and~} {,~} {,~and~} }
    }
}

\cs_new_protected:Npn \@@_project_reference_clist_use:N #1
{
  \bool_if:NTF \g_@@_tblr_inside_bool
    { \clist_use:Nn #1 {\addnbthinspace/\addthinspace} }
    { \clist_use:Nnnn #1 {~and~} {,~} {,~and~} }
}

\cs_new_protected:Npn \@@_get_project_compact:nn #1#2 {
  % #1: id of project
  % #2: optional text, or \newline/\\ for a stacked project list
  \bool_set_false:N \l_@@_project_newline_separator_bool
  \bool_set_false:N \l_@@_project_custom_text_bool
  \IfNoValueF{#2}
    {
      \bool_set_true:N \l_@@_project_custom_text_bool
      \tl_if_eq:nnT {#2} {\newline}
        { \bool_set_false:N \l_@@_project_custom_text_bool
          \bool_set_true:N \l_@@_project_newline_separator_bool }
      \tl_if_eq:nnT {#2} {\\}
        { \bool_set_false:N \l_@@_project_custom_text_bool
          \bool_set_true:N \l_@@_project_newline_separator_bool }
    }
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \seq_set_from_clist:Nn \l_tmpa_seq {#1}
    \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq
    {
      \exp_not:n
      {
        \bool_if:NTF \l_@@_project_custom_text_bool
          {#2}
          {
            \dfgShowTag {##1}{number}
              {\@@_fast_project_reference:n {##1}}[project]
          }
      }
    }
    \@@_project_reference_seq_use:N \l_tmpb_seq
  }
  {
  \seq_clear:N \l_tmpa_seq
  \seq_set_from_clist:Nn \l_tmpa_seq {#1}%
  \seq_set_map:NNn \l_tmpb_seq \l_tmpa_seq {
  	\exp_not:n {
  		\group_begin:
      \@@_getvalueforkey:Nnnnn{\theProjectNumber}{number}{project}{id}{##1}
  		\datatool_if_null:NTF {\theProjectNumber}
  		{ \getEntry[project]{##1}{number} %<- just to get the error message 
  			\textcolor{error}{\texttt{<##1>}}
  		}{
  			\bfseries%
  			\getProjectColor{##1}%
        \@@_project_if_reference_only:nTF {##1}
        {
          \bool_if:NTF \l_@@_project_custom_text_bool
            {#2}
            {\dfgShowTag{##1}{number}{\theProjectNumber}[project]}%
          \@@_project_reference_only_indicator:
        }
        {
          \bool_if:NTF \l_@@_project_custom_text_bool
          {
            \bool_if:NTF \l_@@_class_cv_bool
              { #2 }
              { \hyperlink{project:##1}{#2} }
          }
          {
            \bool_if:NTF \l_@@_class_cv_bool
              { \dfgShowTag{##1}{number}{\theProjectNumber}[project] }
              { \hyperlink{project:##1}
                  {\dfgShowTag{##1}{number}{\theProjectNumber}[project]} }
          }
        }
  		}
  		\group_end:
  	}}%
  \@@_project_reference_seq_use:N \l_tmpb_seq
  }
}

\NewDocumentCommand{\getProject}{s m o}
{
  \IfBooleanTF{#1}
    { \@@_get_project_compact:nn {#2} {#3} }
    {
      \bool_if:NTF \l_@@_custom_project_pi_once_per_section_bool
        { \@@_get_project_with_people:nnn {\BooleanFalse} {#2} {#3} }
        { \@@_get_project_compact:nn {#2} {#3} }
    }
}

\int_new:N \g_@@_project_count_all_int
\prop_new:N \g_@@_project_count_area_prop
\tl_new:N  \l_@@_project_count_id_tl
\tl_new:N  \l_@@_project_count_area_tl
\tl_new:N  \l_@@_project_count_status_tl
\tl_new:N  \l_@@_project_count_consider_for_lists_tl
\tl_new:N  \l_@@_project_count_reference_only_tl

\cs_new_protected:Npn \@@_project_count_increment:n #1
{
  \int_gincr:N \g_@@_project_count_all_int
  \tl_set:Nx \l_tmpa_tl { \tl_upper_case:n {#1} }
  \prop_get:NVNTF \g_@@_project_count_area_prop
    \l_tmpa_tl \l_tmpb_tl
    {
      \prop_gput:NVx \g_@@_project_count_area_prop \l_tmpa_tl
        { \int_eval:n { \l_tmpb_tl + 1 } }
    }
    { \prop_gput:NVn \g_@@_project_count_area_prop \l_tmpa_tl { 1 } }
}

\cs_new_protected:Npn \@@_project_count_build:
{
  \int_gzero:N \g_@@_project_count_all_int
  \prop_gclear:N \g_@@_project_count_area_prop
  \DTLifdbexists{project}
  {
    \DTLifhaskey { project } { project-area }
      { }
      { \DTLaddcolumn { project } { project-area } }
    \DTLforeach*{project}
    {
      \l_@@_project_count_id_tl                 = id,
      \l_@@_project_count_area_tl               = project-area,
      \l_@@_project_count_status_tl             = project-status,
      \l_@@_project_count_consider_for_lists_tl = consider-for-lists,
      \l_@@_project_count_reference_only_tl     = reference-only
    }
    {
      \bool_lazy_all:nT
      {
        { \str_if_eq_p:Vn \l_@@_project_count_consider_for_lists_tl { true } }
        { \str_if_eq_p:Vn \l_@@_project_count_reference_only_tl { false } }
        {
          \bool_lazy_or_p:nn
            { \str_if_eq_p:Vn \l_@@_project_count_status_tl { C } }
            { \str_if_eq_p:Vn \l_@@_project_count_status_tl { N } }
        }
      }
      {
        \DTLifnullorempty{\l_@@_project_count_area_tl}
          {
            \tl_set:Nx \l_@@_project_count_area_tl
              { \tl_head:V \l_@@_project_count_id_tl }
          }
          { }
        \tl_trim_spaces:N \l_@@_project_count_area_tl
        \exp_args:NV \@@_project_count_increment:n
          \l_@@_project_count_area_tl
      }
    }
  }
  { \msg_warning:nnn { dfg } { database-not-found } { project } }
  \bool_gset_true:N \g_@@_project_count_ready_bool
}

\NewDocumentCommand{\getProjectCount}{o}
{
  \bool_if:NF \g_@@_project_count_ready_bool
    { \@@_project_count_build: }
  \dfgShowCalculatedTag{getProjectCount}{project}
  {
    \IfNoValueTF{#1}
      { \int_use:N \g_@@_project_count_all_int }
      {
        \tl_set:Nx \l_tmpa_tl { \tl_upper_case:n {#1} }
        \prop_get:NVNTF \g_@@_project_count_area_prop
          \l_tmpa_tl \l_tmpb_tl
          { \tl_use:N \l_tmpb_tl }
        {
          \msg_warning:nnn { dfg } { invalid-project-count-area } {#1}
          0
        }
      }
  }
}
\clist_new:N \l_@@_person_project_clist
\clist_new:N \l_@@_project_id_clist
\clist_new:N \l_@@_project_number_clist
\bool_new:N \l_@@_suppress_deprecated_project_pi_warning_bool
% Global flags keep repeated calls and table measurement groups quiet.
\bool_new:N \g_@@_warned_get_pi_project_bool
\bool_new:N \g_@@_warned_get_project_pi_bool
\seq_new:N \l_@@_project_pi_with_project_seq
\msg_new:nnn {dfg} {deprecated-get-pi-project}
  {Command~\token_to_str:N \getPIProject \c_space_tl is~deprecated;~use~\token_to_str:N \getPIWithProject.}
\msg_new:nnn {dfg} {deprecated-get-project-pi}
  {Command~\token_to_str:N \getProjectPI \c_space_tl is~deprecated;~use~\token_to_str:N \getProjectWithPI.}

\NewDocumentCommand{\getPIProject}{s m}{
  \bool_if:NF \l_@@_suppress_deprecated_project_pi_warning_bool
    {
      \bool_if:NF \g_@@_warned_get_pi_project_bool
        {
          \bool_gset_true:N \g_@@_warned_get_pi_project_bool
          \msg_warning:nn {dfg}{deprecated-get-pi-project}
        }
    }
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \dfgFastReference{#2} }
  {
  %
  %  • Argument #1  (optional *-star)
  %      – if present, the PI’s *first name* is printed before the last name;
  %        if the star is omitted only the last name is printed.
  %
  %  • Argument #2  (mandatory)
  %      – a comma‑separated list of *person‑IDs* (the field “id” in your
  %        “person” datatool table).
  %        Example:  `\getPIProject*{per1,per2}`.
  %
  %  What the macro does (high‑level description)
  %  --------------------------------------------------------------
  %  1. Turns the comma list #2 into a clist:   \l_@@_person_id_clist
  %  2. For **each** person‑ID in that clist it builds an
  %     “author block” consisting of
  %        • a coloured, bold hyperlink to the PI’s entry, and
  %        • the list of projects (formatted by \getProject*) that are
  %          attached to that PI.
  %  3. All author blocks are collected in a second clist
  %     \l_@@_person_project_clist.
  %  4. Finally the blocks are printed in an *Oxford‑comma* style
  %     using \clist_use:Nnnn.
  %
  %  Internal containers (all declared elsewhere with \clist_new:N)
  %  --------------------------------------------------------------
  %    \l_@@_person_id_clist          – list of the IDs passed in #2
  %    \l_@@_person_project_clist     – the final list of “author blocks”
  %    \l_@@_project_id_clist         – temporary clist that stores the raw
  %                                      CSV string returned by the DB field
  %                                      `ref‑project‑id` for the current PI.
  %    \l_@@_project_number_clist      – coloured project numbers for the
  %                                      current PI (built by the inner loop).
  %    \l_@@_project_id_clist (re‑used) – holds the CSV string before it is
  %                                      split into \l_@@_project_id_clist.
  %    \l_tmpa_clist                  – loop variable used by
  %                                      \clist_map_variable:NNn (holds a *single*
  %                                      project‑ID during the inner loop).
  %
  %---------------------------------------------------------------------
  %  Detailed walk‑through of the code
  %---------------------------------------------------------------------
  %---------------------------------------------------------------
  %   0.  Initialise the containers
  %---------------------------------------------------------------
  % #2 is a comma‑separated list of person IDs → turn it into a clist
  \clist_set:Nn \l_@@_person_id_clist {#2}
  % containers that will be filled later
  \clist_clear:N \l_@@_person_project_clist
  \clist_clear:N \l_@@_project_id_clist   % (used as a *scratch* clist)

  %---------------------------------------------------------------
  %   1.  Outer loop – one iteration per PI
  %---------------------------------------------------------------
  \clist_map_inline:Nn \l_@@_person_id_clist
  {               % ##1 = the current person ID
  	%---------------------------------------------------------
  	%   a)  Build the *author name* (hyperlinked, coloured,
  	%       bold).  We wrap everything in \exp_not:n so that the
  	%       whole fragment is **not expanded now** – it will be
  	%       expanded later when the final clist is printed.
  	%---------------------------------------------------------
  	\clist_put_right:Nn \l_@@_person_project_clist {
  		\clist_clear:N   \l_@@_project_number_clist
  		\IfBooleanTF{#1}
  		{\getPI*{##1}}
  		{\getPI{##1}}
  		%---------------------------------------------------------
  		%   b)  Pull the raw CSV string that contains *all* project
  		%       IDs belonging to this PI.
  		%---------------------------------------------------------
      \@@_getvalueforkey:Nnnnn{\l_@@_project_id_clist}
  		{ref-project-id}
  		{person}{id}{##1}

  		%---------------------------------------------------------
  		%   c)  Print the project list inside parentheses.
  		%       The raw CSV string is *still* a token list; we turn it
  		%       into a clist by using the special “variable” version of
  		%       \clist_map_… which gives us a temporary clist variable
  		%       (\l_tmpa_clist) that holds *one* project ID at a time.
  		%---------------------------------------------------------
  		\space(
  		\clist_map_variable:NNn \l_@@_project_id_clist \l_tmpa_clist {
  			% ##1 (here called \l_tmpa_clist) is a single project ID.
        % Keep project references compact: the PI name is already printed.
  			\clist_put_right:Ne \l_@@_project_number_clist {
          \getProject*{\l_tmpa_clist}
  			}
  		}
  		% finally print the list of coloured project numbers, separated
  		% by a thin space + comma
  		\clist_use:Nn \l_@@_project_number_clist  {\addnbthinspace/\addthinspace}
  		)
  	}   % end of \clist_put_right:Nn  (one author block)
  } % end of outer \clist_map_inline:Nn

  %---------------------------------------------------------------
  %   2.  Typeset the collected author blocks.
  %       \clist_use:Nnnn joins the items with
  %          “~and~”   for the *last* separator,
  %          “,~”      for the *middle* separators,
  %          “,~and~”  for the *penultimate* separator
  %---------------------------------------------------------------
  \clist_use:Nnnn \l_@@_person_project_clist {~and~} {,~} {,~and~}%
  }
}

\clist_new:N \l_@@_person_clist

% Track which projects have already had their PI names expanded by either
% \cs{getProject} or \cs{getProjectPI} in the current section. Chapter
% boundaries also clear the state so references before the first section of a
% new chapter cannot inherit the preceding section's state.
\prop_new:N \g_@@_project_pi_seen_prop
\cs_new_protected:Npn \@@_project_pi_seen_clear:
  { \prop_gclear:N \g_@@_project_pi_seen_prop }
\AddToHook{cmd/chapter/before}[dfg/project-pi-once-per-section]
  { \@@_project_pi_seen_clear: }
\AddToHook{cmd/section/before}[dfg/project-pi-once-per-section]
  { \@@_project_pi_seen_clear: }

% PI details are never appended to reference-only projects, the project
% currently being typeset, or references inside generated tables and lists.
% Otherwise the customization setting selects either the former always-expanded
% \cs{getProjectPI} behaviour or one shared expansion per project and section.
\prg_new_protected_conditional:Npnn \@@_project_pi_if_show_people:n #1
  { T,F,TF }
{
  \@@_project_if_reference_only:nTF {#1}
    { \prg_return_false: }
    {
      \tl_if_eq:VnTF \l__tmp_current_project_tl {#1}
        { \prg_return_false: }
        {
          \bool_if:nTF
            {
              \g_@@_tblr_inside_bool
              || \l_@@_former_project_compact_bool
            }
            { \prg_return_false: }
            {
              \bool_if:NTF \l_@@_custom_project_pi_once_per_section_bool
              {
                \prop_if_in:NnTF \g_@@_project_pi_seen_prop {#1}
                  { \prg_return_false: }
                  {
                    \prop_gput:Nnn \g_@@_project_pi_seen_prop {#1} { }
                    \prg_return_true:
                  }
              }
              { \prg_return_true: }
            }
        }
    }
}

\cs_new_protected:Npn \@@_get_project_with_people:nnn #1#2#3
{
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  { \@@_get_project_compact:nn {#2} {#3} }
  {
  \group_begin:
  % Project-first references use lastnames by default regardless of the
  % global PIReferenceFirstName setting. The explicit star still selects full
  % names through the starred \getPI call below.
  \bool_set_false:N \l_@@_custom_pi_reference_firstname_bool
  %-----------------------------------------------------------------
  % 0.  Initialise the containers we are going to use.
  %-----------------------------------------------------------------
  %   #2 is a comma‑separated list of *project* IDs → turn it into a clist.
  \clist_set:Nn \l_@@_project_id_clist {#2}
  %   These three clists will be filled during the loops.
  \clist_clear:N \l_@@_person_project_clist   % final result: “project → PI list”
  \clist_clear:N \l_@@_person_id_clist        % temporary list of PIs for one project
  \clist_clear:N \l_@@_person_clist           % temporary list of formatted PI names

  %-----------------------------------------------------------------
  % 1.  Outer loop – one iteration per *project* ID.
  %-----------------------------------------------------------------
  \clist_map_inline:Nn \l_@@_project_id_clist
  {
  	% ##1 = the current project ID
  	%-------------------------------------------------------------
  	%   a)  Put the *project number* (coloured) at the beginning
  	%       of the block that will be stored in
  	%       \l_@@_person_project_clist.
  	%-------------------------------------------------------------
  	\clist_put_right:Nn \l_@@_person_project_clist
  	{%
  		% Reset the per‑project temporaries before we start filling them.
  		\clist_clear:N \l_@@_person_clist
  		\clist_clear:N \l_@@_person_id_clist

		% The coloured project number (e.g. “\color{blue}{12}”)
		\@@_get_project_compact:nn {##1} {#3}

		% Reference-only projects and the current project remain compact. For
		% other projects, the customization setting determines whether PI names
		% are always shown or only on the first reference in this section.
    \@@_project_pi_if_show_people:nT {##1}
    {
		%---------------------------------------------------------
		%   b)  Retrieve the *raw* CSV string that contains all
  		%       person IDs attached to this project.
  		%---------------------------------------------------------
      \@@_getvalueforkey:Nnnnn
  		{\l_@@_person_id_clist}      % ← will receive something like “per1,per3”
  		{ref-person-id}              % field name in the “project” table
  		{project}{id}{##1}           % look it up for the current project

  		%---------------------------------------------------------
  		%   c)  Build the *list of PI names* for this project.
  		%       We use the “variable” version of \clist_map which
  		%       gives us a temporary clist variable (\l_tmpa_clist)
  		%       that holds a *single* person ID at each iteration.
  		%---------------------------------------------------------
  		\space(%
  		\clist_map_variable:NNn \l_@@_person_id_clist \l_tmpa_clist
  		{
  			% \l_tmpa_clist now expands to one person ID.
  			% We format it with \getPI (or \getPI* if the star was given).
  			\clist_put_right:Ne \l_@@_person_clist
  			{
  				\IfBooleanTF{#1}
  				{\getPI*{\l_tmpa_clist}}
  				{\getPI{\l_tmpa_clist}}
  			}
  		}
  		%---------------------------------------------------------
  		%   d)  Print the formatted PI list, separating consecutive
  		%       names with a thin slash (the macro \addnbthinspace and
  		%       \addthinspace are assumed to be defined elsewhere).
  		%---------------------------------------------------------
		\clist_use:Nn \l_@@_person_clist {\addnbthinspace/\addthinspace}
		  ) % end of the parentheses that surround the PI list
		}
	}   % end of \clist_put_right:Nn   (one *project block*)
  } % end of outer \clist_map_inline:Nn

  %-----------------------------------------------------------------
  % 2.  Typeset the collected project blocks.
  %     \clist_use:Nnnn joins the items with
  %        “~and~”   for the *last* separator,
  %        “,~”      for the *middle* separators,
  %        “,~and~”  for the *penultimate* separator.
  %-----------------------------------------------------------------
  \@@_project_reference_clist_use:N \l_@@_person_project_clist
  \group_end:
  }
}

\NewDocumentCommand{\getPIWithProject}{s m}
{
  \group_begin:
  \bool_set_true:N \l_@@_suppress_deprecated_project_pi_warning_bool
  \IfBooleanTF{#1}{\getPIProject*{#2}}{\getPIProject{#2}}
  \group_end:
}

\NewDocumentCommand{\getProjectPI}{s m}
  {
    \bool_if:NF \l_@@_suppress_deprecated_project_pi_warning_bool
      {
        \bool_if:NF \g_@@_warned_get_project_pi_bool
          {
            \bool_gset_true:N \g_@@_warned_get_project_pi_bool
            \msg_warning:nn {dfg}{deprecated-get-project-pi}
          }
      }
    \exp_args:NnnV \@@_get_project_with_people:nnn
      {#1} {#2} \c_novalue_tl
  }
\NewDocumentCommand{\getProjectWithPI}{s m}
{
  \group_begin:
  \bool_set_true:N \l_@@_suppress_deprecated_project_pi_warning_bool
  \IfBooleanTF{#1}{\getProjectPI*{#2}}{\getProjectPI{#2}}
  \group_end:
}

\NewDocumentCommand{\getPIOfProjectWithProject}{s m}
{
  \seq_clear:N \l_@@_project_pi_with_project_seq
  \clist_map_inline:nn {#2}
  {
    \seq_put_right:Nn \l_@@_project_pi_with_project_seq
    {
      \IfBooleanTF{#1}
        {\getPIofProject*{##1}}
        {\getPIofProject{##1}}
      \space(\getProject*{##1})
    }
  }
  \@@_project_reference_seq_use:N \l_@@_project_pi_with_project_seq
}
%    \end{macrocode}
% We also need a way to extract all PIs of a project. 
%    \begin{macrocode}
% The star defaults to full names and a prose list; explicit properties still
% override the default. A starred delimiter overrides only the final join.
\clist_new:N \l_@@_project_pi_properties_clist
\tl_new:N \l_@@_project_pi_name_tl
\NewDocumentCommand{\getPIofProject}{s o m o}
{
  \group_begin:
  \IfNoValueTF{#2}
    {
      \bool_if:NTF \l_@@_custom_pi_reference_firstname_bool
        {\clist_set:Nn \l_@@_project_pi_properties_clist {firstname,lastname}}
        {
          \IfBooleanTF{#1}
            {\clist_set:Nn \l_@@_project_pi_properties_clist {firstname,lastname}}
            {\clist_set:Nn \l_@@_project_pi_properties_clist {lastname}}
        }
    }
    {\clist_set:Nn \l_@@_project_pi_properties_clist {#2}}
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
    {\@@_fast_project_reference:n {#3}}
    {
      \clist_clear:N \l_@@_person_clist
      \@@_getvalueforkey:Nnnnn{\l_@@_person_id_clist}
        {ref-person-id}{project}{id}{#3}
      \DTLifnullorempty{\l_@@_person_id_clist}
        {\clist_clear:N \l_@@_person_id_clist}{}
      \clist_map_variable:NNn \l_@@_person_id_clist \l_tmpa_clist
        {
          \@@_getvalueforkey:Nnnnn{\tmpPIacademicdegree}{academicdegree}{person}{id}{\l_tmpa_clist}
          \@@_getvalueforkey:Nnnnn{\tmpPIfirstname}{firstname}{person}{id}{\l_tmpa_clist}
          \@@_getvalueforkey:Nnnnn{\tmpPIlastname}{lastname}{person}{id}{\l_tmpa_clist}
          \tl_clear:N \l_@@_project_pi_name_tl
          \clist_if_in:NnT \l_@@_project_pi_properties_clist {academicdegree}
            {
              \tl_put_right:Ne \l_@@_project_pi_name_tl
                {\dfgShowTag{\l_tmpa_clist}{academicdegree}{\tmpPIacademicdegree}[person]\addnbthinspace}
            }
          \clist_if_in:NnT \l_@@_project_pi_properties_clist {firstname}
            {
              \tl_put_right:Ne \l_@@_project_pi_name_tl
                {\dfgShowTag{\l_tmpa_clist}{firstname}{\tmpPIfirstname}[person]\space}
            }
          \clist_if_in:NnT \l_@@_project_pi_properties_clist {lastname}
            {
              \tl_put_right:Ne \l_@@_project_pi_name_tl
                {\dfgShowTag{\l_tmpa_clist}{lastname}{\tmpPIlastname}[person]}
            }
          % Reuse getPI's target, reference styling, and missing-person handling.
          % Freeze the ID and selected fields before advancing the metadata loop.
          \tl_if_empty:NF \l_@@_project_pi_name_tl
            {
              \clist_put_right:Ne \l_@@_person_clist
                {
                  \exp_not:N \getPI {\exp_not:V \l_tmpa_clist}
                    [\exp_not:V \l_@@_project_pi_name_tl]
                }
            }
        }
      \IfBooleanTF{#1}
        {
          \IfNoValueTF{#4}
            {\clist_use:Nnnn \l_@@_person_clist {~and~} {,~} {~and~}}
            {\clist_use:Nnnn \l_@@_person_clist {#4} {,~} {#4}}
        }
        {
          \IfNoValueTF{#4}
            {\clist_use:Nn \l_@@_person_clist {\,/\,}}
            {\clist_use:Nn \l_@@_person_clist {#4}}
        }
    }
  \group_end:
}
%    \end{macrocode}
% PI and project references also accept an all-lowercase command spelling.
% Copy the complete command so stars, optional arguments, and legacy warnings
% follow the canonical implementation without a separate argument parser.
%    \begin{macrocode}
\clist_map_inline:nn
  {
    getPI, getPIsWithRole, getProject, getProjectColor, getProjectCount,
    getPIWithProject, getProjectWithPI, getPIOfProjectWithProject,
    getPIofProject, getPIProject, getProjectPI
  }
  { \cs_new_eq:cc { \str_lowercase:n {#1} } {#1} }
% Common mixed-case spellings retained alongside the lowercase aliases.
\cs_new_eq:NN \getPIwithProject \getPIWithProject
\cs_new_eq:NN \getProjectwithPI \getProjectWithPI
\cs_new_eq:NN \getPIOfProject \getPIofProject
%    \end{macrocode}
% For referencing Aims we need to define a new macro.
%    \begin{macrocode}
\clist_new:N \l_@@_aim_refs_clist
\NewDocumentCommand{\getAim}{O{\l__tmp_current_project_tl} m}
{
  % #1: current project
  % #2: id of aim(s)
  \clist_clear:N \l_@@_aim_refs_clist
  \clist_map_inline:nn { #2 }
  { \clist_put_right:Nn \l_@@_aim_refs_clist { #1-aim-##1 } }
  \exp_args:NV \cref \l_@@_aim_refs_clist
}
%    \end{macrocode}
% For work-package references, \cs{labelcref} keeps cleveref's sorting and
% ranges while we provide a narrow, unbreakable space after |WP| or |WPs|.
%    \begin{macrocode}
\tl_new:N \l__tmp_current_project_tl
\clist_new:N \l_@@_wp_refs_clist
\NewDocumentCommand{\getWP}{O{\l__tmp_current_project_tl} m}
{
  % #1: current project
  % #2: id of workpackage(s)
  \clist_clear:N \l_@@_wp_refs_clist
  \clist_map_inline:nn { #2 }
  { \clist_put_right:Nn \l_@@_wp_refs_clist { #1-wp-##1 } }
  \textcolor{referenceWP}
    {\textbf{WP\int_compare:nNnF
      { \clist_count:N \l_@@_wp_refs_clist } = { 1 } { s }}}
  \addnbthinspace
  \exp_args:NV \labelcref \l_@@_wp_refs_clist
}
%    \end{macrocode}
% \paragraph{Work-package metadata normalization}
% The public WP keys separate narrative titles from chart-specific options.
% Collect legacy and new values separately, without expanding their contents;
% merge only after parsing so new keys win regardless of their source order.
% Property membership distinguishes omission from an explicitly empty value.
% Legacy-only declarations pass through verbatim, preserving absent fields,
% validation, database column order and existing output. New declarations are
% normalized into the same Gantt fields; direct \cs{addEntry} callers and all
% downstream readers therefore keep the established database schema.
% Unknown outer keys are forwarded to the original Gantt parser, including its
% diagnostics and the focused-mode behaviour when no database is requested.
%    \begin{macrocode}
\RequirePackage{dfg-gantt}
% Direct package commands and class dispatch share the same live defaults,
% including settings changed locally through either public setup command.
\cs_set:Npn \__dfgplots_defaults:n #1
  {
    \exp_not:V \l_@@_custom_plot_options_tl,
    \str_if_eq:nnTF {#1}{gantt}
      {\exp_not:V \l_@@_custom_gantt_plot_options_tl}
      {\exp_not:V \l_@@_custom_collaboration_plot_options_tl}
  }
\keys_define:nn {dfgplots/setup}
  {plotOptions .meta:nn = {dfg/custom}{plotOptions={#1}},
   ganttPlotOptions .meta:nn = {dfg/custom}{ganttPlotOptions={#1}},
   collaborationPlotOptions .meta:nn = {dfg/custom}{collaborationPlotOptions={#1}}}
\RenewDocumentCommand \DFGGanttLabel {mm}{\getWP[#1]{#2}}
\RenewDocumentCommand \DFGGanttTag {mmmm}{\dfgShowTag{#1}{#2}{#3}[#4]}
\RenewDocumentCommand{\dfgGanttShowQs}{mm}{%
  \bool_if:NTF \l__dfg_class_showtags_bool
  {\leavevmode\vbox to\z@{{%
        \vss\color{color@tags@line}
        \rlap{\vrule\raise .9em%
          \hbox{{%
              \fontsize{4}{0}\selectfont%
              \ttfamily\,#1:#2}}}}}
    \textcolor{color@tags@font}{#1}}
  {#1}
}
\cs_new_protected:Npn \@@_workpackage_store:nn #1#2
  { \addEntry[gantt]{gantt-\l__tmp_current_project_tl}{id=#1,#2} }
%    \end{macrocode}
% \cs{addWP} must be called within |workpackages|. Its focused-mode heading
% parser reads the same normalized keys even when images are disabled and no
% Gantt database is loaded. It retains the existing blank-title ID fallback.
%    \begin{macrocode}
\tl_new:N \l_@@_fast_workpackage_name_tl
\keys_define:nn { dfg / fast-workpackage }
{
  name .tl_set:N = \l_@@_fast_workpackage_name_tl,
  unknown .code:n = { }
}

% A nested workpackage starts directly with its authored body; its list label
% already supplies the required separation.  Remove only the immediately
% following spaces and paragraph tokens, without adding interword space.  Later
% paragraph breaks in the authored body remain untouched.
\cs_new_protected:Npn \@@_start_subworkpackage_body:
{
  \peek_meaning_remove_ignore_spaces:NTF \par
    { \@@_start_subworkpackage_body: }
    { \ignorespaces }
}

% The visible sub-workpackage label contains its parent number, but enumitem's
% child counter restarts for every parent.  Cleveref otherwise sees, for
% example, both WP 1b and WP 2b as child counter 2 and can discard the latter
% while sorting or compress a range across two parents.  Store the parent
% counter as Cleveref's numeric prefix so sorting and range detection respect
% the work-package hierarchy.
\RenewDocumentCommand{\addWP}{ m m }{
  % #1: workpackage-id
  % #2: key-set
  \@@_workpackage_normalize:n {#2}
  \bool_if:NTF \l_@@_class_fastcompile_project_bool
  {
    \tl_clear:N \l_@@_fast_workpackage_name_tl
    \exp_args:NnV \keys_set:nn { dfg / fast-workpackage }
      \l_@@_wp_normalized_tl
    \bool_if:NT \l_@@_class_fastcompile_project_show_images_bool
      {
        \exp_args:NnV \@@_workpackage_store:nn {#1}
          \l_@@_wp_normalized_tl
      }
  }
  {
    \exp_args:NnV \@@_workpackage_store:nn {#1}
      \l_@@_wp_normalized_tl
  }
  \str_if_eq:eeTF { \@enumctr } { workpackagesi }
  {
    \bool_if:NTF \l_@@_class_fastcompile_project_bool
    {
      \item \textbf{
        \tl_if_blank:VTF \l_@@_fast_workpackage_name_tl
        { WP~#1 }
        { \tl_use:N \l_@@_fast_workpackage_name_tl }
      }%
    }
    {
      \item \textbf{\getEntry[gantt-\l__tmp_current_project_tl]{#1}{name}}%
    }
  }
  { \item }
  \label{\l__tmp_current_project_tl-wp-#1}%
  \str_if_eq:eeF { \@enumctr } { workpackagesi }
    { \@@_start_subworkpackage_body: }
}
%    \end{macrocode}
% Project collaborations are stored with each project as an undirected list.
% The default plot is a compact focus heatmap containing every active project;
% the focus and its direct collaborators are highlighted.  An arc layout uses
% the same ordered nodes, draws only the focus project's edges, and gives every
% edge the same peak height.  It prints identifiers inside uniformly sized
% nodes and places unlabelled project-area rules directly below them.  Heatmap
% rows and colors are generated dynamically from |project-area| (with the
% project-ID prefix as fallback); a rotating palette supports any number of
% areas.  Boxes use a shared dynamic column width determined by the widest
% project area, so the grid fills the complete text block after its area labels.  Both
% layouts are deterministic, are generated entirely with TikZ, and omit ending,
% reference-only, and list-excluded projects.
% The built-in area palette cycles when more areas are present than palette
% entries; existing A, B, and Q projects retain their familiar colors.
%    \begin{macrocode}
\RequirePackage{dfg-collaboration}
\keys_define:nn {dfgcollab/setup}
  {area-colors .code:n =
    {\tl_set:Nn\l__dfgcollab_colors_tl{#1}
     \changeSettings{collaborationAreaColors={#1}}},
   area-palette .code:n =
    {\clist_if_empty:nF{#1}
      {\tl_set:Nn\l__dfgcollab_palette_tl{#1}
       \changeSettings{collaborationAreaPalette={#1}}}}}
\cs_new_protected:Npn \__dfg_collaboration_plot_collect_nodes:
{
  \seq_clear:N  \l__dfg_collaboration_plot_nodes_seq
  \prop_clear:N \l__dfg_collaboration_plot_all_status_prop
  \prop_clear:N \l__dfg_collaboration_plot_status_prop
  \prop_clear:N \l__dfg_collaboration_plot_lists_prop
  \prop_clear:N \l__dfg_collaboration_plot_edges_prop
  \prop_clear:N \l__dfg_collaboration_plot_area_prop
  % DATATOOL requires an iterated key to exist as a database column.  Older
  % proposals do not have project-area yet, so create the optional column and
  % let the ID-prefix fallback below handle its empty values.
  \DTLifhaskey { project } { project-area }
    { }
    { \DTLaddcolumn { project } { project-area } }
  \DTLifhaskey { project } { collaborations }
    { }
    { \DTLaddcolumn { project } { collaborations } }
  \DTLforeach*{project}
  {
    \l__dfg_collaboration_plot_id_tl = id,
    \l__dfg_collaboration_plot_status_tl = project-status,
    \l__dfg_collaboration_plot_consider_tl = consider-for-lists,
    \l__dfg_collaboration_plot_reference_only_tl = reference-only,
    \l__dfg_collaboration_plot_area_tl = project-area,
    \l__dfg_collaboration_plot_collaborations_tl = collaborations
  }
  {
    \prop_put:NVV \l__dfg_collaboration_plot_all_status_prop
      \l__dfg_collaboration_plot_id_tl
      \l__dfg_collaboration_plot_status_tl
    \bool_lazy_all:nT
    {
      { \str_if_eq_p:Vn \l__dfg_collaboration_plot_consider_tl { true } }
      { \str_if_eq_p:Vn \l__dfg_collaboration_plot_reference_only_tl { false } }
      {
        \bool_lazy_or_p:nn
          { \str_if_eq_p:Vn \l__dfg_collaboration_plot_status_tl { C } }
          { \str_if_eq_p:Vn \l__dfg_collaboration_plot_status_tl { N } }
      }
    }
    {
      \DTLifnullorempty{\l__dfg_collaboration_plot_collaborations_tl}
        { \tl_clear:N \l__dfg_collaboration_plot_collaborations_tl }
        { }
      \seq_put_right:NV \l__dfg_collaboration_plot_nodes_seq
        \l__dfg_collaboration_plot_id_tl
      \DTLifnullorempty{\l__dfg_collaboration_plot_area_tl}
        { \tl_set:Nx \l__dfg_collaboration_plot_area_tl
            { \tl_head:V \l__dfg_collaboration_plot_id_tl } }
        { }
      \tl_trim_spaces:N \l__dfg_collaboration_plot_area_tl
      \prop_put:NVV \l__dfg_collaboration_plot_area_prop
        \l__dfg_collaboration_plot_id_tl \l__dfg_collaboration_plot_area_tl
      \prop_put:NVV \l__dfg_collaboration_plot_status_prop
        \l__dfg_collaboration_plot_id_tl
        \l__dfg_collaboration_plot_status_tl
      \prop_put:NVV \l__dfg_collaboration_plot_lists_prop
        \l__dfg_collaboration_plot_id_tl
        \l__dfg_collaboration_plot_collaborations_tl
    }
  }
  \seq_sort:Nn \l__dfg_collaboration_plot_nodes_seq
  {
    \prop_get:NnN \l__dfg_collaboration_plot_area_prop {##1} \l_tmpa_tl
    \prop_get:NnN \l__dfg_collaboration_plot_area_prop {##2} \l_tmpb_tl
    \str_compare:eNeTF
      { \tl_use:N \l_tmpa_tl / ##1 }
      <
      { \tl_use:N \l_tmpb_tl / ##2 }
      { \sort_return_same: }
      { \sort_return_swapped: }
  }
}

\NewDocumentCommand{\ProjectCollaborationPlot}{ O{} m o }
{%
  \group_begin:
  % Capture the normal body width before hvfloat builds the caption.
  \dim_set:Nn \l_@@_collaboration_plot_width_dim { \textwidth }
  \exp_args:NNV \prop_set_from_keyval:Nn
    \l_@@_collaboration_plot_area_color_override_prop
    \l_@@_custom_collaboration_area_colors_tl
  \exp_args:NNV \seq_set_from_clist:Nn
    \l_@@_collaboration_plot_area_palette_seq
    \l_@@_custom_collaboration_area_palette_tl
  \tl_clear:N \l_@@_collaboration_plot_caption_tl
  \__dfgcollab_reset:
  \@@_plot_options_set:nNn { project-collaboration-plot }
    \l_@@_custom_collaboration_plot_options_tl {#1}
  \IfNoValueF{#3}
    { \tl_set:Nn \l_@@_collaboration_plot_caption_tl {#3} }
  \tl_set:Nn \l_@@_collaboration_plot_focus_tl {#2}
  \tl_trim_spaces:N \l_@@_collaboration_plot_focus_tl
  \DTLifdbexists{project}
  {
    \@@_collaboration_plot_collect_nodes:
    \__dfgcollab_select:
    \prop_if_in:NVTF \l_@@_collaboration_plot_status_prop
      \l_@@_collaboration_plot_focus_tl
    {
      \@@_collaboration_plot_collect_edges:
      \@@_collaboration_plot_prepare:
      \tl_if_blank:VTF \l_@@_collaboration_plot_caption_tl
      {%
        \@@_plot_float:
        {figure}
        {\@@_collaboration_plot_full_width_picture:}
        {Collaborations~of~\getProject{#2}.}
        {fig:project-collaboration-#2-
          \tl_use:N \l_@@_collaboration_plot_layout_tl}%
      }
      {%
        \@@_plot_float:
        {figure}
        {\@@_collaboration_plot_full_width_picture:}
        {Collaborations~of~\getProject{#2}.~
          \tl_use:N \l_@@_collaboration_plot_caption_tl}
        {fig:project-collaboration-#2-
          \tl_use:N \l_@@_collaboration_plot_layout_tl}%
      }
    }
    {
      \msg_warning:nne { dfg } { collaboration-focus-not-found }
        { \l_@@_collaboration_plot_focus_tl }
      \textcolor{error}
        {Project~collaboration~plot:~unknown~project~'#2'.}
    }
  }
  { \msg_warning:nnn { dfg } { database-not-found } { project } }
  \group_end:
}

% Since the workpackage is closely related to the Gantt chart we continue with
% that.  \cs{GanttPlot} is the plot dispatcher's target.  The old
% \cs{printGantt} spelling remains as a compatibility wrapper.
\tl_new:N \l_@@_gantt_plot_caption_tl
\keys_define:nn { dfg / gantt-plot }
{
  slots .meta:nn = {dfggantt/chart}{slots=#1},
  first-quarter .meta:nn = {dfggantt/chart}{first-quarter=#1},
  year-labels .meta:nn = {dfggantt/chart}{year-labels={#1}},
  caption .tl_set:N = \l_@@_gantt_plot_caption_tl,
}

\NewDocumentCommand{\GanttPlot}{ O{} m o }
{
  \group_begin:
  \tl_clear:N \l_@@_gantt_plot_caption_tl
  \@@_plot_options_set:nNn { gantt-plot }
    \l_@@_custom_gantt_plot_options_tl {#1}
  \IfNoValueF{#3}
    { \tl_set:Nn \l_@@_gantt_plot_caption_tl {#3} }
  \DTLifdbexists{gantt-#2}
  {
    \tl_if_blank:VTF \l_@@_gantt_plot_caption_tl
    {%
      \@@_plot_float:
      {figure}
      {\dfgGanttEnvironment{#2}}
      {Gantt~chart~of~\getProject{#2}.}
      {fig:gantt-#2}%
    }
    {%
      \@@_plot_float:
      {figure}
      {\dfgGanttEnvironment{#2}}
      {Gantt~chart~of~\getProject{#2}.~
        \tl_use:N \l_@@_gantt_plot_caption_tl}
      {fig:gantt-#2}%
    }
  }
  {
    Database~ \texttt{gantt-#2}~ missing.
    \msg_warning:nne { dfg } { database-not-found }{ gantt-#2 }
  }
  \group_end:
}

% Lowercase plot names accept either an explicit project ID or the active
% project.  An explicit ID may carry a trailing caption; the current-project
% form uses the caption key instead.
\cs_new_protected:Npn \@@_typed_plot:nnnn #1#2#3#4
{
  \IfNoValueTF{#4}
    { #1[#2]{#3} }
    { #1[#2]{#3}[#4] }
}
\cs_new_protected:Npn \@@_typed_plot_current:nnnn #1#2#3#4
  { \@@_typed_plot:nnnn {#2}{#3}{#1}{#4} }

\NewDocumentCommand{\ganttPlot}{ O{} g o }
{
  \IfNoValueTF{#2}
    {
      \tl_if_blank:VTF \l__tmp_current_project_tl
        { \msg_warning:nnn { dfg } { plot-current-project-missing } { gantt } }
        { \exp_args:NV \@@_typed_plot_current:nnnn
            \l__tmp_current_project_tl {\GanttPlot}{#1}{#3} }
    }
    { \@@_typed_plot:nnnn {\GanttPlot}{#1}{#2}{#3} }
}
\NewDocumentCommand{\collaborationPlot}{ O{} g o }
{
  \IfNoValueTF{#2}
    {
      \tl_if_blank:VTF \l__tmp_current_project_tl
        { \msg_warning:nnn { dfg } { plot-current-project-missing }
            { collaboration } }
        { \exp_args:NV \@@_typed_plot_current:nnnn
            \l__tmp_current_project_tl {\ProjectCollaborationPlot}{#1}{#3} }
    }
    { \@@_typed_plot:nnnn {\ProjectCollaborationPlot}{#1}{#2}{#3} }
}
% Preserve the plural current-project shorthand for existing documents.
\cs_new_eq:NN \collaborationsPlot \collaborationPlot

\NewDocumentCommand{\printGantt}{ m o }
{
  \IfNoValueTF{#2}
    { \printPlot{{Gantt}{#1}} }
    { \printPlot[caption={#2}]{{Gantt}{#1}} }
}
%    \end{macrocode}
% \subsection{Gantt chart rendering}
%
% The Gantt chart for each project is assembled in two steps:
% \begin{enumerate}
%   \item \cs{dfgGanttContent}\marg{project}: iterates over the
%         |gantt-\meta{project}| database and generates one
%         |\ganttbar| call per row.  Rows where |periodStart = periodEnd|
%         are silently skipped.  Row breaks precede each visible bar after
%         the first, so skipped rows and the last bar add no blank bottom row.
%         The bar style is dispatched via
%         \cs{str\_case:VnF}: |crosshatch| uses a pgfgantt pattern fill;
%         |striped| overlays two colours at 45° with \cs{postaction}, using
%         an explicitly coloured PDF pattern for consistent viewer rendering;
%         |alternative| and |important| use flat fills; the default is
%         a solid |color@gantt@default| bar.
%   \item \cs{dfgGanttEnvironment}\marg{project}: wraps the content in a
%         |pgfgantt| |ganttchart| environment spanning 16 columns (quarters
%         Q3 of year 0 through Q2 of year 5, matching the standard DFG
%         5-year period).  The chart is scaled with \cs{resizebox} to fill
%         the full text width.  A 0.9-row bar with no top shift leaves a
%         narrow gap between the final bar and the bottom rule.
% \end{enumerate}
%
% \cs{printPlot}|{{Gantt}{|\meta{project}|}}| is the preferred user-facing
% command; \cs{printGantt} remains a compatibility alias.  The dispatcher
% calls \cs{GanttPlot}, which wraps the chart in an |hvfloat| figure with an
% appropriate caption, optionally followed by extra text. Both variants use
% the label |fig:gantt-<project>|, for example |fig:gantt-A02|. The shared float
% helper defaults to |floatPos=!hb,capPos=bottom|; native hvfloat options may
% override these defaults for the current plot. The following
% \cs{FloatBarrier} closes the project-plan block.
%
% \textbf{Quarter numbering:} columns 1--2 correspond to Q3--Q4 of the
% calendar year preceding the funding start; columns 3--16 are Q1--Q4 of
% years 1--4; the final 16th column is Q1--Q2 of year 5.  Bar start/end
% values in the Gantt database should use these numbers directly.
%    \begin{macrocode}
% Store the stripe colour inside the PDF pattern. Some renderers paint
% stroked, uncoloured patterns black even when their fill colour is set.
% Include the resolved model and components in the pattern cache key, so
% per-chart colour changes produce a new pattern instead of reusing one.
% The shared renderer and configurable quarter grid are in dfg-gantt.sty.
%    \end{macrocode}
% \subsection{TOC entry and work-package helpers}
%
% \cs{dfgTOCprojectPart}\marg{letter}\marg{title} adds a bold chapter-level
% entry to the table of contents coloured in the project colour (|projectA|
% for letter A, etc.).  Call it immediately before the project's
% \cs{chapter} command.
%
%    \begin{macrocode}
\NewDocumentCommand{\dfgTOCprojectPart}{m O{Project~area} m}{
  % #1: project       (kann leer sein)
  % #2: pre-freetext  (default: "Project area")
  % #3: free text     (kann leer sein)
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \addtocentrydefault{chapter}
      { \tl_if_blank:nF {#1} { \texorpdfstring{\getProjectColor{#1}#1}{} } }
    {
      #2\c_space_tl
      \tl_if_blank:nF {#1} { \texorpdfstring{\getProjectColor{#1}#1}{#1} ~--~ #3 }
    }
  }
}
%    \end{macrocode}
%
% \subsection{CV / Curriculum Vitae}
%
% The CV section produces structured curricula vitae in the DFG-prescribed
% format for each project leader.  The same document class is used for
% both the integrated CV pages inside the main proposal and the standalone
% |crc-cv.tex| document (identified by |cv=true|).
%
% Every section is a breakable \texttt{tcolorbox} with a colored title bar.
% Entry bodies
% use ordinary paragraphs and lists, so a single career description,
% optional entry, publication, or privacy paragraph may span pages.
% Labels use one quarter of the row width; date-free entries use the
% full width. The existing command signatures and metadata schema are unchanged.
% \refKey{cvTableAfterSkip} adjusts spacing after each box; its new default
% is zero because the boxes supply their own normal spacing.
% Standard after-box spacing preserves page breaks between adjacent sections;
% the configured adjustment is appended once after the final box part.
%
% The shared |dfgCVSection| tcolorbox style controls fonts, colors and padding.
% Section bodies use the normal document font at \cs{normalsize}, including
% its italic and bold faces; title bars use the sans-serif bold face.
% Customize it from |preamble/dfg-customization.tex| after class loading:
% |\AddToHook{class/dfg-crc/after}{\tcbset{dfgCVSection/.append style={top=3pt}}}|.
% Long entry bodies are never wrapped in an unbreakable table row. Optional
% sections with no matching records, empty publication categories, and skipped
% publication lists create no empty title boxes or additional spacing.
%
% \textbf{Structure per PI:}
% \begin{enumerate}
%   \item \cs{dfgCVheader}\marg{id} — chapter heading with name, academic
%         title and (if present) a QR code linking to the PI's homepage.
%   \item \cs{dfgCVmandatory}\marg{id} — qualification and career section
%         built from all |cv| entries with |cv-type=mandatory|.
%   \item \cs{dfgCVoptional}\marg{id} — the five supplementary sections
%         (supplement, activities, supervision, distinction, other), each
%         rendered only when at least one matching entry exists.
%   \item \cs{dfgCVpublications}\marg{id} — the ten most important
%         publications printed via biblatex; skippable with |skip10pub=true|.
%   \item \cs{dfgCVdataprivacy} — the mandatory GDPR data-privacy statement.
% \end{enumerate}
%
% \cs{dfgCV}\marg{id} is a convenience wrapper that calls all five steps
% in order and manages the bold-author activations around the publications.
%
% Creating a boolean for detecting optional content (used to conditionally
% include the privacy statement when optional sections exist).
%    \begin{macrocode}
\bool_new:N \l_@@_cvoptional_bool
%    \end{macrocode}
% \subsubsection{CV commands}
%
% \paragraph{\cs{dfgCVheader}}
% Renders the standardised CV heading for one PI.  The chapter title
% uses a two-line format: the word \enquote{Curriculum Vitae} in the
% alternative font colour, followed by the PI's full name with academic
% title in bold.  If the PI has a URL in the |person| database, a QR code
% linking to it is placed in the top-right margin on the first CV page
% via |\AddToHookNext{shipout/background}|.  The QR code is omitted when
% the URL field is empty to avoid rendering an empty code.
%    \begin{macrocode}
\bool_if:NT  \l_@@_class_cv_bool {
% multicols for TOC
% https://tex.stackexchange.com/a/314046/98739
\BeforeStartingTOC[toc]{\begin{multicols}{2}}%
\AfterStartingTOC[toc]{\end{multicols}}

% no page number for chapters in TOC
\RedeclareSectionCommands[
  tocraggedpagenumber,
  toclinefill=\tocpageseparator,
  tocindent=0em,
  tocnumwidth=0em,
  tocpagenumberbox=\tocpagenumberbox,%\tocgobble,% <- added
  tocpagenumberformat=\textsf,
]{chapter}
}

\newcommand\dfgReduceSpace{%
  \dim_compare:nNnF {\l_@@_custom_cv_table_after_skip_tl} = {0pt}
    {\vspace*{\dim_eval:n {\l_@@_custom_cv_table_after_skip_tl}}}%
}

% One breakable box per section; body text remains ordinary paragraphs.
\tcbset{dfgCVSection/.style={
  enhanced~jigsaw,breakable,sharp~corners,frame~hidden,
  boxrule=0pt,boxsep=0pt,width=\linewidth,
  colback=white,colbacktitle=tableHeadingsBG,coltitle=tableHeadingsFont,
  fonttitle=\normalsize\sffamily\bfseries,
  % Use the document body family, including its italic and bold faces.
  fontupper=\normalfont\normalsize,
  left=4pt,right=4pt,top=4pt,bottom=4pt,
  toptitle=4pt,bottomtitle=4pt,
  before~skip=.5\baselineskip,
  % Retain a legal break between boxes before applying the configured gap.
  after~skip=0pt,
  after~app={\dfgReduceSpace},
  lines~before~break=3
}}
\newtcolorbox{dfgCVSectionBox}[1]{
  dfgCVSection,title={#1},
  %title~after~break={#1~(continued)}
}
% The left column takes one quarter of the available row width. Labels align
% with the first text baseline but do not deepen that line: a tall label must
% not push the description's second line downward. Build the body once, then
% unpack its vertical list so all ordinary paragraph/page breaks remain live.
% Only short bodies receive trailing padding to reserve the label's full height.
\box_new:N \l_@@_cv_label_box
\box_new:N \l_@@_cv_body_box
\dim_new:N \l_@@_cv_column_dim
\dim_new:N \l_@@_cv_label_gap_dim
\cs_new_protected:Npn \@@_cv_labeled:nnn #1#2#3
  {
    \par\group_begin:
    \dim_set:Nn \l_@@_cv_column_dim {#1}
    \hbox_set:Nn \l_@@_cv_label_box
      {\parbox[t]{\dim_eval:n {\l_@@_cv_column_dim-6pt}}
        {\RaggedRight\strut #2\strut\par}}
    \vbox_set:Nn \l_@@_cv_body_box
      {
        \begin{list}{}{
          \setlength{\leftmargin}{\l_@@_cv_column_dim}
          \setlength{\labelsep}{6pt}
          \setlength{\labelwidth}{\dimexpr\leftmargin-\labelsep\relax}
          \setlength{\rightmargin}{0pt}
          \setlength{\itemindent}{0pt}
          \setlength{\listparindent}{0pt}
          \setlength{\topsep}{0pt}
          \setlength{\partopsep}{0pt}
          \setlength{\itemsep}{0pt}
          \setlength{\parsep}{2pt}
          \renewcommand\makelabel[1]{\smash[b]{##1}}
        }
        \item[{\box_use:N \l_@@_cv_label_box}]\leavevmode #3\par
        \end{list}
      }
    \dim_set:Nn \l_@@_cv_label_gap_dim
      {\box_ht:N \l_@@_cv_label_box+\box_dp:N \l_@@_cv_label_box
       -\box_ht:N \l_@@_cv_body_box-\box_dp:N \l_@@_cv_body_box}
    \vbox_unpack_drop:N \l_@@_cv_body_box
    \dim_compare:nNnT {\l_@@_cv_label_gap_dim}>{0pt}
      {\nobreak\vspace*{\l_@@_cv_label_gap_dim}}
    \group_end:
    \par\vspace{2pt}
  }
\cs_new_protected:Npn \@@_cv_field:nn #1#2
  {\@@_cv_labeled:nnn {.25\linewidth}{#1}{#2}}
\cs_new_protected:Npn \@@_cv_entry:nn #1#2
  {\@@_cv_labeled:nnn {.25\linewidth}{#1}{#2}}
\cs_new_protected:Npn \@@_cv_text:n #1
  {\par\noindent #1\par\vspace{2pt}}
\cs_new_protected:Npn \@@_cv_period:nnn #1#2#3
  {
    \tl_if_blank:eTF {#2}
      {\tl_if_blank:eF {#3}{\dfgShowTag{#1}{periodEnd}{#3}[cv-#1]}}
      {
        \tl_if_blank:eTF {#3}
          {since\space\dfgShowTag{#1}{periodStart}{#2}[cv-#1]}
          {\dfgShowTag{#1}{periodStart}{#2}[cv-#1]
           \str_if_eq:eeF {#2}{#3}
             {--\allowbreak\dfgShowTag{#1}{periodEnd}{#3}[cv-#1]}}
      }
  }
\NewDocumentCommand{\dfgCVheader}{ m }{%
  % #1: person-id
  \bool_set_false:N \l_@@_cvoptional_bool

  % Single scan: pull all needed fields at once
  \getEntry*[person]{#1}{
    \theAcademicDegree = academicdegree,
    \theURLValue       = url,
    \theNameValue      = lastname,
    \theFirstNameValue = firstname,
    \CurrentPosition   = position,
    \CurrentPositionText   = positionText
  }%
  \addchap[{
      head={CV
        \texorpdfstring{\dfgShowTag{#1}{academicdegree}{\theAcademicDegree}[person]}
          {\theAcademicDegree}\space
        \texorpdfstring{\dfgShowTag{#1}{firstname}{\theFirstNameValue}[person]}
          {\theFirstNameValue}\space
        \texorpdfstring{\dfgShowTag{#1}{lastname}{\theNameValue}[person]}
          {\theNameValue}},
      tocentry={
        \texorpdfstring{\dfgShowTag{#1}{lastname}{\theNameValue}[person]}
          {\theNameValue},\space
        \texorpdfstring{\dfgShowTag{#1}{firstname}{\theFirstNameValue}[person]}
          {\theFirstNameValue}}}]{%
        {\normalsize\textcolor{color@font@alternative}{Curriculum \space Vitae}\\[.5\baselineskip]
	\dfgShowTag{#1}{academicdegree}{\theAcademicDegree}[person]\\[.25\baselineskip]}
	\bfseries
        \dfgShowTag{#1}{firstname}{\theFirstNameValue}[person]\space
        \dfgShowTag{#1}{lastname}{\theNameValue}[person]
  }%
  %\pdfbookmark{CV~\theNameValue, ~~ \theFirstNameValue}{cv-#1}

  % Printing the QR code only on one page next to the headline.
  \AddToHookNext{shipout/background}{%
    \DTLifnullorempty{\theURLValue}
    {}
    {\put(\pagewidth-\marginparwidth,-.05\paperheight){%
			\dfgShowTag{#1}{url}{\qrcode[link,height=1.5cm]{\theURLValue}}[person]}}%
  }

  \begin{dfgCVSectionBox}{Personal~Data}
    \@@_cv_field:nn {Title}
      {\dfgShowTag{#1}{academicdegree}{\theAcademicDegree}[person]}
    \@@_cv_field:nn {First~name}
      {\dfgShowTag{#1}{firstname}{\theFirstNameValue}[person]}
    \@@_cv_field:nn {Name}
      {\dfgShowTag{#1}{lastname}{\theNameValue}[person]}
    \@@_cv_field:nn {Current~position}
      {\ifdefempty{\CurrentPositionText}
        {\dfgShowTag{#1}{position}{\dfgCategoryName{\CurrentPosition}}[person]}
        {\dfgShowTag{#1}{positionText}{\CurrentPositionText}[person]}}
    \@@_cv_field:nn {Current~institution(s)/\\site(s),~country}
      {\printList{{Institutions}{#1}}}
    \@@_cv_field:nn {ORCiD}{\getORCiD{#1}}
  \end{dfgCVSectionBox}
}
%    \end{macrocode}
% The next section is about |Qualifications and Career|.
%    \begin{macrocode}
\NewDocumentCommand{\dfgCVmandatory}{ m }{%
  \DTLsortdata{cv-#1}
    {periodStart={descending=true},periodEnd={descending=true},position={ascending=true}}
  \group_begin:
  \@@_proj_pi_build:
  \getEntry*[person]{#1}{
    \theDegreeProgramme=degree-programme,
    \theDoctorateYear=doctorateYear,
    \theDoctorate=doctorate
  }
  \begin{dfgCVSectionBox}{Qualifications~and~Career}
    \@@_cv_entry:nn {\bfseries Stages}{\bfseries Periods~and~Details}
    \@@_cv_entry:nn {Degree~programme}
      {\dfgShowTag{#1}{degree-programme}{\theDegreeProgramme}[person]}
    \@@_cv_entry:nn {Doctorate}
      {\dfgShowTag{#1}{doctorateYear}{\theDoctorateYear}[person]\space
       \dfgShowTag{#1}{doctorate}{\theDoctorate}[person]}
    \DTLforeach*[
      \DTLiseq{\dfgrefpersonid}{#1}\and\DTLiseq{\dfgtype}{mandatory}
    ]{cv-#1}{
      \dfgrefpersonid=ref-person-id,\dfgtype=type,
      \dfgyearstart=periodStart,\dfgyearend=periodEnd,
      \dfgpositionText=positionText,\dfgposition=position,
      \dfgrefinstitutionid=ref-institution-id,\dfgdescription=description
    }{
      \DTLifnullorempty{\dfgyearstart}{\def\dfgyearstart{}}{}
      \DTLifnullorempty{\dfgyearend}{\def\dfgyearend{}}{}
      \prop_get:NVNTF \g_@@_inst_narrow_prop \dfgrefinstitutionid \theInstAffName
        {}{\tl_clear:N \theInstAffName}
      \@@_cv_entry:nn
        {\@@_cv_period:nnn {#1}{\dfgyearstart}{\dfgyearend}
         \ifdefempty{\dfgposition}{}{:\space\dfgShowTag{#1}{position}{\dfgposition}[cv-#1]}}
        {\dfgShowTag{#1}{positionText}{\dfgpositionText}[cv-#1]
         \ifdefempty{\theInstAffName}{}{,\space\theInstAffName}
         \ifdefempty{\dfgdescription}{}
           {\par\textit{\dfgShowTag{#1}{description}{\dfgdescription}[cv-#1]}}}
    }
  \end{dfgCVSectionBox}
  \group_end:
}
%    \end{macrocode}
% The next section is about |Supplementary Career Information|, or
% |Activities in the Research System| or |Supervision of Researchers in Early|
% |Career Phases| since they all are technically the same.
%    \begin{macrocode}
\NewDocumentCommand{\dfgCVoptional}{ m m m }{%
  \group_begin:
  \def\tblrbody{}
  \DTLforeach*[
    \DTLiseq{\dfgrefpersonid}{#1}\and\DTLiseq{\dfgtype}{#2}
  ]{cv-#1}{
    \dfgrefpersonid=ref-person-id,\dfgtype=type,
    \dfgyearstart=periodStart,\dfgyearend=periodEnd,
    \dfgpositionText=positionText,\dfgposition=position,
    \dfgrefinstitutionid=ref-institution-id,\dfgdescription=description
  }{
    \DTLifnullorempty{\dfgyearstart}{\def\dfgyearstart{}}{}
    \DTLifnullorempty{\dfgyearend}{\def\dfgyearend{}}{}
    \bool_lazy_and:nnTF
      {\tl_if_empty_p:V \dfgyearstart}{\tl_if_empty_p:V \dfgyearend}
      {\protected@edef\tblrbody{\tblrbody
        \@@_cv_text:n {\dfgShowTag{#1}{description}{\dfgdescription}[cv-#1]}}}
      {\protected@edef\tblrbody{\tblrbody
        \@@_cv_entry:nn
          {\@@_cv_period:nnn {#1}{\dfgyearstart}{\dfgyearend}}
          {\dfgShowTag{#1}{description}{\dfgdescription}[cv-#1]}}}
  }
  \ifdefempty{\tblrbody}{}
    {\begin{dfgCVSectionBox}{#3}\tblrbody\end{dfgCVSectionBox}}
  % Keep the optional-content flag visible after the local rendering group.
  \ifdefempty{\tblrbody}
    {\group_end:}
    {\group_end:\bool_set_true:N \l_@@_cvoptional_bool}
}
%    \end{macrocode}
% For the publications we define a custom bibliography template that is
% enumerating the items as required.
%    \begin{macrocode}
\newlist{DFGlist}{enumerate}{1}
\setlist[DFGlist]{leftmargin=*}
\setlist[DFGlist,1]{
  % font=\bfseries,
  % first=\bfseries,
  % after=\normalfont,
  % itemsep=.5\baselineskip,
  % wide,
  label={\bfseries\arabic*.},
  nosep
}
%    \end{macrocode}
% Further on we apply this to the bibliography environment.
%    \begin{macrocode}
\tl_new:N \g_@@_cv_publication_title_tl
\tl_gset:Nn \g_@@_cv_publication_title_tl {Scientific~results}
\tl_new:N \g_@@_cv_publication_description_tl
\cs_new_protected:Npn \@@_cv_publication_begin:
  {
    \begin{dfgCVSectionBox}{\tl_use:N \g_@@_cv_publication_title_tl}
    \tl_use:N \g_@@_cv_publication_description_tl\par\nobreak\smallskip
    \begin{DFGlist}\RaggedRight
  }
\cs_new_protected:Npn \@@_cv_publication_end:
  {
    \end{DFGlist}\end{dfgCVSectionBox}
    \tl_gset:Nn \g_@@_cv_publication_title_tl {Scientific~results}
    \tl_gclear:N \g_@@_cv_publication_description_tl
  }
\defbibenvironment{DFGlist}
{\@@_cv_publication_begin:}
{\@@_cv_publication_end:}
{\item}
%    \end{macrocode}
% The next section combines everything and wraps it.
% To have a reference listed in this section you have to write into the
%    \begin{macrocode}
\defbibheading{categoryA}{%
  \tl_gset:Nn \g_@@_cv_publication_title_tl {Scientific~results~--~Category~A}
  \tl_gset:Nn \g_@@_cv_publication_description_tl
    {Articles~in~peer-reviewed~journals,~contributions~to~peer-reviewed~conferences~or~to~anthology~volumes,~and~book~publications}
}
\defbibheading{categoryB}{%
  \tl_gset:Nn \g_@@_cv_publication_title_tl {Scientific~results~--~Category~B}
  \tl_gset:Nn \g_@@_cv_publication_description_tl
    {Any~other~form~of~published~results}
}

\NewDocumentCommand{\dfgCVpublications}{ m }{%
  % #1: person-id
  \bool_if:NTF \l_@@_class_skipTENpublications_bool
  {%
    \par
    \group_begin: \ttfamily
    Publication~ section~ for~ \getFullName{#1}~ omitted~
    for~ faster~ compilation.\\
    To~ enable~ the~ 10~ most~ important~ publications,~
    go~ to~ the~ documentclass~ options\\ and~ state~
    '\textbf{skip10pub=false}'.
    \group_end:
  }{%
    \tl_gset:Nn \g_@@_current_pi_tl {#1}
    \newrefcontext[sorting=ydnt]
    \nocite{*}%
    \datatool_if_has_key:nnT { person } { name-alias }
    {
      \@@_getvalueforkey:Nnnnn { \theAliases } { name-alias } { person } { id } { #1 }
      \DTLifnullorempty { \theAliases }
      { }
      { \exp_args:No \addboldnames { \theAliases } }
    }

    \renewcommand*{\bibfont}{\normalfont\normalsize}%

    \printbibliography[
      env          = DFGlist,
      resetnumbers,
      keyword      = {#1-A},
      heading      = categoryA
    ]
    \printbibliography[
      env          = DFGlist,
      resetnumbers,
      keyword      = {#1-B},
      heading      = categoryB
    ]

    \endrefcontext
    \resetboldnames
    \tl_gclear:N \g_@@_current_pi_tl
  }%
}

\tl_new:N \g_@@_current_pi_tl
%    \end{macrocode}
% \begin{macro}{\ifIDequal}
%   Conditional macro for use inside \texttt{.bib} files.  Inside an
%   |addendum| field, write \verb|\ifIDequal{pi-id}{text}|; the text is
%   only emitted when the bibliography is being rendered for that PI.
%
%   The current PI is held in |\g_@@_current_pi_tl|, which is set by
%   |\dfgCVpublications| before each \verb|\printbibliography| call.
%
%   The protected public command is defined with expl3 syntax. Its stored
%   tokens remain valid when biblatex calls it with |\ExplSyntaxOff| active;
%   callers do not need to change their syntax mode.
%
%   Only literally empty text is skipped, without expanding it. Both IDs are
%   fully expanded before their tokens and category codes are compared,
%   preserving the former |\edef|/|\ifx| semantics. Matching text starts a
%   paragraph in the alternative font colour, outside the comparison's scope.
%    \begin{macrocode}
\DeclareFieldFormat{addendum}{\mkbibitalic{#1}}
\cs_new_protected:Npn \ifIDequal #1#2
  {
    \tl_if_empty:nF {#2}
      {
        \tl_if_eq:eeT {#1} {\g_@@_current_pi_tl}
          {
            \par
            \textcolor{color@font@alternative}{#2}
          }
      }
  }
%    \end{macrocode}
% \end{macro}
% After each section - especially when any content was written for the optional
% parts, a data privacy is needed.
% We only need this section if there has been optional text before. We find this
% out by checking the bool.
%    \begin{macrocode}
\ExplSyntaxOff
\NewDocumentCommand{\dfgCVdataprivacy}{ m }{%
  \begin{dfgCVSectionBox}{Data protection and consent to the processing of optional data}
  \normalsize
  \noindent{\large\ding{55}}\enspace I (\getFullName*{#1}) expressly consent
        to the processing of the voluntary
    (optional) information, including “special categories of personal data” in
    connection with the DFG’s review and decision-making process regarding my
    proposal. This also includes forwarding my data to the external reviewers,
    committee members and, where applicable, foreign partner organisations who
    are involved in the decision-making process. To the extent that these
    recipients are located in a third country (outside the European Economic
    Area), I additionally consent to them being granted access to my data for
    the above-mentioned purposes, even though a level of data protection
    comparable to EU law may not be guaranteed. For this reason, compliance with
    the data protection principles of EU law is not guaranteed in such cases. In
    this respect, there may be a violation of my fundamental rights and freedoms
    and resulting damages. This may make it more difficult for me to assert my
    rights under the General Data Protection Regulation (e.g.\ information,
    rectification, erasure, compensation) and, if necessary, to enforce these
    rights with the help of authorities or in court.

I may \emph{revoke} my consent in whole or in part at any time – with effect for the
    future, freely and without giving reasons – vis-à-vis the DFG
    (\href{mailto:postmaster@dfg.de}{postmaster@dfg.de}). The lawfulness of the
    processing carried out up to that point remains unaffected. Insofar as I
    transmit \enquote{special categories of personal data} relating to third
    parties, I confirm that the necessary legitimation under data protection law
    exists (e.g.\ based on consent).

I have taken note of the DFG’s Data Protection Notice relating to research
    funding, which I can access at \url{www.dfg.de/privacy_policy} and I will forward it
    to such persons whose data the DFG processes as a result of being mentioned in
    this CV.
  \end{dfgCVSectionBox}
}
\ExplSyntaxOn
%    \end{macrocode}
% We wrap everything into one command.
%    \begin{macrocode}
\NewDocumentCommand{\dfgCV}{ m }{%
  % #1: person-id
	\bool_if:NF \l_@@_class_fastcompile_project_bool
	{
  \DTLifdbexists{cv-#1}{
  \StartTimer\dfgCVheader{#1}\StopTimer{#1:dfgCVheader}
  \StartTimer\dfgCVmandatory{#1}\StopTimer{#1:dfgCVmandatory}
  \StartTimer\dfgCVoptional{#1}{supplement}{Supplementary~ Career~ Information}\StopTimer{#1:dfgCVoptional|supplement}
  \StartTimer\dfgCVoptional{#1}{activities}{Activities~  in~  the~  Research~ System}\StopTimer{#1:dfgCVoptional|activities}
  \StartTimer\dfgCVoptional{#1}{supervision}{Supervision~  of~  Researchers~  in~  Early~  Career~  Phases}\StopTimer{#1:dfgCVoptional|supervision}
  \StartTimer \dfgCVpublications{#1}\StopTimer{#1: dfgCVpublications}
  \StartTimer\dfgCVoptional{#1}{distinction}{Academic~  Distinctions}\StopTimer{#1:dfgCVoptional|distinction}
  \StartTimer\dfgCVoptional{#1}{other}{Other~ Information}\StopTimer{#1:dfgCVoptional|other}

  % We check for the bool at this place because we dont have to enable
  % \LaTeX3-Syntax within the command which would require to put |~| at each space.
  \bool_if:NT \l_@@_cvoptional_bool  {
    \StartTimer	\dfgCVdataprivacy{#1} \StopTimer{#1:dfgCVdataprivacy}
  }
}
{\msg_warning:nne { dfg } { database-not-found }{ cv-#1 }}
	}
}
%    \end{macrocode}
% The CV should be printed automatically for all persons with the role |PI|.
%    \begin{macrocode}
\NewDocumentCommand{\dfgCVsection}{ O{person} }{%
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
  \DTLifdbexists{#1}{%
    \DTLsort*{lastname,firstname}{#1}%
    \DTLforeach*[%start of conditions
      \DTLisinlist{\theFundingPeriodNumeral}{\period}% 1st condition
      \and%
      \DTLisinlist{PI}{\role}% 2nd condition
    ]{#1}{%
      \id             =id,
      \period         =period,
      \role           =role%
    }{%
	\exp_args:Ne \dfgCV { \id }
    }
}{
   Database \texttt{#1} missing.
    \msg_warning:nne { dfg } { database-not-found }{ #1 }
  }%
  }
}
%    \end{macrocode}
% Finally we load the metadata and customization provided by the user.
% In case a file is missing a message will be displayed to inform the user.
%    \begin{macrocode}
\NewDocumentCommand{\checkFile}{m}{%
    \StartTimer
  \file_if_exist:nTF {#1}
  {\ExplSyntaxOff\input{#1}\ExplSyntaxOn}
  {\msg_warning:nne { dfg } { file-not-found }{#1}}%
    \StopTimer{checkFile:#1}
}
%    \end{macrocode}
% There are at least some file we need or should consider checking.
%    \begin{macrocode}
\bool_if:NF \l_@@_class_documentation_bool
{
\bool_if:NTF \l_@@_class_fastcompile_project_bool
{
  \bool_if:NT \l_@@_class_fastcompile_project_show_images_bool
    { \checkFile{metadata/dfg-metadata.tex} }
}
{
  \checkFile{metadata/dfg-metadata.tex}
  \bool_if:NTF \l_@@_class_cv_bool
  { \checkFile{metadata/dfg-metadata-cv.tex} }
  { \msg_warning:nnn { dfg } { cv-entry-omitted }
    {metadata/dfg-metadata-cv.tex} }
  \bool_if:NF \l_@@_class_cv_bool
  { \checkFile{metadata/dfg-metadata-tables.tex} }
}
}
%    \end{macrocode}
% This is a gimmick but quite fun to experiment with. This is taken from
% \url{https://tex.stackexchange.com/a/732406/98739}. Note that the message is
% written into the |.log|-file, not in the terminal.
%    \begin{macrocode}
\def\dfgFinalComment{Well~ done~ coding!~ Happy~ TeXing.}
\directlua{
  luatexbase.add_to_callback('wrapup_run',
  function ()
  f=io.open("\jobname.log", "a")
  f:write("\dfgFinalComment")
  f:close()
  end,
  "final message"
  )
}
%    \end{macrocode}
% \iffalse
%</cls>
%<*plot-core>
% \fi
% \subsection{Reusable package: dfg-plots.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplPackage{dfg-plots}{2026-11-24}{0.4.0}{Reusable proposal plot infrastructure}
% hvfloat loads picture; its calc mode remains supported by picture v2.
\PassOptionsToPackage{calc}{picture}
\RequirePackage{hvfloat}
\ExplSyntaxOn
\tl_new:N \l__dfgplots_options_tl
\tl_new:N \l__dfgplots_gantt_options_tl
\tl_new:N \l__dfgplots_collaboration_options_tl
\tl_new:N \l__dfgplots_float_options_tl
\tl_new:N \l__dfgplots_project_tl
\prop_new:N \g__dfgplots_renderers_prop
\keys_define:nn {dfgplots/setup}
  {
    plotOptions .tl_set:N = \l__dfgplots_options_tl,
    ganttPlotOptions .tl_set:N = \l__dfgplots_gantt_options_tl,
    collaborationPlotOptions .tl_set:N = \l__dfgplots_collaboration_options_tl,
  }
\NewDocumentCommand \dfgPlotSetup {m}
  {\keys_set:nn {dfgplots/setup}{#1}}
\ProvideDocumentCommand \changeSettings {m} {\dfgPlotSetup{#1}}
\NewDocumentCommand \dfgPlotProject {m} {\tl_set:Nn \l__dfgplots_project_tl {#1}}
\NewDocumentCommand \dfgDeclarePlotType {mm}
  {\prop_gput:Nnn \g__dfgplots_renderers_prop {#1}{#2}}
\cs_new_protected:Npn \__dfgplots_dispatch:nn #1#2
  {\__dfgplots_spec:nnnw {#1} #2 {} \q_stop}
\cs_new_protected:Npn \__dfgplots_spec:nnnw #1#2#3#4\q_stop
  {
    \group_begin:
    \tl_if_blank:nF {#3}{\tl_set:Nn \l__dfgplots_project_tl {#3}}
    \prop_get:NnNTF \g__dfgplots_renderers_prop {#2} \l_tmpa_tl
      {
        \tl_if_blank:VTF \l__dfgplots_project_tl
          {\msg_error:nn {dfg-plots}{missing-project}}
          {\use:e {\exp_not:V \l_tmpa_tl [\exp_not:n {#1}]
            {\exp_not:V \l__dfgplots_project_tl}}}
      }
      {\msg_error:nnn {dfg-plots}{unknown-type}{#2}}
    \group_end:
  }
\msg_new:nnn {dfg-plots}{missing-project}
  {Give~a~project~ID~or~set~one~with~\string\dfgPlotProject.}
\msg_new:nnn {dfg-plots}{unknown-type}
  {Unknown~plot~type~'#1'.~Load~dfg-collaboration~or~dfg-gantt.}
\ProvideDocumentCommand \printPlot {O{} +m}{\__dfgplots_dispatch:nn {#1}{#2}}
% The host adapter overrides this accessor, rather than copying settings.
\cs_new:Npn \__dfgplots_defaults:n #1
  {
    \exp_not:V \l__dfgplots_options_tl,
    \str_if_eq:nnTF {#1}{gantt}
      {\exp_not:V \l__dfgplots_gantt_options_tl}
      {\exp_not:V \l__dfgplots_collaboration_options_tl}
  }
\cs_new_protected:Npn \__dfgplots_options:nnn #1#2#3
  {
    \exp_args:Nne \keys_set_known:nnN {#1}
      {\__dfgplots_defaults:n {#2},\exp_not:n {#3}}
      \l__dfgplots_float_options_tl
  }
\cs_new_protected:Npn \__dfgplots_float:
  {\par\use:e {\exp_not:N \hvFloat
    [floatPos=!hb,capPos=bottom,\exp_not:V \l__dfgplots_float_options_tl]}}
\hvDefFloatStyle{proposalPlots}{floatPos=!t,capPos=top,floatCapSep=8pt}
\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</plot-core>
%<*collaboration-package>
% \fi
% \subsection{Reusable package: dfg-collaboration.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplPackage{dfg-collaboration}{2026-11-24}{0.4.0}{Independent collaboration plots}
\ExplSyntaxOff
\RequirePackage{dfg-plots}
\RequirePackage{tikz}
\usetikzlibrary{calc}
\providecolor{grey}{gray}{.5}
\ExplSyntaxOn
\dim_new:N  \l__dfg_collaboration_plot_x_dim
\dim_new:N  \l__dfg_collaboration_plot_y_dim
\dim_new:N  \l__dfg_collaboration_plot_x_step_dim
\dim_new:N  \l__dfg_collaboration_plot_box_width_dim
\dim_new:N  \l__dfg_collaboration_plot_box_gap_dim
\dim_new:N  \l__dfg_collaboration_plot_area_label_width_dim
\dim_new:N  \l__dfg_collaboration_plot_content_start_dim
\dim_new:N  \l__dfg_collaboration_plot_width_dim
\dim_new:N  \l__dfg_collaboration_plot_arc_height_dim
\box_new:N  \l__dfg_collaboration_plot_area_label_box
\seq_new:N  \l__dfg_collaboration_plot_nodes_seq
\seq_new:N  \l__dfg_collaboration_plot_areas_seq
\seq_new:N  \l__dfg_collaboration_plot_area_palette_seq
\seq_new:N  \l__dfg_collaboration_plot_edges_seq
\prop_new:N \l__dfg_collaboration_plot_all_status_prop
\prop_new:N \l__dfg_collaboration_plot_status_prop
\prop_new:N \l__dfg_collaboration_plot_lists_prop
\prop_new:N \l__dfg_collaboration_plot_edges_prop
\prop_new:N \l__dfg_collaboration_plot_visible_prop
\prop_new:N \l__dfg_collaboration_plot_area_prop
\prop_new:N \l__dfg_collaboration_plot_area_nodes_prop
\prop_new:N \l__dfg_collaboration_plot_area_color_prop
\prop_new:N \l__dfg_collaboration_plot_area_color_override_prop
\tl_new:N   \l__dfg_collaboration_plot_focus_tl
\tl_new:N   \l__dfg_collaboration_plot_layout_tl
\tl_new:N   \l__dfg_collaboration_plot_id_tl
\tl_new:N   \l__dfg_collaboration_plot_status_tl
\tl_new:N   \l__dfg_collaboration_plot_consider_tl
\tl_new:N   \l__dfg_collaboration_plot_reference_only_tl
\tl_new:N   \l__dfg_collaboration_plot_collaborations_tl
\tl_new:N   \l__dfg_collaboration_plot_area_tl
\tl_new:N   \l__dfg_collaboration_plot_source_tl
\tl_new:N   \l__dfg_collaboration_plot_target_tl
\tl_new:N   \l__dfg_collaboration_plot_edge_tl
\tl_new:N   \l__dfg_collaboration_plot_edge_left_tl
\tl_new:N   \l__dfg_collaboration_plot_edge_right_tl
\tl_new:N   \l__dfg_collaboration_plot_label_tl
\tl_new:N   \l__dfg_collaboration_plot_color_tl
\tl_new:N   \l__dfg_collaboration_plot_caption_tl
\int_new:N  \l__dfg_collaboration_plot_group_index_int
\int_new:N  \l__dfg_collaboration_plot_row_index_int
\int_new:N  \l__dfg_collaboration_plot_node_count_int
\int_new:N  \l__dfg_collaboration_plot_area_index_int
\bool_new:N \l__dfg_collaboration_plot_arcs_bool

\cs_new_protected:Npn \__dfg_collaboration_plot_merge_area_colors:n #1
{
  \prop_set_from_keyval:Nn \l_tmpa_prop {#1}
  \prop_map_inline:Nn \l_tmpa_prop
    { \prop_put:Nnn \l__dfg_collaboration_plot_area_color_override_prop
        {##1} {##2} }
}

\keys_define:nn { dfg / project-collaboration-plot }
{
  layout .choice:,
  layout / heatmap .code:n =
    { \tl_set:Nn \l__dfg_collaboration_plot_layout_tl { heatmap } },
  layout / arc .code:n =
    { \tl_set:Nn \l__dfg_collaboration_plot_layout_tl { arc } },
  layout / arc-diagram .meta:n = { layout = arc },
  heatmap .meta:n = { layout = heatmap },
  arc .meta:n = { layout = arc },
  arc-diagram .meta:n = { layout = arc },
  arcs .bool_set:N = \l__dfg_collaboration_plot_arcs_bool,
  arcs .default:n = true,
  no-arcs .meta:n = { arcs = false },
  area-colors .code:n =
    { \__dfg_collaboration_plot_merge_area_colors:n {#1} },
  area-colours .meta:n = { area-colors = {#1} },
  area-palette .code:n =
    {
      \clist_if_empty:nF {#1}
        { \seq_set_from_clist:Nn \l__dfg_collaboration_plot_area_palette_seq {#1} }
    },
  caption .tl_set:N = \l__dfg_collaboration_plot_caption_tl,
}

\cs_new_protected:Npn \__dfg_collaboration_plot_collect_edge:nn #1#2
{
  \tl_set:Nn \l__dfg_collaboration_plot_source_tl {#1}
  \tl_set:Nn \l__dfg_collaboration_plot_target_tl {#2}
  \tl_trim_spaces:N \l__dfg_collaboration_plot_source_tl
  \tl_trim_spaces:N \l__dfg_collaboration_plot_target_tl
  \tl_if_blank:VF \l__dfg_collaboration_plot_target_tl
  {
    \prop_if_in:NVTF \l__dfg_collaboration_plot_status_prop
      \l__dfg_collaboration_plot_target_tl
    {
      \str_if_eq:VVF
        \l__dfg_collaboration_plot_source_tl
        \l__dfg_collaboration_plot_target_tl
      {
        \str_compare:eNeTF
          { \tl_use:N \l__dfg_collaboration_plot_source_tl }
          <
          { \tl_use:N \l__dfg_collaboration_plot_target_tl }
          {
            \tl_set:Nx \l__dfg_collaboration_plot_edge_tl
              {
                \tl_use:N \l__dfg_collaboration_plot_source_tl
                /\tl_use:N \l__dfg_collaboration_plot_target_tl
              }
          }
          {
            \tl_set:Nx \l__dfg_collaboration_plot_edge_tl
              {
                \tl_use:N \l__dfg_collaboration_plot_target_tl
                /\tl_use:N \l__dfg_collaboration_plot_source_tl
              }
          }
        \prop_put:NVn \l__dfg_collaboration_plot_edges_prop
          \l__dfg_collaboration_plot_edge_tl { 1 }
      }
    }
    {
      \prop_if_in:NVF \l__dfg_collaboration_plot_all_status_prop
        \l__dfg_collaboration_plot_target_tl
      {
        \msg_warning:nnee { dfg-collaboration } { target-not-found }
          { \l__dfg_collaboration_plot_source_tl }
          { \l__dfg_collaboration_plot_target_tl }
      }
    }
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_collect_edges:
{
  \seq_clear:N \l__dfg_collaboration_plot_edges_seq
  \prop_map_inline:Nn \l__dfg_collaboration_plot_lists_prop
  {
    \clist_map_inline:nn {##2}
      { \__dfg_collaboration_plot_collect_edge:nn {##1} {####1} }
  }
  \__dfgcollab_override_edges:
  \prop_map_inline:Nn \l__dfg_collaboration_plot_edges_prop
    { \seq_put_right:Nn \l__dfg_collaboration_plot_edges_seq {##1} }
  \seq_sort:Nn \l__dfg_collaboration_plot_edges_seq
    {
      \str_compare:eNeTF {##1} < {##2}
        { \sort_return_same: }
        { \sort_return_swapped: }
    }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_unpack_edge:n #1
{
  \seq_set_split:Nnn \l_tmpa_seq {/} {#1}
  \seq_pop_left:NN \l_tmpa_seq \l__dfg_collaboration_plot_edge_left_tl
  \seq_pop_left:NN \l_tmpa_seq \l__dfg_collaboration_plot_edge_right_tl
}

\cs_new_protected:Npn \__dfg_collaboration_plot_prepare:
{
  \prop_clear:N \l__dfg_collaboration_plot_visible_prop
  \seq_clear:N \l__dfg_collaboration_plot_areas_seq
  \prop_clear:N \l__dfg_collaboration_plot_area_nodes_prop
  \prop_clear:N \l__dfg_collaboration_plot_area_color_prop
  \int_zero:N \l__dfg_collaboration_plot_area_index_int
  \prop_put:NVn \l__dfg_collaboration_plot_visible_prop
    \l__dfg_collaboration_plot_focus_tl { 1 }
  \seq_map_inline:Nn \l__dfg_collaboration_plot_edges_seq
  {
    \__dfg_collaboration_plot_unpack_edge:n {##1}
    \bool_lazy_or:nnT
    {
      \str_if_eq_p:VV
        \l__dfg_collaboration_plot_edge_left_tl
        \l__dfg_collaboration_plot_focus_tl
    }
    {
      \str_if_eq_p:VV
        \l__dfg_collaboration_plot_edge_right_tl
        \l__dfg_collaboration_plot_focus_tl
    }
    {
      \prop_put:NVn \l__dfg_collaboration_plot_visible_prop
        \l__dfg_collaboration_plot_edge_left_tl { 1 }
      \prop_put:NVn \l__dfg_collaboration_plot_visible_prop
        \l__dfg_collaboration_plot_edge_right_tl { 1 }
    }
  }
  \seq_map_inline:Nn \l__dfg_collaboration_plot_nodes_seq
  {
    \prop_get:NnN \l__dfg_collaboration_plot_area_prop {##1}
      \l__dfg_collaboration_plot_area_tl
    \prop_if_in:NVF \l__dfg_collaboration_plot_area_nodes_prop
      \l__dfg_collaboration_plot_area_tl
    {
      \seq_put_right:NV \l__dfg_collaboration_plot_areas_seq
        \l__dfg_collaboration_plot_area_tl
      \prop_get:NVNTF \l__dfg_collaboration_plot_area_color_override_prop
        \l__dfg_collaboration_plot_area_tl
        \l__dfg_collaboration_plot_color_tl
      {
        \prop_put:NVV \l__dfg_collaboration_plot_area_color_prop
          \l__dfg_collaboration_plot_area_tl
          \l__dfg_collaboration_plot_color_tl
      }
      {
        \int_incr:N \l__dfg_collaboration_plot_area_index_int
        \int_set:Nn \l_tmpa_int
          {
            1 + \int_mod:nn
              { \l__dfg_collaboration_plot_area_index_int - 1 }
              { \seq_count:N \l__dfg_collaboration_plot_area_palette_seq }
          }
        \prop_put:NVx \l__dfg_collaboration_plot_area_color_prop
          \l__dfg_collaboration_plot_area_tl
          {
            \seq_item:Nn \l__dfg_collaboration_plot_area_palette_seq
              { \l_tmpa_int }
          }
      }
      \prop_put:NVn \l__dfg_collaboration_plot_area_nodes_prop
        \l__dfg_collaboration_plot_area_tl { }
    }
    \prop_get:NVN \l__dfg_collaboration_plot_area_nodes_prop
      \l__dfg_collaboration_plot_area_tl \l_tmpa_tl
    \tl_if_blank:VTF \l_tmpa_tl
      { \tl_set:Nn \l_tmpa_tl {##1} }
      { \tl_put_right:Nn \l_tmpa_tl { , ##1 } }
    \prop_put:NVV \l__dfg_collaboration_plot_area_nodes_prop
      \l__dfg_collaboration_plot_area_tl \l_tmpa_tl
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_set_color:n #1
{
  \tl_set:Nx \l__dfg_collaboration_plot_label_tl {#1}
  \prop_get:NnNTF \l__dfg_collaboration_plot_area_prop
    {#1} \l__dfg_collaboration_plot_area_tl
    { \prop_get:NVN \l__dfg_collaboration_plot_area_color_prop
        \l__dfg_collaboration_plot_area_tl
        \l__dfg_collaboration_plot_color_tl }
    { \tl_set:Nn \l__dfg_collaboration_plot_color_tl { grey } }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_heatmap_cell:n #1
{
  \__dfg_collaboration_plot_set_color:n {#1}
  \str_if_eq:VVTF
    \l__dfg_collaboration_plot_focus_tl
    \l__dfg_collaboration_plot_label_tl
  {
    \node[
      anchor=center,
      minimum~width=\dim_use:N \l__dfg_collaboration_plot_box_width_dim,
      minimum~height=5.2mm,
      inner~sep=0pt,
      rounded~corners=1.4pt,
      draw=\tl_use:N \l__dfg_collaboration_plot_color_tl!78!black,
      fill=\tl_use:N \l__dfg_collaboration_plot_color_tl,
      text=white,
      font=\footnotesize\bfseries
    ] at
      (\dim_use:N \l__dfg_collaboration_plot_x_dim,
       \dim_use:N \l__dfg_collaboration_plot_y_dim)
      { \strut\tl_use:N \l__dfg_collaboration_plot_label_tl };
  }
  {
    \prop_if_in:NVTF \l__dfg_collaboration_plot_visible_prop
      \l__dfg_collaboration_plot_label_tl
    {
      \node[
        anchor=center,
        minimum~width=\dim_use:N \l__dfg_collaboration_plot_box_width_dim,
        minimum~height=5.2mm,
        inner~sep=0pt,
        rounded~corners=1.4pt,
        draw=\tl_use:N \l__dfg_collaboration_plot_color_tl!48,
        fill=\tl_use:N \l__dfg_collaboration_plot_color_tl!14,
        text=\tl_use:N \l__dfg_collaboration_plot_color_tl,
        font=\footnotesize\bfseries
      ] at
        (\dim_use:N \l__dfg_collaboration_plot_x_dim,
         \dim_use:N \l__dfg_collaboration_plot_y_dim)
        { \strut\tl_use:N \l__dfg_collaboration_plot_label_tl };
    }
    {
      \node[
        anchor=center,
        minimum~width=\dim_use:N \l__dfg_collaboration_plot_box_width_dim,
        minimum~height=5.2mm,
        inner~sep=0pt,
        rounded~corners=1.4pt,
        draw=grey!22,
        fill=white,
        text=grey!70!black,
        font=\footnotesize
      ] at
        (\dim_use:N \l__dfg_collaboration_plot_x_dim,
         \dim_use:N \l__dfg_collaboration_plot_y_dim)
        { \strut\tl_use:N \l__dfg_collaboration_plot_label_tl };
    }
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_heatmap_row:nnn #1#2#3
{
  \clist_if_empty:nF {#1}
  {
    \int_incr:N \l__dfg_collaboration_plot_row_index_int
    \dim_set:Nn \l__dfg_collaboration_plot_y_dim
    {
      -7mm *
      \int_eval:n { \l__dfg_collaboration_plot_row_index_int - 1 }
    }
    \node[
      anchor=east,
      inner~sep=0pt,
      font=\scriptsize\bfseries
    ] at
      (\dim_use:N \l__dfg_collaboration_plot_area_label_width_dim,
       \dim_use:N \l__dfg_collaboration_plot_y_dim)
      {Project~area~#3};
    \draw[draw=#2,line~width=.75pt,line~cap=round]
      (\dim_eval:n
         { \l__dfg_collaboration_plot_area_label_width_dim + .8mm },
       \dim_use:N \l__dfg_collaboration_plot_y_dim)
      --
      (\dim_eval:n
         { \l__dfg_collaboration_plot_area_label_width_dim + 2.8mm },
       \dim_use:N \l__dfg_collaboration_plot_y_dim);
    \int_zero:N \l__dfg_collaboration_plot_group_index_int
    \clist_map_inline:nn {#1}
    {
      \int_incr:N \l__dfg_collaboration_plot_group_index_int
      \dim_set:Nn \l__dfg_collaboration_plot_x_dim
      {
        \l__dfg_collaboration_plot_content_start_dim
        + \l__dfg_collaboration_plot_box_width_dim / 2
        + \l__dfg_collaboration_plot_x_step_dim *
        \int_eval:n { \l__dfg_collaboration_plot_group_index_int - 1 }
      }
      \__dfg_collaboration_plot_heatmap_cell:n {##1}
    }
  }
}
\cs_generate_variant:Nn \__dfg_collaboration_plot_heatmap_row:nnn { V V n }

\cs_new_protected:Npn \__dfg_collaboration_plot_heatmap_picture:
{
    % Use the widest project area as the shared column grid.  Each column gets
    % a dynamic box width, and the final cell reaches the right edge of the
    % text block instead of leaving a large unused strip before the caption.
    \dim_zero:N \l__dfg_collaboration_plot_area_label_width_dim
    \seq_map_inline:Nn \l__dfg_collaboration_plot_areas_seq
      {
        \hbox_set:Nn \l__dfg_collaboration_plot_area_label_box
          { \scriptsize\bfseries Project~area~##1 }
        \dim_compare:nNnT
          { \box_wd:N \l__dfg_collaboration_plot_area_label_box }
          >
          { \l__dfg_collaboration_plot_area_label_width_dim }
          {
            \dim_set:Nn \l__dfg_collaboration_plot_area_label_width_dim
              { \box_wd:N \l__dfg_collaboration_plot_area_label_box }
          }
      }
    \dim_set:Nn \l__dfg_collaboration_plot_content_start_dim
      { \l__dfg_collaboration_plot_area_label_width_dim + 4mm }
  \begin{tikzpicture}
    \int_zero:N \l__dfg_collaboration_plot_node_count_int
    \seq_map_inline:Nn \l__dfg_collaboration_plot_areas_seq
      {
        \prop_get:NnN \l__dfg_collaboration_plot_area_nodes_prop {##1}
          \l_tmpa_tl
        \clist_set:NV \l_tmpa_clist \l_tmpa_tl
        \int_set:Nn \l_tmpa_int { \clist_count:N \l_tmpa_clist }
        \int_set:Nn \l__dfg_collaboration_plot_node_count_int
          { \int_max:nn { \l__dfg_collaboration_plot_node_count_int }
            { \l_tmpa_int } }
      }
    \dim_set:Nn \l__dfg_collaboration_plot_box_gap_dim { 1mm }
    \int_compare:nNnTF
      { \l__dfg_collaboration_plot_node_count_int } > { 0 }
      {
        \dim_set:Nn \l__dfg_collaboration_plot_box_width_dim
        {
          ( \l__dfg_collaboration_plot_width_dim
            - \l__dfg_collaboration_plot_content_start_dim
            - \l__dfg_collaboration_plot_box_gap_dim *
              \int_eval:n
                { \l__dfg_collaboration_plot_node_count_int - 1 }
          ) / \l__dfg_collaboration_plot_node_count_int
        }
        \dim_set:Nn \l__dfg_collaboration_plot_x_step_dim
        {
          \l__dfg_collaboration_plot_box_width_dim
          + \l__dfg_collaboration_plot_box_gap_dim
        }
      }
      {
        \dim_zero:N \l__dfg_collaboration_plot_box_width_dim
        \dim_zero:N \l__dfg_collaboration_plot_x_step_dim
      }
    \int_zero:N \l__dfg_collaboration_plot_row_index_int
    \seq_map_inline:Nn \l__dfg_collaboration_plot_areas_seq
      {
        \prop_get:NnN \l__dfg_collaboration_plot_area_nodes_prop {##1}
          \l_tmpa_tl
        \prop_get:NnN \l__dfg_collaboration_plot_area_color_prop {##1}
          \l__dfg_collaboration_plot_color_tl
        \__dfg_collaboration_plot_heatmap_row:VVn
          \l_tmpa_tl \l__dfg_collaboration_plot_color_tl {##1}
      }
  \end{tikzpicture}
}

\cs_new_protected:Npn \__dfg_collaboration_plot_arc_place_nodes:
{
  \int_set:Nn \l__dfg_collaboration_plot_node_count_int
    { \seq_count:N \l__dfg_collaboration_plot_nodes_seq }
  \int_compare:nNnTF
    { \l__dfg_collaboration_plot_node_count_int } > { 1 }
    {
      \dim_set:Nn \l__dfg_collaboration_plot_x_step_dim
      {
        ( \l__dfg_collaboration_plot_width_dim - 6mm ) /
        \int_eval:n { \l__dfg_collaboration_plot_node_count_int - 1 }
      }
    }
    { \dim_zero:N \l__dfg_collaboration_plot_x_step_dim }
  \int_zero:N \l__dfg_collaboration_plot_group_index_int
  \seq_map_inline:Nn \l__dfg_collaboration_plot_nodes_seq
  {
    \dim_set:Nn \l__dfg_collaboration_plot_x_dim
    {
      3mm + \l__dfg_collaboration_plot_x_step_dim
      * \l__dfg_collaboration_plot_group_index_int
    }
    \coordinate (dfg-collaboration-arc-##1) at
      (\dim_use:N \l__dfg_collaboration_plot_x_dim,0);
    \int_incr:N \l__dfg_collaboration_plot_group_index_int
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_draw_focus_arc:n #1
{
  \__dfg_collaboration_plot_unpack_edge:n {#1}
  \tl_clear:N \l__dfg_collaboration_plot_target_tl
  \str_if_eq:VVTF
    \l__dfg_collaboration_plot_edge_left_tl
    \l__dfg_collaboration_plot_focus_tl
    {
      \tl_set_eq:NN \l__dfg_collaboration_plot_target_tl
        \l__dfg_collaboration_plot_edge_right_tl
    }
    {
      \str_if_eq:VVT
        \l__dfg_collaboration_plot_edge_right_tl
        \l__dfg_collaboration_plot_focus_tl
      {
        \tl_set_eq:NN \l__dfg_collaboration_plot_target_tl
          \l__dfg_collaboration_plot_edge_left_tl
      }
  }
  \tl_if_blank:VF \l__dfg_collaboration_plot_target_tl
  {
    \exp_args:NV \__dfg_collaboration_plot_set_color:n
      \l__dfg_collaboration_plot_target_tl
    \draw[
      draw=\tl_use:N \l__dfg_collaboration_plot_color_tl,
      line~width=.75pt,
      opacity=.78,
      line~cap=round
    ]
      (dfg-collaboration-arc-\l__dfg_collaboration_plot_focus_tl)
      .. controls % chktex 12
      ($ (dfg-collaboration-arc-\l__dfg_collaboration_plot_focus_tl) % chktex 25
         + (0,\dim_use:N \l__dfg_collaboration_plot_arc_height_dim) $) % chktex 25 chktex 35
      and
      ($ (dfg-collaboration-arc-\l__dfg_collaboration_plot_target_tl) % chktex 25
         + (0,\dim_use:N \l__dfg_collaboration_plot_arc_height_dim) $) % chktex 25 chktex 35
      ..
      (dfg-collaboration-arc-\l__dfg_collaboration_plot_target_tl);
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_arc_node:n #1
{
  \__dfg_collaboration_plot_set_color:n {#1}
  \str_if_eq:VVTF
    \l__dfg_collaboration_plot_focus_tl
    \l__dfg_collaboration_plot_label_tl
  {
    \node[
      anchor=center,
      minimum~width=6mm,
      minimum~height=5mm,
      inner~sep=0pt,
      rounded~corners=1pt,
      draw=\tl_use:N \l__dfg_collaboration_plot_color_tl!78!black,
      fill=\tl_use:N \l__dfg_collaboration_plot_color_tl,
      text=white,
      font=\scriptsize\bfseries
    ] at (dfg-collaboration-arc-#1) {#1};
  }
  {
    \prop_if_in:NVTF \l__dfg_collaboration_plot_visible_prop
      \l__dfg_collaboration_plot_label_tl
    {
      \node[
        anchor=center,
        minimum~width=6mm,
        minimum~height=5mm,
        inner~sep=0pt,
        rounded~corners=.8pt,
        draw=\tl_use:N \l__dfg_collaboration_plot_color_tl!48,
        fill=\tl_use:N \l__dfg_collaboration_plot_color_tl!14,
        text=\tl_use:N \l__dfg_collaboration_plot_color_tl,
        font=\scriptsize\bfseries
      ] at (dfg-collaboration-arc-#1) {#1};
    }
    {
      \node[
        anchor=center,
        minimum~width=6mm,
        minimum~height=5mm,
        inner~sep=0pt,
        rounded~corners=.8pt,
        draw=grey!22,
        fill=white,
        text=grey!70!black,
        font=\scriptsize
      ] at (dfg-collaboration-arc-#1) {#1};
    }
  }
}

\cs_new_protected:Npn \__dfg_collaboration_plot_arc_group:nn #1#2
{
  \clist_if_empty:nF {#1}
  {
    \tl_set:Nx \l_tmpa_tl { \clist_item:nn {#1} { 1 } }
    \tl_set:Nx \l_tmpb_tl { \clist_item:nn {#1} { -1 } }
    \draw[draw=#2,line~width=.75pt,line~cap=round]
      ($ (dfg-collaboration-arc-\l_tmpa_tl) + (-3mm,-3.5mm) $) % chktex 25
      --
      ($ (dfg-collaboration-arc-\l_tmpb_tl) + (3mm,-3.5mm) $); % chktex 25
  }
}
\cs_generate_variant:Nn \__dfg_collaboration_plot_arc_group:nn { V V }

\cs_new_protected:Npn \__dfg_collaboration_plot_arc_picture:
{
  \begin{tikzpicture}
    \__dfg_collaboration_plot_arc_place_nodes:
    % Equal control-point heights give every symmetric cubic arc the same peak.
    \dim_set:Nn \l__dfg_collaboration_plot_arc_height_dim { 12mm }
    \bool_if:NT \l__dfg_collaboration_plot_arcs_bool
    {
      \seq_map_inline:Nn \l__dfg_collaboration_plot_edges_seq
        { \__dfg_collaboration_plot_draw_focus_arc:n {##1} }
    }
    \seq_map_inline:Nn \l__dfg_collaboration_plot_nodes_seq
      { \__dfg_collaboration_plot_arc_node:n {##1} }
    \seq_map_inline:Nn \l__dfg_collaboration_plot_areas_seq
      {
        \prop_get:NnN \l__dfg_collaboration_plot_area_nodes_prop {##1}
          \l_tmpa_tl
        \prop_get:NnN \l__dfg_collaboration_plot_area_color_prop {##1}
          \l__dfg_collaboration_plot_color_tl
        \__dfg_collaboration_plot_arc_group:VV
          \l_tmpa_tl \l__dfg_collaboration_plot_color_tl
      }
  \end{tikzpicture}
}

\cs_new_protected:Npn \__dfg_collaboration_plot_picture:
{
  \str_case:VnF \l__dfg_collaboration_plot_layout_tl
  {
    { heatmap } { \__dfg_collaboration_plot_heatmap_picture: }
    { arc }     { \__dfg_collaboration_plot_arc_picture: }
  }
  { \__dfg_collaboration_plot_arc_picture: }
}

% Both plot families explicitly allow here-or-bottom placement. A lone |h|
% is promoted to |ht| by LaTeX when here placement fails, which can put a plot
% at the top of the same page above its source section. Including |b| prevents
% that promotion while retaining ordinary floating, captions and hyperlinks.
% The bang retains the class default's relaxed float-fraction limits, so a
% moderately tall plot need not wait for a forced float page. This policy is
% local to generated plots; other figure placement is unchanged.
% Keep both caption variants at the captured body-text width without scaling
% the TikZ plot, even when the surrounding \linewidth is temporarily narrower.
\cs_new_protected:Npn \__dfg_collaboration_plot_full_width_picture:
{
  \makebox[\dim_use:N \l__dfg_collaboration_plot_width_dim][l]
    {\__dfg_collaboration_plot_picture:}
}


\prop_new:N \l__dfgcollab_projects_prop
\tl_new:N \l__dfgcollab_area_tl
\tl_new:N \l__dfgcollab_links_tl
\bool_new:N \l__dfgcollab_active_bool
\clist_new:N \l__dfgcollab_selection_clist
\clist_new:N \l__dfgcollab_override_clist
\prop_new:N \l__dfgcollab_selection_prop
\bool_new:N \l__dfgcollab_selection_bool
\bool_new:N \l__dfgcollab_override_bool
\tl_new:N \l__dfgcollab_colors_tl
\tl_new:N \l__dfgcollab_palette_tl
\keys_define:nn {dfgcollab/project}
  {
    area .tl_set:N = \l__dfgcollab_area_tl,
    collaboration .tl_set:N = \l__dfgcollab_links_tl,
    collaborations .meta:n = {collaboration={#1}},
    active .bool_set:N = \l__dfgcollab_active_bool,
  }
\keys_define:nn {dfgcollab/setup}
  {
    area-colors .tl_set:N = \l__dfgcollab_colors_tl,
    area-palette .tl_set:N = \l__dfgcollab_palette_tl,
    area-palette .initial:n = {blue!70!black,teal!80!black,orange!85!black,violet,brown},
  }
\NewDocumentCommand \CollaborationSetup {m}{\keys_set:nn {dfgcollab/setup}{#1}}
\NewDocumentCommand \clearCollaborationProjects {}{\prop_clear:N \l__dfgcollab_projects_prop}
\NewDocumentCommand \DeclareCollaborationProject {m m}
  {
    \regex_match:nnTF {\A[A-Za-z0-9][A-Za-z0-9-]*\Z}{#1}
      {
        \group_begin:
        \tl_set:Nn \l__dfgcollab_area_tl {#1}
        \tl_set:Ne \l__dfgcollab_area_tl {\tl_head:V \l__dfgcollab_area_tl}
        \tl_clear:N \l__dfgcollab_links_tl
        \bool_set_true:N \l__dfgcollab_active_bool
        \keys_set:nn {dfgcollab/project}{#2}
        \use:e {\group_end:
          \prop_put:Nnn \exp_not:N \l__dfgcollab_projects_prop {#1}
            {area={\exp_not:V \l__dfgcollab_area_tl},
             collaboration={\exp_not:V \l__dfgcollab_links_tl},
             active=\bool_if:NTF \l__dfgcollab_active_bool {true}{false}}}
      }
      {\msg_error:nnn {dfg-collaboration}{bad-id}{#1}}
  }
\msg_new:nnn {dfg-collaboration}{bad-id}{Invalid~project~ID~'#1'.~Use~letters,~digits,~and~hyphens.}
\msg_new:nnn {dfg-collaboration}{target-not-found}
  {Project~'#1'~references~unknown~collaboration~target~'#2'.}
\msg_new:nnn {dfg-collaboration}{focus-not-found}{Unknown~or~inactive~focus~project~'#1'.}
\msg_new:nnn {dfg-collaboration}{empty-palette}{The~area~palette~must~not~be~empty.}
\keys_define:nn {dfg / project-collaboration-plot}
  {
    collaboration .code:n =
      {\bool_set_true:N \l__dfgcollab_override_bool
       \clist_set:Nn \l__dfgcollab_override_clist {#1}},
    collaboration .value_required:n = true,
    collaborations .meta:n = {collaboration={#1}},
    show-projects .code:n =
      {\bool_set_true:N \l__dfgcollab_selection_bool
       \clist_set:Nn \l__dfgcollab_selection_clist {#1}},
    show-projects .value_required:n = true,
    projects .meta:n = {show-projects={#1}},
    projects .value_required:n = true,
    width .dim_set:N = \l__dfg_collaboration_plot_width_dim,
  }
\cs_new_protected:Npn \__dfgcollab_reset:
  {
    \bool_set_false:N \l__dfgcollab_selection_bool
    \bool_set_false:N \l__dfgcollab_override_bool
    \clist_clear:N \l__dfgcollab_selection_clist
    \clist_clear:N \l__dfgcollab_override_clist
    \keys_set:nn {dfg / project-collaboration-plot}{layout=arc,arcs=false}
  }
\cs_new_protected:Npn \__dfgcollab_select:
  {
    \bool_if:NT \l__dfgcollab_selection_bool
      {
        \prop_clear:N \l__dfgcollab_selection_prop
        \clist_map_inline:Nn \l__dfgcollab_selection_clist
          {\prop_put:Nnn \l__dfgcollab_selection_prop {##1}{1}}
        \prop_put:NVn \l__dfgcollab_selection_prop \l__dfg_collaboration_plot_focus_tl {1}
        \seq_map_inline:Nn \l__dfg_collaboration_plot_nodes_seq
          {\prop_if_in:NnF \l__dfgcollab_selection_prop {##1}
            {\seq_remove_all:Nn \l__dfg_collaboration_plot_nodes_seq {##1}
             \prop_remove:Nn \l__dfg_collaboration_plot_status_prop {##1}
             \prop_remove:Nn \l__dfg_collaboration_plot_lists_prop {##1}}}
      }
  }
\cs_new_protected:Npn \__dfgcollab_override_edges:
  {
    \bool_if:NT \l__dfgcollab_override_bool
      {
        \prop_map_inline:Nn \l__dfg_collaboration_plot_edges_prop
          {
            \__dfg_collaboration_plot_unpack_edge:n {##1}
            \bool_lazy_or:nnT
              {\str_if_eq_p:VV \l__dfg_collaboration_plot_edge_left_tl \l__dfg_collaboration_plot_focus_tl}
              {\str_if_eq_p:VV \l__dfg_collaboration_plot_edge_right_tl \l__dfg_collaboration_plot_focus_tl}
              {\prop_remove:Nn \l__dfg_collaboration_plot_edges_prop {##1}}
          }
        \clist_map_inline:Nn \l__dfgcollab_override_clist
          {\exp_args:NV \__dfg_collaboration_plot_collect_edge:nn
            \l__dfg_collaboration_plot_focus_tl {##1}}
      }
  }
\cs_new_protected:Npn \__dfgcollab_collect:
  {
    \seq_clear:N \l__dfg_collaboration_plot_nodes_seq
    \prop_clear:N \l__dfg_collaboration_plot_status_prop
    \prop_clear:N \l__dfg_collaboration_plot_all_status_prop
    \prop_clear:N \l__dfg_collaboration_plot_lists_prop
    \prop_clear:N \l__dfg_collaboration_plot_area_prop
    \prop_clear:N \l__dfg_collaboration_plot_edges_prop
    \prop_map_inline:Nn \l__dfgcollab_projects_prop
      {
        \keys_set:nn {dfgcollab/project}{##2}
        \prop_put:Nnn \l__dfg_collaboration_plot_all_status_prop {##1}{C}
        \bool_if:NT \l__dfgcollab_active_bool
          {\seq_put_right:Nn \l__dfg_collaboration_plot_nodes_seq {##1}
           \prop_put:Nnn \l__dfg_collaboration_plot_status_prop {##1}{C}
           \prop_put:NnV \l__dfg_collaboration_plot_area_prop {##1}\l__dfgcollab_area_tl
           \prop_put:NnV \l__dfg_collaboration_plot_lists_prop {##1}\l__dfgcollab_links_tl}
      }
    \seq_sort:Nn \l__dfg_collaboration_plot_nodes_seq
      {\str_compare:eNeTF
        {\prop_item:Nn \l__dfg_collaboration_plot_area_prop {##1}/##1}<
        {\prop_item:Nn \l__dfg_collaboration_plot_area_prop {##2}/##2}
        {\sort_return_same:}{\sort_return_swapped:}}
    \__dfgcollab_select:
  }
\NewDocumentCommand \CollaborationPlot {O{} m}
  {
    \group_begin:
    \__dfgcollab_reset:
    \dim_set:Nn \l__dfg_collaboration_plot_width_dim {\linewidth}
    \exp_args:NNV \prop_set_from_keyval:Nn \l__dfg_collaboration_plot_area_color_override_prop
      \l__dfgcollab_colors_tl
    \exp_args:NNV \seq_set_from_clist:Nn \l__dfg_collaboration_plot_area_palette_seq
      \l__dfgcollab_palette_tl
    \tl_clear:N \l__dfg_collaboration_plot_caption_tl
    \__dfgplots_options:nnn {dfg / project-collaboration-plot}{collaboration}{#1}
    \seq_if_empty:NT \l__dfg_collaboration_plot_area_palette_seq
      {\msg_error:nn {dfg-collaboration}{empty-palette}
       \seq_put_right:Nn \l__dfg_collaboration_plot_area_palette_seq {blue}}
    \tl_set:Nn \l__dfg_collaboration_plot_focus_tl {#2}
    % An explicit one-off link list is a complete ID-only dataset when none exists.
    \prop_if_empty:NT \l__dfgcollab_projects_prop
      {\bool_if:NT \l__dfgcollab_override_bool
        {\DeclareCollaborationProject{#2}{}
         \clist_map_inline:Nn \l__dfgcollab_override_clist
           {\DeclareCollaborationProject{##1}{}}}}
    \__dfgcollab_collect:
    \prop_if_in:NnTF \l__dfg_collaboration_plot_status_prop {#2}
      {
        \__dfg_collaboration_plot_collect_edges:
        \__dfg_collaboration_plot_prepare:
        \__dfgplots_float: {figure}{\__dfg_collaboration_plot_full_width_picture:}
          {Collaborations~of~#2.\tl_if_blank:VF \l__dfg_collaboration_plot_caption_tl
            {~\tl_use:N \l__dfg_collaboration_plot_caption_tl}}
          {fig:project-collaboration-#2-\tl_use:N \l__dfg_collaboration_plot_layout_tl}
      }
      {\msg_error:nnn {dfg-collaboration}{focus-not-found}{#2}}
    \group_end:
  }
\dfgDeclarePlotType{collaboration}{\CollaborationPlot}
\dfgDeclarePlotType{collaborations}{\CollaborationPlot}
\dfgDeclarePlotType{ProjectCollaboration}{\CollaborationPlot}
\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</collaboration-package>
%<*gantt-package>
% \fi
% \subsection{Reusable package: dfg-gantt.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplPackage{dfg-gantt}{2026-11-24}{0.4.0}{Workpackages and independent Gantt charts}
\ExplSyntaxOff
\RequirePackage{dfg-plots}
\RequirePackage{pgfgantt}
\RequirePackage{datatool}
\RequirePackage{enumitem}
\RequirePackage{etoolbox}
\usetikzlibrary{patterns,patterns.meta}
\providecolor{tableHeadingsBG}{rgb}{.80,.88,.95}
\providecolor{tableOuterLines}{gray}{.15}
\providecolor{tableHeadingsFont}{gray}{.1}
\providecolor{color@gantt@frame}{gray}{.2}
\providecolor{color@gantt@default}{rgb}{.7,.82,.95}
\providecolor{color@gantt@alternative}{rgb}{.7,.9,.75}
\providecolor{color@gantt@important}{rgb}{.95,.7,.6}
\providecolor{color@gantt@crosshatch}{gray}{.4}
\providecolor{color@gantt@stripe-one}{rgb}{.7,.82,.95}
\providecolor{color@gantt@stripe-two}{rgb}{.5,.75,.6}
\ExplSyntaxOn
\prop_new:N \l__dfg_wp_legacy_prop
\prop_new:N \l__dfg_wp_new_prop
\prop_new:N \l__dfg_wp_fields_prop
\bool_new:N \l__dfg_wp_new_syntax_bool
\tl_new:N \l__dfg_wp_normalized_tl
\tl_new:N \l__dfg_wp_unknown_tl
\keys_define:nn { dfg / workpackage }
{
  title .code:n =
    {
      \bool_set_true:N \l__dfg_wp_new_syntax_bool
      \prop_put:Nnn \l__dfg_wp_new_prop {name} {#1}
    },
  title .value_required:n = true,
  gantt .code:n =
    {
      \bool_set_true:N \l__dfg_wp_new_syntax_bool
      \keys_set:nn { dfg / workpackage / gantt } {#1}
    },
  gantt .value_required:n = true,
  id .code:n = \prop_put:Nnn \l__dfg_wp_legacy_prop {id} {#1},
  name .code:n = \prop_put:Nnn \l__dfg_wp_legacy_prop {name} {#1},
  description .code:n =
    \prop_put:Nnn \l__dfg_wp_legacy_prop {description} {#1},
  periodStart .code:n =
    \prop_put:Nnn \l__dfg_wp_legacy_prop {periodStart} {#1},
  periodEnd .code:n =
    \prop_put:Nnn \l__dfg_wp_legacy_prop {periodEnd} {#1},
  style .code:n = \prop_put:Nnn \l__dfg_wp_legacy_prop {style} {#1},
}
\keys_define:nn { dfg / workpackage / gantt }
{
  label .code:n = \prop_put:Nnn \l__dfg_wp_new_prop {description} {#1},
  start .code:n = \prop_put:Nnn \l__dfg_wp_new_prop {periodStart} {#1},
  end .code:n = \prop_put:Nnn \l__dfg_wp_new_prop {periodEnd} {#1},
  style .code:n = \prop_put:Nnn \l__dfg_wp_new_prop {style} {#1},
  label .value_required:n = true,
  start .value_required:n = true,
  end .value_required:n = true,
  style .value_required:n = true,
}
\cs_new_protected:Npn \__dfg_workpackage_normalize:n #1
{
  \prop_clear:N \l__dfg_wp_legacy_prop
  \prop_clear:N \l__dfg_wp_new_prop
  \bool_set_false:N \l__dfg_wp_new_syntax_bool
  \keys_set_known:nnN { dfg / workpackage } {#1} \l__dfg_wp_unknown_tl
  \bool_if:NTF \l__dfg_wp_new_syntax_bool
    {
      \prop_set_eq:NN \l__dfg_wp_fields_prop \l__dfg_wp_legacy_prop
      \prop_map_inline:Nn \l__dfg_wp_new_prop
        { \prop_put:Nnn \l__dfg_wp_fields_prop {##1} {##2} }
      \prop_if_in:NnF \l__dfg_wp_fields_prop {description}
        {
          \prop_get:NnNT \l__dfg_wp_fields_prop {name} \l_tmpa_tl
            { \prop_put:NnV \l__dfg_wp_fields_prop {description} \l_tmpa_tl }
        }
      \prop_if_in:NnF \l__dfg_wp_fields_prop {style}
        { \prop_put:Nnn \l__dfg_wp_fields_prop {style} {default} }
      \tl_clear:N \l__dfg_wp_normalized_tl
      \prop_map_inline:Nn \l__dfg_wp_fields_prop
        { \tl_put_right:Nn \l__dfg_wp_normalized_tl {##1={##2},} }
      \tl_put_right:NV \l__dfg_wp_normalized_tl \l__dfg_wp_unknown_tl
    }
    { \tl_set:Nn \l__dfg_wp_normalized_tl {#1} }
}

\int_new:N \l__dfggantt_slots_int
\int_new:N \l__dfggantt_first_quarter_int
\int_new:N \l__dfggantt_remaining_int
\int_new:N \l__dfggantt_group_int
\int_new:N \l__dfggantt_year_int
\int_new:N \l__dfggantt_quarter_int
\clist_new:N \l__dfggantt_year_labels_clist
\tl_new:N \l__dfggantt_project_tl
\tl_new:N \l__dfggantt_name_tl
\tl_new:N \l__dfggantt_description_tl
\tl_new:N \l__dfggantt_start_tl
\tl_new:N \l__dfggantt_end_tl
\tl_new:N \l__dfggantt_style_tl
\tl_new:N \l__dfggantt_caption_tl
\bool_new:N \l__dfggantt_valid_bool
\msg_new:nnn {dfg-gantt}{bad-range}{Invalid~period~range~'#1'.~Use~nonnegative~integers~with~start~<=~end.}
\msg_new:nnn {dfg-gantt}{missing-project}{Set~a~project~with~\string\GanttProject~before~adding~workpackages.}
\msg_new:nnn {dfg-gantt}{missing-data}{No~workpackages~declared~for~project~'#1'.}
\msg_new:nnn {dfg-gantt}{bad-grid}{Use~positive~slots~and~first-quarter~between~1~and~4.}
\cs_new_protected:Npn \__dfggantt_validate_grid:
  {
    \bool_lazy_or:nnT
      {\int_compare_p:n {\l__dfggantt_slots_int < 1}}
      {\bool_lazy_or_p:nn
        {\int_compare_p:n {\l__dfggantt_first_quarter_int < 1}}
        {\int_compare_p:n {\l__dfggantt_first_quarter_int > 4}}}
      {\msg_error:nn {dfg-gantt}{bad-grid}
       \int_set:Nn \l__dfggantt_slots_int {16}
       \int_set:Nn \l__dfggantt_first_quarter_int {3}}
  }
\keys_define:nn {dfggantt/chart}
  {
    slots .int_set:N = \l__dfggantt_slots_int,
    slots .initial:n = 16,
    first-quarter .int_set:N = \l__dfggantt_first_quarter_int,
    first-quarter .initial:n = 3,
    year-labels .clist_set:N = \l__dfggantt_year_labels_clist,
  }
\keys_define:nn {dfggantt/plot}
  {
    slots .meta:nn = {dfggantt/chart}{slots=#1},
    first-quarter .meta:nn = {dfggantt/chart}{first-quarter=#1},
    year-labels .meta:nn = {dfggantt/chart}{year-labels={#1}},
    caption .tl_set:N = \l__dfggantt_caption_tl,
  }
\NewDocumentCommand \GanttSetup {m}
  {\keys_set:nn {dfggantt/chart}{#1}\__dfggantt_validate_grid:}
\ProvideDocumentCommand \dfgFundingYear {m}{Year~#1}
\ProvideDocumentCommand \DFGGanttTag {mmmm}{#3}
\ProvideDocumentCommand \DFGGanttLabel {mm}
  {WP~\cs_if_exist:cTF {r@#1-wp-#2}{\ref{#1-wp-#2}}{#2}}
\NewDocumentCommand \DFGGanttTitles {}
  {
    \__dfggantt_validate_grid:
    \int_set_eq:NN \l__dfggantt_remaining_int \l__dfggantt_slots_int
    \int_set:Nn \l__dfggantt_group_int {5-\l__dfggantt_first_quarter_int}
    \int_set:Nn \l__dfggantt_year_int {1}
    \int_while_do:nn {\l__dfggantt_remaining_int > 0}
      {
        \int_set:Nn \l__dfggantt_group_int
          {\int_min:nn {\l__dfggantt_group_int}{\l__dfggantt_remaining_int}}
        \gantttitle[dfgTitleTopRule]
          {\int_compare:nNnTF {\clist_count:N \l__dfggantt_year_labels_clist}
            < {\l__dfggantt_year_int}
            {\dfgFundingYear{\int_use:N\l__dfggantt_year_int}}
            {\clist_item:Nn \l__dfggantt_year_labels_clist {\l__dfggantt_year_int}}}
          {\int_use:N\l__dfggantt_group_int}
        \int_sub:Nn \l__dfggantt_remaining_int {\l__dfggantt_group_int}
        \int_set:Nn \l__dfggantt_group_int {4}
        \int_incr:N \l__dfggantt_year_int
      }
    \ganttnewline
    \int_step_inline:nn {\l__dfggantt_slots_int}
      {
        \int_set:Nn \l__dfggantt_quarter_int
          {1+\int_mod:nn {\l__dfggantt_first_quarter_int+##1-2}{4}}
        \int_compare:nNnTF {\l__dfggantt_quarter_int}={4}
          {\gantttitle[dfgTitleBottomRightRule]
            {\dfgGanttShowQs{Q\int_use:N\l__dfggantt_quarter_int}{##1}}{1}}
          {\gantttitle[dfgTitleBottomRule]
            {\dfgGanttShowQs{Q\int_use:N\l__dfggantt_quarter_int}{##1}}{1}}
      }
    \ganttnewline
  }
\cs_if_exist:NF \workpackages
  {
    \newlist{workpackages}{enumerate}{3}
    \setlist[workpackages,1]{leftmargin=*,font=\bfseries,label={WP\,\arabic*:},ref={\arabic*}}
    \setlist[workpackages,2]{leftmargin=*,font=\bfseries,label={WP\,\theworkpackagesi\alph*:},ref={\theworkpackagesi\alph*}}
    \setlist[workpackages,3]{leftmargin=*,label={WP\,\theworkpackagesii.\roman*:}}
  }
\NewDocumentCommand \GanttProject {m}
  {\tl_set:Nn \l__dfggantt_project_tl {#1}\dfgPlotProject{#1}}
\keys_define:nn {dfggantt/record}
  {
    id .code:n = {},
    name .tl_set:N = \l__dfggantt_name_tl,
    description .tl_set:N = \l__dfggantt_description_tl,
    periodStart .tl_set:N = \l__dfggantt_start_tl,
    periodEnd .tl_set:N = \l__dfggantt_end_tl,
    style .tl_set:N = \l__dfggantt_style_tl,
  }
\cs_new_protected:Npn \__dfggantt_store:nnn #1#2#3
  {
    \__dfg_workpackage_normalize:n {#3}
    \keys_set:nn {dfggantt/record}{name={},description={},periodStart=1,periodEnd=1,style=default}
    \exp_args:NnV \keys_set:nn {dfggantt/record}\l__dfg_wp_normalized_tl
    \bool_set_true:N \l__dfggantt_valid_bool
    \exp_args:NnV \regex_match:nnF {\A\d+\Z}\l__dfggantt_start_tl
      {\bool_set_false:N \l__dfggantt_valid_bool}
    \exp_args:NnV \regex_match:nnF {\A\d+\Z}\l__dfggantt_end_tl
      {\bool_set_false:N \l__dfggantt_valid_bool}
    \bool_if:NT \l__dfggantt_valid_bool
      {\int_compare:nNnT {\l__dfggantt_start_tl}>{\l__dfggantt_end_tl}
        {\bool_set_false:N \l__dfggantt_valid_bool}}
    \bool_if:NTF \l__dfggantt_valid_bool
      {
        \DTLifdbexists{gantt-#1}{}{\DTLnewdb{gantt-#1}}
        \DTLnewrow{gantt-#1}
        \DTLnewdbentry{gantt-#1}{id}{#2}
        \clist_map_inline:nn {name,description,periodStart,periodEnd,style}
          {
            \str_case:nn {##1}
              {{name}{\tl_set_eq:NN \l_tmpa_tl \l__dfggantt_name_tl}
               {description}{\tl_set_eq:NN \l_tmpa_tl \l__dfggantt_description_tl}
               {periodStart}{\tl_set_eq:NN \l_tmpa_tl \l__dfggantt_start_tl}
               {periodEnd}{\tl_set_eq:NN \l_tmpa_tl \l__dfggantt_end_tl}
               {style}{\tl_set_eq:NN \l_tmpa_tl \l__dfggantt_style_tl}}
            \use:e {\exp_not:N\DTLnewdbentry{gantt-#1}{##1}{\exp_not:V\l_tmpa_tl}}
          }
      }
      {\msg_error:nne {dfg-gantt}{bad-range}{\l__dfggantt_start_tl--\l__dfggantt_end_tl}}
  }
\NewDocumentCommand \DeclareWorkPackage {mmm}{\__dfggantt_store:nnn {#1}{#2}{#3}}
\ProvideDocumentCommand \addWP {mm}
  {
    \tl_if_blank:VTF \l__dfggantt_project_tl
      {\msg_error:nn {dfg-gantt}{missing-project}}
      {
        \exp_args:NV \__dfggantt_store:nnn \l__dfggantt_project_tl {#1}{#2}
        \item \str_if_eq:eeT {\@enumctr}{workpackagesi}
          {\textbf{\tl_use:N \l__dfggantt_name_tl}\space}
        \label{\l__dfggantt_project_tl-wp-#1}\ignorespaces
      }
  }
\ProvideDocumentCommand \getWP {O{} m}
  {
    \group_begin:
    \tl_if_blank:nF {#1}{\tl_set:Nn \l__dfggantt_project_tl {#1}}
    \clist_set:Nn \l_tmpa_clist {#2}
    \int_zero:N \l_tmpa_int
    \clist_map_inline:Nn \l_tmpa_clist
      {\int_incr:N \l_tmpa_int
       \int_compare:nNnT {\l_tmpa_int}>{1}{,~}
       \DFGGanttLabel{\l__dfggantt_project_tl}{##1}}
    \group_end:
  }
\NewDocumentCommand \GanttChart {O{} m}{\dfgGanttEnvironment[#1]{#2}}
\NewDocumentCommand \GanttPlotFigure {O{} m}
  {
    \group_begin:
    \tl_clear:N \l__dfggantt_caption_tl
    \__dfgplots_options:nnn {dfggantt/plot}{gantt}{#1}
    \DTLifdbexists{gantt-#2}
      {\__dfgplots_float: {figure}{\dfgGanttEnvironment{#2}}
        {Gantt~chart~of~#2.\tl_if_blank:VF \l__dfggantt_caption_tl
          {~\tl_use:N\l__dfggantt_caption_tl}}{fig:gantt-#2}}
      {\msg_error:nnn {dfg-gantt}{missing-data}{#2}}
    \group_end:
  }
\dfgDeclarePlotType{gantt}{\GanttPlotFigure}
\dfgDeclarePlotType{Gantt}{\GanttPlotFigure}
\tl_new:N \l__dfg_gantt_stripe_color_model_tl
\tl_new:N \l__dfg_gantt_stripe_color_spec_tl
\pgfdeclarepattern{
  name = dfg~gantt~stripes,
  type = colored,
  parameters = {
    \l__dfg_gantt_stripe_color_model_tl,
    \l__dfg_gantt_stripe_color_spec_tl
  },
  bottom~left = {\pgfpoint{-6pt}{-6pt}},
  top~right = {\pgfpoint{6pt}{6pt}},
  tile~size = {\pgfpoint{12pt}{12pt}},
  tile~transformation = {\pgftransformrotate{45}},
  code = {
    \pgfsetstrokecolor{dfgGanttStripeColor}
    \pgfsetlinewidth{6pt}
    \pgfpathmoveto{\pgfpoint{-6pt}{0pt}}
    \pgfpathlineto{\pgfpoint{6pt}{0pt}}
    \pgfusepath{stroke}
  },
}
\bool_new:N \l__dfg_gantt_first_bar_bool
\NewDocumentCommand{\dfgGanttContent}{m}{%
  % Resolve the active colour model before extracting the cache parameters.
  \colorlet{dfgGanttStripeColor}{color@gantt@stripe-two}
  \extractcolorspecs{dfgGanttStripeColor}
    {\l__dfg_gantt_stripe_color_model_tl}{\l__dfg_gantt_stripe_color_spec_tl}
  \bool_set_true:N \l__dfg_gantt_first_bar_bool
  \DTLforeach*{gantt-#1}{%
    \ganttWP=id,%
    \ganttName=name,%
    \ganttDescription=description,%
    \ganttPeriodStart=periodStart,%
    \ganttPeriodEnd=periodEnd,%
    \ganttPatternbar=style%
  }{%
    % If we want to omit a bar in the plot,
    % you need to set periodStart and periodEnd
    % the same value.
    \ifdefstrequal{\ganttPeriodStart}{\ganttPeriodEnd}{}{%
      % if the values are different then there will be a bar.
    \bool_if:NTF \l__dfg_gantt_first_bar_bool
      { \bool_set_false:N \l__dfg_gantt_first_bar_bool }
      { \ganttnewline }
    \def\ganttBarPlot{
      \sffamily
      \DFGGanttTag{\ganttWP}{id}{\DFGGanttLabel{#1}{\ganttWP}}{gantt-#1}
      \ifdefempty{\ganttDescription}{}
        {:~\DFGGanttTag{\ganttWP}{description}{\ganttDescription}{gantt-#1}}}

      \str_case:VnF {\ganttPatternbar}
      {%
        {crosshatch}{\ganttbar[bar/.append~ style = {%
                pattern       = {crosshatch},
                pattern~ color = {color@gantt@crosshatch},
                draw           = {color@gantt@frame}
              }]{\ganttBarPlot}{\ganttPeriodStart}{\ganttPeriodEnd}}%

        {striped}{\ganttbar[bar/.append~ style = {%
                fill          = {color@gantt@stripe-one},
                % the pattern needs to be applied after the filled color
              postaction    ={pattern={dfg~gantt~stripes}},
                postaction    = {draw, semithick},
                draw          = {color@gantt@frame}
              }]{\ganttBarPlot}{\ganttPeriodStart}{\ganttPeriodEnd}}%

        {alternative}{\ganttbar[bar/.append~ style = {%
                fill          = {color@gantt@alternative},
                draw          = {color@gantt@frame}
              }]{\ganttBarPlot}{\ganttPeriodStart}{\ganttPeriodEnd}}%

        {important}{\ganttbar[bar/.append~ style = {%
                fill          = {color@gantt@important},
                draw          = {color@gantt@frame}
              }]{\ganttBarPlot}{\ganttPeriodStart}{\ganttPeriodEnd}}%
      }
      { % default
        {}{\ganttbar[bar/.append~ style = {%
                fill          = {color@gantt@default},
                draw          = {color@gantt@frame}
              }]{\ganttBarPlot}{\ganttPeriodStart}{\ganttPeriodEnd}}%
      }
    }%
    }
}
% The following macro makes it easier to debug the position of the bars.
\ProvideDocumentCommand\dfgGanttShowQs{mm}{#1}
\NewDocumentCommand{\dfgGanttEnvironment}{O{} m}{
  \group_begin:
  \keys_set:nn {dfggantt/chart}{#1}
  \__dfggantt_validate_grid:
  % #2 : Project ID
  \resizebox{\linewidth}{!}{
    \begin{ganttchart}[
        title~ height=.8,
        title/.append~ style={draw=none, fill=tableHeadingsBG},
        dfgTitleTopRule/.style={
          title/.append~ style={
            path~ picture={
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.north~ west) --
                (path~ picture~ bounding~ box.north~ east);
            }}},
        dfgTitleBottomRule/.style={
          title/.append~ style={
            path~ picture={
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.south~ west) --
                (path~ picture~ bounding~ box.south~ east);
            }}},
        dfgTitleBottomRightRule/.style={
          title/.append~ style={
            path~ picture={
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.south~ west) --
                (path~ picture~ bounding~ box.south~ east);
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.north~ east) --
                (path~ picture~ bounding~ box.south~ east);
            }}},
        title~ label~ font={\bfseries\footnotesize\color{tableHeadingsFont}},
        canvas/.style={
            shape=rectangle,
            draw=none,
            fill=white,
            path~ picture={
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.north~ west) --
                (path~ picture~ bounding~ box.north~ east);
              \draw[draw=tableOuterLines,line~ width=2pt]
                (path~ picture~ bounding~ box.south~ west) --
                (path~ picture~ bounding~ box.south~ east);
            }},
        x~ unit = \linewidth/\int_use:N\l__dfggantt_slots_int,
        y~ unit~ title=0.5cm,
        y~ unit~ chart=.5cm,
      vgrid={*1{tableOuterLines,dashed}},
        %hgrid,
        %   group label font=\bfseries\footnotesize,
        %   milestone label font=\scriptsize,
        bar~ inline~ label~ node/.style={anchor=west},
        bar~ inline~ label~ anchor=west,
        bar~ label~ font={\scriptsize\color{tableHeadingsFont}},
        %  title label font=\bfseries\scriptsize\color{white},
        % bar/.style={rounded~ corners=1mm},
      bar~ top~ shift=0,
      bar~ height=.9,
        inline
      ]{1}{\int_use:N\l__dfggantt_slots_int}
    \DFGGanttTitles
  \dfgGanttContent{#2}
    \end{ganttchart}%
  }
  \group_end:
}
\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</gantt-package>
%<*timeline-package>
% \fi
% \subsection{Reusable package: dfg-timeline.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
% ============================================================================
% EVENT TIMELINES -- quick reference and visual overview
% ============================================================================
% Complete guide, copyable examples and option tables are included below.
% Documentation is maintained in this file.
%
% LOAD ONCE IN THE PREAMBLE
%   This proposal loads the module through dfg-customization.tex.
%   Other projects: copy this file, then use \usepackage{dfg-timeline}.
%   TikZ, FontAwesome5 and enumitem are loaded automatically. No DFG class,
%   proposal metadata or other preamble files are needed. Repeated input is safe.
%   Existing definitions of the Event* colours are preserved.
%
% VISUAL OVERVIEW (positive rotation; schematic, not to scale)
%
%                                      Event label
%                                    /
%                            [icon] /   rotation
%                                  A    label BEGINS here
%                                  |
%              connector width --> |    label distance + lane * lane spacing
%                                  |
%    ------------------------------o=============|-------------------
%    |<----------------------- width ------------------------------>|
%                                  |             ^ end of a range
%         date connector width --> |    date distance
%                                  B    date ENDS here
%                                 /
%                    ISO date(s) /      date rotation
%
%    o    start point; dot radius sets its size
%    ===  optional event span; range width sets span/end-tick thickness
%    ---  main axis; line width sets its thickness
%    A/B  label/date anchors; xshift and yshift move text relative to its point
%    The date connector stays vertical, stopping 1pt above the selected digit.
%    date direction=left (default) connects to the last digit; right to the first.
%
%    lane=0 is closest above the axis; lane=1,2,... move labels further up.
%    date lane=0 is closest below; higher date lanes move dates further down.
%    Identical starts share a black point. Identical start/end pairs also share
%    one date label, whose formatting comes from the first event.
%
% MAIN COMMANDS
%   \clearEvents                 start a fresh event collection
%   \addEvent[formatting]{data}   store one event (see the two sections below)
%   \printEventTimeline[options]  draw the selected events
%   \printEventDetails[options]   print full titles and descriptions
%
% COPYABLE CALLS (all braces balanced on each comment line)
%   \addEvent{date=2025-01,category=retreat,title={Annual retreat}}
%   \addEvent[lane=1]{date=2025-01,category=progress,title={Progress day}}
%   \addEvent[date direction=right]{date=2025-01,category=progress,title={Progress day}}
%   \addEvent{date=2026-06-28,end date=2026-06-30,category=retreat,title={Retreat}}
%   \printEventTimeline[width=.9\linewidth,rotation=45,year=2025]
%   \printEventTimeline[labels=abbreviation,legend=false]
%   \printEventTimeline[show dates=false,show labels=false,icons=false,legend=false]
%   \printEventTimeline[line width=1pt,connector width=.7pt,date connector width=.7pt]
%   \printEventDetails[format=prose,year=2025]
%   \printEventDetails[format=prose,nodate,aggregated]
%   \printEventDetails[format=prose,show dates=false,aggregated]
%
% EVENT DATA -- mandatory argument of \addEvent
%   date / start date  required ISO start; two names for the same field
%   end date           optional inclusive end; default = start
%   category           required declared category (presets below)
%   title              required full title; default heading in printed details
%   id                 unique identifier; default = event-N
%   label              short chart label; default = title
%   abbreviation       shortest chart label; fallback = label, then title
%   summary            optional extra chart line, shown with summary=true
%   description        full account for list/prose details
%   icon               replacement in the chart and individual-event details
%
%   ISO syntax: YYYY-MM or YYYY-MM-DD; calendar dates and range order are checked.
%   Months sit at their centre; exact days sit at their day centre within the
%   month. Months have equal widths on the calendar scale. Sorting follows
%   these positions; ties preserve source order.
%   Ranges draw a coloured span from start to end. A year filter includes any
%   overlapping range, clipping its span with continuation arrows as needed.
%   Date labels and details retain the original, complete range when shown.
%
% CHART OPTIONS -- \printEventTimeline[...]
%   option                default            meaning
%   width                 \linewidth         total graphic width
%   year                  all                all events, or one four-digit year
%   rotation              30                 upper-label angle in degrees
%   date rotation         auto               follow each label's effective angle
%   labels                label              title | label | abbreviation
%   show labels           true               show upper text and its connectors
%   show dates            true               show lower dates and their connectors
%   summary               false              show each event's summary
%   icons                 true               show category/event icons
%   legend                true               show categories present in the plot
%   label width           0pt                natural width; >0 wraps label text
%   label distance        1.8mm              gap from axis to lowest label edge
%   lane                  auto               automatic, or a nonnegative integer
%   lane spacing          auto               text height + gap, or a positive dim.
%   date lane             auto               automatic, or a nonnegative integer
%   date distance         1.8mm              gap from axis to highest date edge
%   date lane spacing     auto               date height + gap, or a positive dim.
%   gap                   .8mm               collision clearance
%   font                  sans 7.4pt / 9pt   font used for chart labels
%   date font             sans 6.5pt / 8pt   font used for dates
%   line color            EventMuted!40      axis colour
%   line width            .6pt               axis thickness
%   connector width       .35pt              upper leader thickness
%   date connector width  .3pt               lower leader thickness
%   range width           1.2pt              event span/end-tick thickness
%   dot radius            .9mm               start-point radius
%   events                empty              temporary per-ID formatting overrides
%
% PER-EVENT FORMATTING -- optional argument of \addEvent, or events={id={...}}
%   lane, rotation, date rotation, label width, font, date lane
%     inherit their corresponding chart-wide defaults.
%   xshift, yshift, date xshift, date yshift
%     default to 0pt; positive x = right, positive y = up.
%   date direction
%     left (default): date extends left of its last digit; right: from its first.
%   label, icon
%     replace chart text/icon only; full details keep their stored content.
%   node options
%     default empty; advanced TikZ appearance options for the upper label.
%   Example: \printEventTimeline[events={event-1={lane=1,xshift=2mm}}]
%
%   Precedence: chart defaults -> stored event formatting -> events overrides.
%   Each print call is local. Explicit lanes are reserved before automatic
%   placement and can overlap; auto avoids collisions. Same-date automatic
%   labels follow source order from the axis upwards, regardless of length.
%
% DETAILS OPTIONS -- \printEventDetails[...]
%   format  list (default) | prose   list uses footnotesize; prose inherits font
%   year    all (default) | YYYY     same overlap rule as the chart
%   icons   true (default) | false   coloured icons in both formats
%   nodate  false (default) | true   omit generated dates/ranges and punctuation
%   show dates true (default)       inverse of nodate; last supplied key wins
%   aggregated false (default)      one block per category, deduplicating content
%   categories {} (default)         per-category title/description overrides
%   Bare nodate/aggregated mean true. All settings are local to this print call.
%   Set year explicitly on BOTH print commands when showing a filtered figure.
%   Different texts are retained; categories={retreat={description={Summary.}}}
%   replaces that category's subentries only when aggregated=true.
%
% CATEGORY PRESETS -- key / legend / colour / FontAwesome5 icon
%   retreat     / Annual retreat  / EventRetreat     (violet)   / \faUsers
%   progress    / Progress day    / EventProgress    (petrol)   / \faComments
%   networking  / Networking      / EventNetworking  (orange)   / \faHandshake
%   graduate    / Graduate school retreat / EventGraduate (magenta) / \faGraduationCap
%   symposium   / International symposium / EventSymposium (bordeaux) / \faGlobe
%   Add/change: \DeclareEventCategory{conference}{Conference}{EventSymposium}{\faGlobe}
%
% VALIDATION AND MAINTENANCE
%   Duplicate event IDs warn and skip the later entry; the first is retained.
%   Width must be positive. Lane spacings must be auto or positive dimensions;
%   gap, distances, text width, stroke widths and radius cannot be negative.
%   Invalid spacing reports an error and recovers to auto if compilation
%   continues. Automatic placement stops with an error after 1000 attempts.
%   Full examples cover hvFloat captions and narrow/crowded charts in the guide.
%   Regression tests: python3 __admin/scripts/test_event_timeline.py -q
% ============================================================================
% BEGIN FULL EVENT TIMELINE GUIDE
% Full guide maintained in this comment block.
% # Event timelines
%
% The timeline module stores event content once and renders a horizontal chart,
% a description list, or continuous prose. It supports month and day precision,
% multi-day ranges, year filters, category icons, and automatic or manual layout.
%
% The implementation is [dfg-event-timeline.tex](../preamble/dfg-event-timeline.tex).
% Its comment header includes an ASCII diagram, a compact option reference, and
% this complete guide as comments.
%
% ## Use in another project
%
% Copy **only** `dfg-timeline.sty` into the new project and load it
% in the preamble. The file loads TikZ, FontAwesome5, and enumitem automatically.
% It needs no DFG class, proposal metadata, fonts, or other proposal files.
% The packages must be installed in the target TeX distribution.
%
% The module is tested with LuaLaTeX and pdfLaTeX. This proposal continues to use
% LuaLaTeX as required by its document class. Repeated input is safe and preserves
% events already declared. Existing `Event*` colour definitions are preserved.
%
% This is a complete document using the standard `figure` environment:
%
% ```latex
% \documentclass{article}
% \usepackage{dfg-timeline}
%
% \begin{document}
% \clearEvents
%
% \addEvent{
%   id           = graduate-2025,
%   date         = 2025-01,
%   category     = graduate,
%   title        = {Graduate School retreat},
%   label        = {Graduate retreat},
%   abbreviation = {GSR},
%   description  = {A dedicated meeting for doctoral researchers.}
% }
% \addEvent{
%   id           = progress-2025-01,
%   date         = 2025-01,
%   category     = progress,
%   title        = {Progress day},
%   abbreviation = {PD},
%   description  = {Project presentations and discussion.}
% }
% \addEvent{
%   id           = symposium-2026,
%   start date   = 2026-06-28,
%   end date     = 2026-06-30,
%   category     = symposium,
%   title        = {International Symposium},
%   label        = {Int. Symposium},
%   abbreviation = {IS},
%   summary      = {Invited talks and posters},
%   description  = {Research presentations and discussion with invited speakers.}
% }
%
% \begin{figure}[htbp]
%   \centering
%   \printEventTimeline[width=\linewidth,rotation=45]
%   \caption[Retreats, progress days and symposia.]{%
%     Retreats, progress days and symposia.\\
%     \printEventDetails[format=prose]}
%   \label{fig:event-timeline}
% \end{figure}
% \end{document}
% ```
%
% The first two events share a black point. Their labels follow declaration order:
% the graduate retreat is closer to the line and the progress day is above it.
% The symposium has a date range and a coloured span.
%
% The module defines `\clearEvents`, `\addEvent`, `\printEventTimeline`,
% `\printEventDetails`, and `\DeclareEventCategory`; these names must be available
% in the target project.
%
% ## Use in this proposal and with `hvFloat`
%
% This proposal already loads the module through
% [dfg-customization.tex](../preamble/dfg-customization.tex). Keep declarations in
% the project content file, next to their figure. Use `\clearEvents` before a new
% collection. The declarations are shared by both rendering commands.
%
% With the quick-start events above, this is the corresponding proposal figure:
%
% ```latex
% \hvFloat
%   {figure}
%   {\printEventTimeline[width=\linewidth,rotation=45]}
%   [Retreats, progress days and symposia.]
%   {Retreats, progress days and symposia.\\
%    \printEventDetails[format=prose]}
%   {fig:event-timeline}
% ```
%
% In another project, load `\usepackage{hvfloat}` yourself if using this wrapper.
% The timeline module itself does not require `hvFloat`. The optional short
% caption is useful when a list of figures is generated: it keeps the detailed
% prose out of that list. For `hvFloat`, put it **between the graphic argument and
% the long caption**, as shown above.
%
% To print a separate list, use `\printEventDetails` after the figure instead of
% putting it in the caption. Add `format=prose` for a paragraph.
%
% ## Event content: `\addEvent[formatting]{content}`
%
% Content belongs in the mandatory argument. The optional argument controls chart
% formatting and is documented separately below. Both `\addEvent{...}` and
% `\addEvent[]{...}` use the chart defaults.
%
% | Field          | Default                               | Meaning                                                                     |
% |----------------|---------------------------------------|-----------------------------------------------------------------------------|
% | `date`         | Required, unless `start date` is used | ISO start date: `YYYY-MM` or `YYYY-MM-DD`.                                  |
% | `start date`   | Alias of `date`                       | An explicit name for the same start field; use one of these two names.      |
% | `end date`     | Start date                            | Inclusive end date, in either supported ISO format.                         |
% | `category`     | Required                              | A declared category key; see the presets below.                             |
% | `title`        | Required                              | Full event title, used in both details formats and as the chart fallback.   |
% | `id`           | `event-N`                             | Unique ID in the current collection. Use explicit IDs for layout overrides. |
% | `label`        | `title`                               | Short chart name when `labels=label`.                                       |
% | `abbreviation` | Falls back to `label`, then `title`   | Shortest chart name when `labels=abbreviation`.                             |
% | `summary`      | Empty                                 | Additional chart text when `summary=true`.                                  |
% | `description`  | Empty                                 | Full account printed by `\printEventDetails`.                               |
% | `icon`         | Category icon                         | Replacement in the chart and individual-event details; aggregation uses the category icon. |
%
% Use braces around text containing commas. A description may contain ordinary
% LaTeX commands such as `\emph`, citations, or project references defined by the
% surrounding document. The module itself does not define those commands.
%
% The distinctions between the three names are deliberate:
%
% - `title`: full text in the list or prose, unless replaced by a category summary.
% - `label`: a shorter chart heading, for example `Int. Symposium`.
% - `abbreviation`: a compact chart heading, for example `IS`.
%
% Choosing short chart text does not shorten the printed details.
%
% ## Dates, ranges, and ordering
%
% Use zero-padded ISO dates, for example `2025-01` or `2025-01-12`. Calendar dates
% are validated, including leap years. An end date must not precede its start.
% Omitting `end date`, or making it equal to the start, creates a point event.
%
% The horizontal scale uses equal-width calendar months. Month-only dates lie at
% the month centre; exact days lie at their day centre within that month.
% Consequently, `2025-01-01` sorts before `2025-01`, and `2025-01-20` after it.
% Events at equal positions retain declaration order when sorted. Automatic
% labels with the same stored start date stack in declaration order.
%
% A range shows its complete start and end dates below the line. Its coloured
% span starts at the event point and ends at a tick. Very short ranges can occupy
% little horizontal space on a chart covering several years.
%
% Events with an identical stored start date share a black point. Different end
% dates still receive separate date labels. Identical start/end pairs share one
% date label, using the first event's date formatting.
%
% ### Show a single year
%
% ```latex
% \printEventTimeline[year=2025]
% \printEventDetails[year=2025,format=prose]
% ```
%
% The same overlap rule is used by both commands. A retreat from `2024-12-30` to
% `2025-01-03` appears in both years. The chart clips its span at the selected
% year's boundary and uses continuation arrows. A range that began earlier has
% an arrow at the left boundary instead of an invented January start point.
% Date labels and details retain the full original range.
%
% Set `year` on both commands when both should be filtered. Options are local to
% each call; the details do not inherit the preceding chart's filter.
%
% ## Chart options: `\printEventTimeline[...]`
%
% Dimensions accept TeX units or expressions such as `150mm` and `.9\textwidth`.
% Angles are in degrees. Boolean options accept `true` or `false`.
%
% | Option | Default | Effect |
% | --- | --- | --- |
% | `width` | `\linewidth` | Total graphic width. Must be positive and large enough for its labels. |
% | `year` | `all` | All events, or events overlapping a four-digit year. |
% | `rotation` | `30` | Angle of the upper labels. |
% | `date rotation` | `auto` | Follows each event's effective label rotation; an explicit angle overrides this. |
% | `labels` | `label` | Select `title`, `label`, or `abbreviation`. |
% | `show labels` | `true` | Show upper label text, summaries, and their connectors. When false, event icons remain if `icons=true`. |
% | `show dates` | `true` | Show dates below the axis and their connectors. |
% | `summary` | `false` | Add each nonempty summary below its chart heading. |
% | `icons` | `true` | Show event/category icons in the chart. |
% | `legend` | `true` | Show the categories present in the selected events. |
% | `label width` | `0pt` | Natural text width; a positive dimension wraps the text to that width. |
% | `label distance` | `1.8mm` | Distance from the axis to the lowest edge of a label in lane 0. |
% | `lane` | `auto` | Default upper-label lane: automatic or a nonnegative integer. |
% | `lane spacing` | `auto` | Maximum unrotated label height plus `gap`, or a positive dimension. |
% | `date lane` | `auto` | Default date lane: automatic or a nonnegative integer. |
% | `date distance` | `1.8mm` | Distance from the axis to the highest edge of a date in date lane 0. |
% | `date lane spacing` | `auto` | Maximum unrotated date height plus `gap`, or a positive dimension. |
% | `gap` | `.8mm` | Clearance used when checking text collisions. |
% | `font` | `\sffamily\fontsize{7.4}{9}\selectfont` | Font for chart headings and summaries. |
% | `date font` | `\sffamily\fontsize{6.5}{8}\selectfont` | Font for dates below the line. |
% | `line color` | `EventMuted!40` | Main axis colour. |
% | `line width` | `.6pt` | Main axis thickness. |
% | `connector width` | `.35pt` | Thickness of leaders from points to upper labels. |
% | `date connector width` | `.3pt` | Thickness of leaders from points to dates. |
% | `range width` | `1.2pt` | Thickness of event spans and their end ticks. |
% | `dot radius` | `.9mm` | Radius of start points. |
% | `events` | Empty | Temporary formatting overrides keyed by event ID. |
%
% The main line spans the requested width. Event positions are fitted inside it
% with space for the measured text. Shortening a label increases spacing when
% that label limits the fit; another label can still determine the available
% space. Text is not automatically reduced to fit a narrow chart.
%
% ### Hide dates, labels, icons, or the legend
%
% Each part can be switched off independently:
%
% ```latex
% \printEventTimeline[show dates=false]  % hide lower dates and their connectors
% \printEventTimeline[show labels=false] % hide upper text; keep event icons
% \printEventTimeline[icons=false]       % hide event icons
% \printEventTimeline[legend=false]      % hide the category legend
% ```
%
% To show only the axis, event points, and range spans:
%
% ```latex
% \printEventTimeline[
%   show dates=false,
%   show labels=false,
%   icons=false,
%   legend=false
% ]
% ```
%
% Hidden dates and upper text do not reserve layout space. When only event icons
% remain above the axis, their measured size determines the layout. Each call
% resets these options to `true`; `\printEventDetails` still prints full event
% content, including dates.
%
% ### Width, angles, and strokes
%
% ```latex
% \printEventTimeline[
%   width=.9\textwidth,
%   rotation=45,
%   date rotation=30,
%   line width=1pt,
%   connector width=.7pt,
%   date connector width=.7pt,
%   range width=1.5pt,
%   dot radius=1mm
% ]
% ```
%
% Upper labels begin near their point and extend up-right at positive angles.
% By default, dates end near their point and extend down-left. Set an event's
% `date direction=right` to extend its date from the first digit instead. Negative
% and zero angles are also supported. Date labels shift slightly so their
% connectors remain vertical and stop 1pt before the selected digit's top centre,
% following the effective date font and rotation. For a date range, `right`
% connects to the first digit of the start date; `left` connects to the final digit
% of the end date. The legend uses a sans-serif `\scriptsize` font.
%
% ## Per-event formatting
%
% Store persistent chart formatting in the optional argument:
%
% ```latex
% \addEvent[lane=1,xshift=2mm,rotation=35,date direction=right]{
%   id          = retreat-2024,
%   date        = 2024-10,
%   category    = retreat,
%   title       = {Annual retreat},
%   description = {A meeting of the CRC.}
% }
% ```
%
% Use `events` for a change applying only to one rendering:
%
% ```latex
% \printEventTimeline[
%   rotation=45,
%   events={
%     graduate-2025={lane=0},
%     progress-2025-01={lane=4,xshift=1mm,date direction=right}
%   }
% ]
% ```
%
% | Option | Default | Effect |
% | --- | --- | --- |
% | `lane` | Chart default | Upper-label lane, `auto` or a nonnegative integer. |
% | `xshift` | `0pt` | Move the upper label right; negative values move left. |
% | `yshift` | `0pt` | Move the upper label up; negative values move down. |
% | `rotation` | Chart default | Upper-label angle. |
% | `date rotation` | Chart default | Explicit date angle, or `auto` to follow this event's effective rotation. |
% | `date direction` | `left` | `left`: connect above the last digit; `right`: connect above the first digit and extend the date to the right. |
% | `label width` | Chart default | Natural width at `0pt`, otherwise a positive wrapping width. |
% | `label` | Selected content title/label/abbreviation | Override this chart's text. |
% | `icon` | Content/category icon | Override this chart's icon. |
% | `font` | Chart default | Override this chart heading's font. |
% | `date lane` | Chart default | Date lane, `auto` or a nonnegative integer. |
% | `date xshift` | `0pt` | Move the date right; negative values move left. |
% | `date yshift` | `0pt` | Move the date up; negative values move down. |
% | `node options` | Empty | Additional TikZ appearance keys for the upper text node. |
%
% The precedence is **chart options, then stored event formatting, then the
% print-time `events` override**. An event-level `label` therefore also overrides
% text selected through `labels=abbreviation`. Event formatting does not change
% the stored full title, description, or the appearance of printed details.
%
% Shifts offset text relative to its date position. The date values remain fixed;
% the overall fitted scale may change to keep the shifted text inside the width.
%
% ### Lanes and crowded events
%
% `lane=0` is the level closest above the axis. Higher numbers move text further
% up. Date lanes work in the opposite direction: higher numbers move dates further
% down. These are vertical levels, so adjacent numbers do not guarantee separation
% of rotated text.
%
% Automatic placement reserves explicit lanes first, then fits the remaining
% labels. For a shared date, earlier declarations take lower automatic lanes.
% Explicit lanes override automatic ordering and may overlap; review the result
% when assigning them manually.
%
% ```latex
% \printEventTimeline[
%   label distance=2mm,
%   date distance=2mm,
%   lane spacing=4mm,
%   date lane spacing=3mm,
%   gap=1mm
% ]
% ```
%
% For a dense chart, shorten `label`, select `labels=abbreviation`, adjust the
% angle or font, or give selected events different lanes and shifts. For example,
% `font={\sffamily\fontsize{8}{10}\selectfont}` changes heading size and line height.
%
% Use `node options` for appearance, such as `draw=EventRetreat`. Geometry changes
% through raw TikZ keys, including `anchor`, `scale`, or `rotate`, are not included
% in the collision measurements; use the named layout options for placement.
%
% ## Details options: `\printEventDetails[...]`
%
% | Option | Default | Effect |
% | --- | --- | --- |
% | `format` | `list` | `list` gives a description list; `prose` gives continuous inline text. |
% | `year` | `all` | Same year-overlap filter as the chart. |
% | `icons` | `true` | Keep coloured icons in either format; use `false` to omit them. |
% | `nodate` | `false` | Omit generated dates/ranges and their surrounding punctuation in either format. |
% | `show dates` | `true` | Inverse of `nodate`; use `show dates=false` to hide generated dates/ranges. |
% | `aggregated` | `false` | Produce one details block per category in the selected events. |
% | `categories` | Empty | Supply per-category title and description overrides for this aggregated print call. |
%
% By default, both formats print full titles, ISO dates or complete ranges, and
% descriptions. `nodate` and `aggregated` change this as described below.
% The list uses `\footnotesize`; prose inherits the surrounding font, including
% the caption font when used inside a caption. Prose adds no forced paragraph
% break, so it can appear inline. An empty selection produces no details output.
%
% ```latex
% \printEventDetails
% \printEventDetails[format=prose]
% \printEventDetails[format=prose,year=2025,icons=false]
% \printEventDetails[format=prose,nodate,aggregated]
% \printEventDetails[format=prose,show dates=false,aggregated]
% ```
%
% ### Dates and aggregation
%
% Bare `nodate` and `aggregated` mean `true`; the explicit forms
% `nodate=true` and `aggregated=true` are equivalent. Every print call starts
% from the defaults. `nodate` and `show dates` control the same setting in
% opposite directions; the last supplied key wins. Thus `nodate,show dates=true`
% prints dates, whereas `show dates=true,nodate` hides them.
%
% Selection and grouping follow these rules:
%
% 1. Apply `year` first, using the existing date-range overlap rule. Dates remain
%    available for selection and sorting when `nodate` is enabled.
% 2. Group the selected events by category. Order category blocks, their titles,
%    and text variants by first occurrence in the chronologically sorted
%    selection; equal dates retain source order.
% 3. Print the category heading and, when `icons=true`, its category icon once.
%    In `format=list` this is one description-list item per category. In
%    `format=prose` keep the content inline, without forced paragraph breaks.
% 4. Within each category, print each identical title/description combination
%    once. Equality compares stored TeX content, rather than semantic similarity.
%    A shared title introduces its distinct descriptions only once; differing
%    titles retain their associated descriptions as subentries. A title equal to
%    the category heading is not repeated.
% 5. When dates are shown, collect the distinct original dates/ranges for each
%    text variant in chronological order. Do not turn separate dates into an
%    invented continuous interval. `nodate` suppresses these generated labels;
%    dates written explicitly in an authored description are ordinary text.
%
% This automatically collapses repeated progress days with identical content.
% Retreats with different accounts retain their distinct descriptions in one
% category block.
%
% For a shorter category-level account, supply an explicit editorial summary:
%
% ```latex
% \printEventDetails[
%   nodate,
%   aggregated,
%   categories={
%     retreat={
%       title={Annual retreats},
%       description={
%         Annual meetings for scientific exchange,
%         doctoral projects and strategic planning.
%       }
%     }
%   }
% ]
% ```
%
% A category's `title` overrides its aggregated heading. When `description` is
% supplied, it replaces that category's event-title/description subentries.
% Categories without a description override use the lossless grouping rules
% above. If dates are enabled, a category with an editorial summary lists the
% selected category's distinct dates/ranges together. An explicitly empty
% `description={}` suppresses all subentries, leaving the heading and, if enabled,
% the dates. Omitting `description` preserves the original content.
%
% Overrides apply to this aggregated details call only. The summary should match
% the selected year window and is printed only if that category has selected
% events. Individual event records, category declarations, and timeline drawing
% keep their existing roles. `categories` has no rendering effect when
% `aggregated=false`. An empty selection prints no details.
%
% ## Categories, icons, and colours
%
% | Key | Legend text | Colour name | Palette default | Icon command |
% | --- | --- | --- | --- | --- |
% | `retreat` | Annual retreat | `EventRetreat` | Violet | `\faUsers` |
% | `progress` | Progress day | `EventProgress` | Petrol | `\faComments` |
% | `networking` | Networking | `EventNetworking` | Orange | `\faHandshake` |
% | `graduate` | Graduate school retreat | `EventGraduate` | Magenta tint | `\faGraduationCap` |
% | `symposium` | International symposium | `EventSymposium` | Bordeaux | `\faGlobe` |
%
% The module uses the host's matching RWTH colours when available, with CMYK,
% RGB, and HTML fallbacks for standalone use. The graduate category uses the
% 50-percent magenta tint. Existing `Event*` colour definitions in the host
% document are retained. To change one
% after loading the module, use an ordinary xcolor command, for example:
%
% ```latex
% \colorlet{EventRetreat}{blue!60!black}
% ```
%
% Declare a category before adding events that use it:
%
% ```latex
% \DeclareEventCategory{conference}{Conference}{EventSymposium}{\faGlobe}
% ```
%
% The four arguments are the key, legend text, an existing colour name, and an
% icon command. Redeclaring a key changes that category's configuration. To change
% only one event's icon, set its `icon` content field; aggregated details always
% use the category icon. A formatting-only `icon` override affects the chart.
%
% The proposal registers five additional science-communication categories in
% `preamble/dfg-customization.tex`: `social`, `science-night`, `speed-date`,
% `cross-talk`, and `outreach-networking`. Chapter 1 and Q04 use the same timeline
% commands; each starts its event collection with `\clearEvents`.
%
% ## Validation and regression tests
%
% IDs must be unique. A duplicate ID produces a warning, keeps the first event,
% and skips the later event, including its formatting. It does not stop a build
% using `-halt-on-error`. `\clearEvents` resets the collection, so IDs can be
% reused in a new collection. This also applies to collisions with automatically
% generated IDs.
%
% Categories must exist, and full titles and valid start dates are required.
% Reversed ranges and impossible calendar dates report errors.
% Width must be positive. Lane spacings must be `auto` or positive dimensions;
% gap, distances, wrapping width, stroke widths, and radius must be nonnegative.
%
% If compilation continues after a spacing error, invalid lane spacing recovers
% to `auto`. Automatic placement stops with an error after 1000 attempts rather
% than retrying indefinitely. Increase spacing, shorten text, or set suitable
% lanes if this limit is reached.
%
% Run the tracked regression suite from the repository root:
%
% ```sh
% python3 __admin/scripts/test_event_timeline.py -q
% ```
%
% The suite covers mixed date precision and validation, duplicate-ID warnings
% with preservation of the first event, ranges and year clipping,
% source order and manual lanes, date direction and temporary overrides, width,
% spacing recovery, the retry limit, both details formats, date switches,
% category aggregation, text deduplication without macro expansion, editorial
% overrides, option locality, caption auxiliary-file reads, and isolated copies in plain
% projects. The suite is available for manual local use; CI/CD does not run it.
% END FULL EVENT TIMELINE GUIDE

\ExplSyntaxOn
\cs_if_exist:NT \crc_event_module_loaded: {\ExplSyntaxOff\endinput}
\cs_new:Npn \crc_event_module_loaded: {}
\ExplSyntaxOff
\ProvidesPackage{dfg-timeline}[2026/11/24 v0.4.0 Independent event timelines]
\RequirePackage{tikz}
\RequirePackage{fontawesome5}
\RequirePackage{enumitem}

% Prefer the host's RWTH palette; keep the single-file module usable without it.
% Existing Event* definitions take precedence over these defaults.
\ExplSyntaxOn
\cs_new_protected:Npn \crc_event_color:nnn #1#2#3
  {
    \cs_if_exist:cF {\c_backslash_str color@#1}
      {
        \cs_if_exist:cTF {\c_backslash_str color@#2}
          {\colorlet{#1}{#2}}
          {\definecolor{#1}{cmyk/RGB/HTML}{#3}}
      }
  }
\crc_event_color:nnn {EventRetreat}{rwth-violet-100}{.70,1,.35,.15/97,33,88/612158}
\crc_event_color:nnn {EventProgress}{rwth-petrol-100}{1,.3,.5,.3/0,97,101/006165}
\crc_event_color:nnn {EventNetworking}{rwth-orange-100}{0,.4,1,0/246,168,0/F6A800}
\crc_event_color:nnn {EventGraduate}{rwth-magenta-50}{0,.5,.13,0/241,158,177/F19EB1}
\crc_event_color:nnn {EventSymposium}{rwth-bordeaux-100}{.25,1,.70,.20/161,16,53/A11035}
\crc_event_color:nnn {EventInk}{rwth-black-100}{0,0,0,1/0,0,0/000000}
\crc_event_color:nnn {EventMuted}{rwth-black-50}{0,0,0,.5/156,158,159/9C9E9F}
\crc_event_color:nnn {EventTalk}{rwth-black-50}{0,0,0,.5/156,158,159/9C9E9F}
\crc_event_color:nnn {EventMisc}{rwth-green-100}{.7,0,1,0/87,171,39/57AB27}
\ExplSyntaxOff

\ExplSyntaxOn
\seq_new:N \l__crc_events_seq
\seq_new:N \l__crc_event_sorted_seq
\seq_new:N \l__crc_event_years_seq
\seq_new:N \g__crc_event_categories_seq
\prop_new:N \l__crc_event_records_prop
\prop_new:N \l__crc_event_formatting_prop
\prop_new:N \l__crc_event_dates_prop
\prop_new:N \l__crc_event_start_positions_prop
\prop_new:N \l__crc_event_end_positions_prop
\prop_new:N \l__crc_event_ids_prop
\prop_new:N \g__crc_event_category_labels_prop
\prop_new:N \g__crc_event_category_colors_prop
\prop_new:N \g__crc_event_category_icons_prop
\tl_new:N \l__crc_event_record_tl
\tl_new:N \l__crc_event_formatting_tl
\tl_new:N \l__crc_event_id_tl
\tl_new:N \l__crc_event_date_tl
\tl_new:N \l__crc_event_end_date_tl
\tl_new:N \l__crc_event_date_label_tl
\tl_new:N \l__crc_event_year_tl
\tl_new:N \l__crc_event_current_year_tl
\tl_new:N \l__crc_event_category_tl
\tl_new:N \l__crc_event_title_tl
\tl_new:N \l__crc_event_label_tl
\tl_new:N \l__crc_event_abbreviation_tl
\tl_new:N \l__crc_event_summary_tl
\tl_new:N \l__crc_event_description_tl
\tl_new:N \l__crc_event_icon_tl
\tl_new:N \l__crc_event_color_tl
\int_new:N \l__crc_event_index_int
\int_new:N \l__crc_event_date_year_int
\int_new:N \l__crc_event_date_month_int
\int_new:N \l__crc_event_date_day_int
\int_new:N \l__crc_event_month_days_int
\bool_new:N \l__crc_event_valid_bool
\fp_new:N \l__crc_event_start_position_fp
\fp_new:N \l__crc_event_end_position_fp
\cs_generate_variant:Nn \prop_put:Nnn {NxV,Nxx}
\cs_generate_variant:Nn \prop_item:Nn {Ne}
\cs_generate_variant:Nn \str_compare:nNnTF {VNV}

\msg_new:nnn {crc-events}{bad-input}{#1}
\msg_new:nnn {crc-events}{duplicate-id}
  {Event~ID~'#1'~is~already~in~use.~
   The~later~event~is~ignored;~the~first~entry~is~kept.}
\cs_new_protected:Npn \crc_event_error:n #1
  {\bool_set_false:N \l__crc_event_valid_bool
   \msg_error:nnn {crc-events}{bad-input}{#1}}

% Parse a date whose ISO syntax has already been checked. Day zero means
% month-only precision; February follows the Gregorian leap-year rules.
\cs_new_protected:Npn \crc_event_date_parts:N #1
  {
    \int_set:Nn \l__crc_event_date_year_int
      {\tl_range:Nnn #1 {1}{4}}
    \int_set:Nn \l__crc_event_date_month_int
      {\tl_range:Nnn #1 {6}{7}}
    \int_set:Nn \l__crc_event_month_days_int
      {\int_case:nnF {\l__crc_event_date_month_int}
        {{2}{28}{4}{30}{6}{30}{9}{30}{11}{30}} {31}}
    \int_compare:nNnT {\l__crc_event_date_month_int} = {2}
      {
        \int_compare:nNnTF {\int_mod:nn {\l__crc_event_date_year_int}{400}} = {0}
          {\int_set:Nn \l__crc_event_month_days_int {29}}
          {
            \int_compare:nNnT {\int_mod:nn {\l__crc_event_date_year_int}{4}} = {0}
              {\int_compare:nNnF {\int_mod:nn {\l__crc_event_date_year_int}{100}} = {0}
                {\int_set:Nn \l__crc_event_month_days_int {29}}}
          }
      }
    \int_zero:N \l__crc_event_date_day_int
    \int_compare:nNnT {\tl_count:N #1} = {10}
      {\int_set:Nn \l__crc_event_date_day_int
        {\tl_range:Nnn #1 {9}{10}}}
  }
\cs_new_protected:Npn \crc_event_date_parts:
  {\crc_event_date_parts:N \l__crc_event_date_tl}
\cs_new_protected:Npn \crc_event_date_position:NN #1#2
  {
    \fp_zero:N #2
    \exp_args:NnV \regex_match:nnTF
      {\A[0-9]{4}-(0[1-9]|1[0-2])(-(0[1-9]|[12][0-9]|3[01]))?\Z} #1
      {
        \crc_event_date_parts:N #1
        \int_compare:nNnTF {\l__crc_event_date_day_int}>{\l__crc_event_month_days_int}
          {\crc_event_error:n {The~day~does~not~exist~in~the~given~month~and~year.}}
          {\fp_set:Nn #2 {12*\l__crc_event_date_year_int+\l__crc_event_date_month_int-1+
            \int_compare:nNnTF {\l__crc_event_date_day_int}={0}
              {.5}{(\l__crc_event_date_day_int-.5)/\l__crc_event_month_days_int}}}
      }
      {\crc_event_error:n {Use~an~ISO~date:~YYYY-MM~or~YYYY-MM-DD.}}
  }

\keys_define:nn {crc/event}
  {
    id .tl_set:N = \l__crc_event_id_tl,
    date .tl_set:N = \l__crc_event_date_tl,
    start~date .tl_set:N = \l__crc_event_date_tl,
    end~date .tl_set:N = \l__crc_event_end_date_tl,
    category .tl_set:N = \l__crc_event_category_tl,
    title .tl_set:N = \l__crc_event_title_tl,
    label .tl_set:N = \l__crc_event_label_tl,
    abbreviation .tl_set:N = \l__crc_event_abbreviation_tl,
    summary .tl_set:N = \l__crc_event_summary_tl,
    description .tl_set:N = \l__crc_event_description_tl,
    icon .tl_set:N = \l__crc_event_icon_tl,

  }
\cs_new_protected:Npn \crc_event_read:n #1
  {
    \keys_set:nn {crc/event}
      {id={},date={},end~date={},category={},title={},label={},abbreviation={},summary={},description={},
       icon={}}
    \keys_set:nn {crc/event}{#1}
    \tl_trim_spaces:N \l__crc_event_date_tl
    \tl_trim_spaces:N \l__crc_event_end_date_tl
    \tl_if_blank:VT \l__crc_event_end_date_tl
      {\tl_set_eq:NN \l__crc_event_end_date_tl \l__crc_event_date_tl}
    \tl_trim_spaces:N \l__crc_event_category_tl
    \tl_trim_spaces:N \l__crc_event_id_tl
  }
\NewDocumentCommand \DeclareEventCategory {mmmm}
  {
    \seq_if_in:NnF \g__crc_event_categories_seq {#1}
      {\seq_gput_right:Nn \g__crc_event_categories_seq {#1}}
    \prop_gput:Nnn \g__crc_event_category_labels_prop {#1}{#2}
    \prop_gput:Nnn \g__crc_event_category_colors_prop {#1}{#3}
    \prop_gput:Nnn \g__crc_event_category_icons_prop {#1}{#4}
  }
\NewDocumentCommand{\EventCategoryIcon}{m}
  {
    \group_begin:
      \color{\prop_item:Nn \g__crc_event_category_colors_prop {#1}}
      \prop_item:Nn \g__crc_event_category_icons_prop {#1}
    \group_end:
  }
\NewDocumentCommand \clearEvents {}
  {
    \seq_clear:N \l__crc_events_seq
    \prop_clear:N \l__crc_event_records_prop
    \prop_clear:N \l__crc_event_formatting_prop
    \prop_clear:N \l__crc_event_dates_prop
    \prop_clear:N \l__crc_event_start_positions_prop
    \prop_clear:N \l__crc_event_end_positions_prop
    \prop_clear:N \l__crc_event_ids_prop
  }
\NewDocumentCommand \addEvent {O{} m}
  {
    \crc_event_read:n {#2}
    \bool_set_true:N \l__crc_event_valid_bool
    \crc_event_date_position:NN \l__crc_event_date_tl \l__crc_event_start_position_fp
    \tl_if_eq:NNTF \l__crc_event_date_tl \l__crc_event_end_date_tl
      {\fp_set_eq:NN \l__crc_event_end_position_fp \l__crc_event_start_position_fp}
      {\crc_event_date_position:NN \l__crc_event_end_date_tl \l__crc_event_end_position_fp}
    \bool_if:NT \l__crc_event_valid_bool
      {\fp_compare:nT {\l__crc_event_end_position_fp<\l__crc_event_start_position_fp}
        {\crc_event_error:n {The~end~date~must~not~precede~the~start~date.}}}
    \tl_if_blank:VT \l__crc_event_title_tl
      {\crc_event_error:n {Every~event~needs~a~title.}}
    \prop_if_in:NVF \g__crc_event_category_labels_prop \l__crc_event_category_tl
      {\crc_event_error:n {Unknown~event~category.}}
    \int_set:Nn \l__crc_event_index_int {\seq_count:N \l__crc_events_seq+1}
    \tl_if_blank:VT \l__crc_event_id_tl
      {\tl_set:Nx \l__crc_event_id_tl {event-\int_use:N \l__crc_event_index_int}}
    \prop_if_in:NVT \l__crc_event_ids_prop \l__crc_event_id_tl
      {
        \bool_set_false:N \l__crc_event_valid_bool
        \msg_warning:nnx {crc-events}{duplicate-id}{\l__crc_event_id_tl}
      }
    \bool_if:NT \l__crc_event_valid_bool
      {
        \seq_put_right:Nx \l__crc_events_seq {\int_use:N \l__crc_event_index_int}
        \tl_set:Nn \l__crc_event_record_tl {#2}
        \tl_set:Nn \l__crc_event_formatting_tl {#1}
        \prop_put:NxV \l__crc_event_records_prop
          {\int_use:N \l__crc_event_index_int} \l__crc_event_record_tl
        \prop_put:NxV \l__crc_event_formatting_prop
          {\int_use:N \l__crc_event_index_int} \l__crc_event_formatting_tl
        \prop_put:NxV \l__crc_event_dates_prop
          {\int_use:N \l__crc_event_index_int} \l__crc_event_date_tl
        \prop_put:Nxx \l__crc_event_start_positions_prop
          {\int_use:N \l__crc_event_index_int}{\fp_use:N \l__crc_event_start_position_fp}
        \prop_put:Nxx \l__crc_event_end_positions_prop
          {\int_use:N \l__crc_event_index_int}{\fp_use:N \l__crc_event_end_position_fp}
        \prop_put:NVn \l__crc_event_ids_prop \l__crc_event_id_tl {used}
      }
  }
\cs_new_protected:Npn \crc_event_prepare:
  {
    \seq_set_eq:NN \l__crc_event_sorted_seq \l__crc_events_seq
    \seq_sort:Nn \l__crc_event_sorted_seq
      {
        \fp_compare:nTF
          {\prop_item:Nn \l__crc_event_start_positions_prop {##1}>
           \prop_item:Nn \l__crc_event_start_positions_prop {##2}}
          {\sort_return_swapped:}{\sort_return_same:}
      }
    \seq_clear:N \l__crc_event_years_seq
    \seq_map_inline:Nn \l__crc_event_sorted_seq
      {
        \prop_get:NnN \l__crc_event_dates_prop {##1}\l__crc_event_date_tl
        \tl_set:Nx \l__crc_event_year_tl {\tl_range:Nnn \l__crc_event_date_tl {1}{4}}
        \seq_if_in:NVF \l__crc_event_years_seq \l__crc_event_year_tl
          {\seq_put_right:NV \l__crc_event_years_seq \l__crc_event_year_tl}
      }
  }
% The same overlap test serves both renderers, including cross-year ranges.
\cs_new_protected:Npn \crc_event_set_year:Nn #1#2
  {
    \tl_set:Nn #1 {#2}
    \tl_trim_spaces:N #1
    \str_if_eq:VnF #1 {all}
      {\exp_args:NnV \regex_match:nnF {\A[0-9]{4}\Z} #1
        {\msg_error:nnn {crc-events}{bad-input}{Use~year=all~or~a~four-digit~year.}
         \tl_set:Nn #1 {all}}}
  }
\cs_new_protected:Npn \crc_event_select_year:NN #1#2
  {
    \crc_event_prepare:
    \seq_clear:N #1
    \str_if_eq:VnTF #2 {all}
      {\seq_set_eq:NN #1 \l__crc_event_sorted_seq}
      {\seq_map_inline:Nn \l__crc_event_sorted_seq
        {\fp_compare:nT
          {\prop_item:Nn \l__crc_event_start_positions_prop {##1}<12*(#2+1) &&
           \prop_item:Nn \l__crc_event_end_positions_prop {##1}>=12*#2}
          {\seq_put_right:Nn #1 {##1}}}}
  }
\cs_new_protected:Npn \crc_event_load:n #1
  {
    \prop_get:NnN \l__crc_event_records_prop {#1}\l__crc_event_record_tl
    \exp_args:NV \crc_event_read:n \l__crc_event_record_tl
    \tl_set_eq:NN \l__crc_event_date_label_tl \l__crc_event_date_tl
    \tl_if_eq:NNF \l__crc_event_date_tl \l__crc_event_end_date_tl
      {\tl_put_right:Nn \l__crc_event_date_label_tl {\,--\,}
       \tl_put_right:NV \l__crc_event_date_label_tl \l__crc_event_end_date_tl}
    \prop_get:NVN \g__crc_event_category_colors_prop \l__crc_event_category_tl \l__crc_event_color_tl
    \tl_if_blank:VT \l__crc_event_icon_tl
      {\prop_get:NVN \g__crc_event_category_icons_prop \l__crc_event_category_tl \l__crc_event_icon_tl}
    \tl_if_blank:VT \l__crc_event_label_tl
      {\tl_set_eq:NN \l__crc_event_label_tl \l__crc_event_title_tl}
    \cs_set:Npx \crcEventIndex {#1}
    \crc_event_date_parts:
    \cs_set:Npx \crcEventMonthPosition
      {
        \fp_eval:n
          {\l__crc_event_date_month_int-1+
            \int_compare:nNnTF {\l__crc_event_date_day_int} = {0}
              {.5}{(\l__crc_event_date_day_int-.5)/\l__crc_event_month_days_int}}
      }
    \cs_set_eq:NN \crcEventDate \l__crc_event_date_label_tl
    \cs_set_eq:NN \crcEventIcon \l__crc_event_icon_tl
    \cs_set_eq:NN \crcEventColor \l__crc_event_color_tl
  }
% Per-call rendering options. No plot option changes the stored event data.
\seq_new:N \l__crc_plot_events_seq
\seq_new:N \l__crc_plot_categories_seq
\prop_new:N \l__crc_plot_overrides_prop
\prop_new:N \l__crc_plot_geometry_prop
\prop_new:N \l__crc_plot_dates_prop
\prop_new:N \l__crc_plot_date_labels_prop
\tl_new:N \l__crc_plot_year_tl
\tl_new:N \l__crc_plot_labels_tl
\tl_new:N \l__crc_plot_lane_spacing_tl
\tl_new:N \l__crc_plot_lane_tl
\tl_new:N \l__crc_plot_date_lane_tl
\tl_new:N \l__crc_plot_default_lane_tl
\tl_new:N \l__crc_plot_default_date_lane_tl
\tl_new:N \l__crc_plot_request_tl
\tl_new:N \l__crc_plot_options_tl
\tl_new:N \l__crc_plot_font_tl
\tl_new:N \l__crc_plot_date_font_tl
\tl_new:N \l__crc_plot_date_rotation_tl
\tl_new:N \l__crc_plot_event_date_rotation_tl
\tl_new:N \l__crc_plot_date_direction_tl
\tl_new:N \l__crc_plot_date_spacing_tl
\tl_new:N \l__crc_plot_event_font_tl
\tl_new:N \l__crc_plot_line_color_tl
\dim_new:N \l__crc_plot_width_dim
\dim_new:N \l__crc_plot_label_width_dim
\dim_new:N \l__crc_plot_event_width_dim
\dim_new:N \l__crc_plot_distance_dim
\dim_new:N \l__crc_plot_date_distance_dim
\dim_new:N \l__crc_plot_date_step_dim
\dim_new:N \l__crc_plot_gap_dim
\dim_new:N \l__crc_plot_step_dim
\dim_new:N \l__crc_plot_xshift_dim
\dim_new:N \l__crc_plot_yshift_dim
\dim_new:N \l__crc_plot_date_xshift_dim
\dim_new:N \l__crc_plot_date_yshift_dim
\dim_new:N \l__crc_plot_left_dim
\dim_new:N \l__crc_plot_axis_span_dim
\seq_new:N \l__crc_plot_fit_seq
\seq_new:N \l__crc_plot_label_order_seq
\fp_new:N \l__crc_plot_fit_span_fp
\dim_new:N \l__crc_plot_height_dim
\dim_new:N \l__crc_plot_date_height_dim
\box_new:N \l__crc_plot_date_digit_box
\dim_new:N \l__crc_plot_date_anchor_offset_dim
\dim_new:N \l__crc_plot_bottom_dim
\dim_new:N \l__crc_plot_x_dim
\dim_new:N \l__crc_plot_y_dim
\dim_new:N \l__crc_plot_min_x_dim
\dim_new:N \l__crc_plot_max_x_dim
\dim_new:N \l__crc_plot_min_y_dim
\dim_new:N \l__crc_plot_max_y_dim
\dim_new:N \l__crc_plot_line_width_dim
\dim_new:N \l__crc_plot_connector_width_dim
\dim_new:N \l__crc_plot_date_connector_width_dim
\dim_new:N \l__crc_plot_range_width_dim
\tl_new:N \l__crc_plot_range_arrows_tl
\dim_new:N \l__crc_plot_dot_dim
\fp_new:N \l__crc_plot_rotation_fp
\fp_new:N \l__crc_plot_event_rotation_fp
\fp_new:N \l__crc_plot_event_date_rotation_fp
\fp_new:N \l__crc_plot_start_fp
\fp_new:N \l__crc_plot_span_fp
\fp_new:N \l__crc_plot_a_fp
\fp_new:N \l__crc_plot_b_fp
\fp_new:N \l__crc_plot_c_fp
\fp_new:N \l__crc_plot_d_fp
\int_new:N \l__crc_plot_candidate_int
\int_new:N \l__crc_plot_attempts_int
\bool_new:N \l__crc_plot_conflict_bool
\bool_new:N \l__crc_plot_summary_bool
\bool_new:N \l__crc_plot_icons_bool
\bool_new:N \l__crc_plot_legend_bool
\bool_new:N \l__crc_plot_show_labels_bool
\bool_new:N \l__crc_plot_show_dates_bool

\cs_new_protected:Npn \crc_plot_missing_override:n #1
  {\msg_error:nnn {crc-events}{bad-input}{Use~events={id={options}}.}}
\cs_new_protected:Npn \crc_plot_override:nn #1#2
  {
    \prop_if_in:NnTF \l__crc_event_ids_prop {#1}
      {\prop_put:Nnn \l__crc_plot_overrides_prop {#1}{#2}}
      {\msg_error:nnn {crc-events}{bad-input}{Unknown~event~ID~'#1'.}}
  }
\keys_define:nn {crc/timeline}
  {
    width .dim_set:N = \l__crc_plot_width_dim,
    year .code:n = {\crc_event_set_year:Nn \l__crc_plot_year_tl {#1}},
    rotation .fp_set:N = \l__crc_plot_rotation_fp,
    date~rotation .tl_set:N = \l__crc_plot_date_rotation_tl,
    labels .choices:nn = {title,label,abbreviation}
      {\tl_set_eq:NN \l__crc_plot_labels_tl \l_keys_choice_tl},
    summary .bool_set:N = \l__crc_plot_summary_bool,
    icons .bool_set:N = \l__crc_plot_icons_bool,
    legend .bool_set:N = \l__crc_plot_legend_bool,
    label~width .dim_set:N = \l__crc_plot_label_width_dim,
    label~distance .dim_set:N = \l__crc_plot_distance_dim,
    lane .tl_set:N = \l__crc_plot_default_lane_tl,
    lane~spacing .tl_set:N = \l__crc_plot_lane_spacing_tl,
    date~lane .tl_set:N = \l__crc_plot_default_date_lane_tl,
    date~distance .dim_set:N = \l__crc_plot_date_distance_dim,
    date~lane~spacing .tl_set:N = \l__crc_plot_date_spacing_tl,
    gap .dim_set:N = \l__crc_plot_gap_dim,
    font .tl_set:N = \l__crc_plot_font_tl,
    date~font .tl_set:N = \l__crc_plot_date_font_tl,
    line~color .tl_set:N = \l__crc_plot_line_color_tl,
    line~width .dim_set:N = \l__crc_plot_line_width_dim,
    connector~width .dim_set:N = \l__crc_plot_connector_width_dim,
    date~connector~width .dim_set:N = \l__crc_plot_date_connector_width_dim,
    range~width .dim_set:N = \l__crc_plot_range_width_dim,
    dot~radius .dim_set:N = \l__crc_plot_dot_dim,
    events .code:n = {\keyval_parse:NNn \crc_plot_missing_override:n \crc_plot_override:nn {#1}},
    show~labels .bool_set:N = \l__crc_plot_show_labels_bool,
    show~dates .bool_set:N = \l__crc_plot_show_dates_bool,
  }
\keys_define:nn {crc/timeline/event}
  {
    lane .tl_set:N = \l__crc_plot_lane_tl,
    xshift .dim_set:N = \l__crc_plot_xshift_dim,
    yshift .dim_set:N = \l__crc_plot_yshift_dim,
    rotation .fp_set:N = \l__crc_plot_event_rotation_fp,
    date~rotation .tl_set:N = \l__crc_plot_event_date_rotation_tl,
    date~direction .choices:nn = {left,right}
      {\tl_set_eq:NN \l__crc_plot_date_direction_tl \l_keys_choice_tl},
    label~width .dim_set:N = \l__crc_plot_event_width_dim,
    label .tl_set:N = \l__crc_event_label_tl,
    icon .tl_set:N = \l__crc_event_icon_tl,
    font .tl_set:N = \l__crc_plot_event_font_tl,
    date~lane .tl_set:N = \l__crc_plot_date_lane_tl,
    date~xshift .dim_set:N = \l__crc_plot_date_xshift_dim,
    date~yshift .dim_set:N = \l__crc_plot_date_yshift_dim,
    node~options .tl_set:N = \l__crc_plot_options_tl
  }
% Invalid spacing recovers to auto after the error, so even nonstopmode cannot
% get stuck retrying exactly the same position. Zero line widths are allowed.
\cs_new_protected:Npn \crc_plot_positive:Nn #1#2
  {\dim_compare:nNnF {#1}>{0pt}
    {\msg_error:nnn {crc-events}{bad-input}{'#2'~must~be~positive.}
     \dim_set:Nn #1 {1pt}}}
\cs_new_protected:Npn \crc_plot_nonnegative:Nn #1#2
  {\dim_compare:nNnT {#1}<{0pt}
    {\msg_error:nnn {crc-events}{bad-input}{'#2'~must~not~be~negative.}
     \dim_zero:N #1}}
\cs_new_protected:Npn \crc_plot_validate_spacing:Nn #1#2
  {\tl_if_eq:NnF #1 {auto}
    {\dim_compare:nNnF {#1}>{0pt}
      {\msg_error:nnn {crc-events}{bad-input}{'#2'~must~be~auto~or~a~positive~dimension.}
       \tl_set:Nn #1 {auto}}}}
\cs_new_protected:Npn \crc_plot_validate:
  {
    \crc_plot_positive:Nn \l__crc_plot_width_dim {width}
    \crc_plot_nonnegative:Nn \l__crc_plot_gap_dim {gap}
    \crc_plot_nonnegative:Nn \l__crc_plot_label_width_dim {label~width}
    \crc_plot_nonnegative:Nn \l__crc_plot_distance_dim {label~distance}
    \crc_plot_nonnegative:Nn \l__crc_plot_date_distance_dim {date~distance}
    \crc_plot_nonnegative:Nn \l__crc_plot_line_width_dim {line~width}
    \crc_plot_nonnegative:Nn \l__crc_plot_connector_width_dim {connector~width}
    \crc_plot_nonnegative:Nn \l__crc_plot_date_connector_width_dim {date~connector~width}
    \crc_plot_nonnegative:Nn \l__crc_plot_range_width_dim {range~width}
    \crc_plot_nonnegative:Nn \l__crc_plot_dot_dim {dot~radius}
    \crc_plot_validate_spacing:Nn \l__crc_plot_lane_spacing_tl {lane~spacing}
    \crc_plot_validate_spacing:Nn \l__crc_plot_date_spacing_tl {date~lane~spacing}
  }
\cs_new_protected:Npn \crc_plot_load:n #1
  {
    \crc_event_load:n {#1}
    \tl_if_blank:VT \l__crc_event_id_tl
      {\tl_set:Nn \l__crc_event_id_tl {event-#1}}
    \str_case:Vn \l__crc_plot_labels_tl
      {
        {title}{\tl_set_eq:NN \l__crc_event_label_tl \l__crc_event_title_tl}
        {abbreviation}{\tl_if_blank:VF \l__crc_event_abbreviation_tl
          {\tl_set_eq:NN \l__crc_event_label_tl \l__crc_event_abbreviation_tl}}
      }
    \tl_set_eq:NN \l__crc_plot_lane_tl \l__crc_plot_default_lane_tl
    \tl_set_eq:NN \l__crc_plot_date_lane_tl \l__crc_plot_default_date_lane_tl
    \tl_set_eq:NN \l__crc_plot_event_date_rotation_tl \l__crc_plot_date_rotation_tl
    \tl_set:Nn \l__crc_plot_date_direction_tl {left}
    \tl_set_eq:NN \l__crc_plot_event_font_tl \l__crc_plot_font_tl
    \fp_set_eq:NN \l__crc_plot_event_rotation_fp \l__crc_plot_rotation_fp
    \dim_set_eq:NN \l__crc_plot_event_width_dim \l__crc_plot_label_width_dim
    \dim_zero:N \l__crc_plot_xshift_dim
    \dim_zero:N \l__crc_plot_yshift_dim
    \dim_zero:N \l__crc_plot_date_xshift_dim
    \dim_zero:N \l__crc_plot_date_yshift_dim
    \tl_clear:N \l__crc_plot_options_tl
    \prop_get:NnNT \l__crc_event_formatting_prop {#1}\l_tmpa_tl
      {\exp_args:NnV \keys_set:nn {crc/timeline/event}\l_tmpa_tl}
    \prop_get:NVNT \l__crc_plot_overrides_prop \l__crc_event_id_tl \l_tmpa_tl
      {\exp_args:NnV \keys_set:nn {crc/timeline/event}\l_tmpa_tl}
    \crc_plot_nonnegative:Nn \l__crc_plot_event_width_dim {label~width}
    \tl_if_eq:NnTF \l__crc_plot_event_date_rotation_tl {auto}
      {\fp_set_eq:NN \l__crc_plot_event_date_rotation_fp \l__crc_plot_event_rotation_fp}
      {\fp_set:Nn \l__crc_plot_event_date_rotation_fp {\l__crc_plot_event_date_rotation_tl}}
    % Icons remain upright when upper text is hidden. Dates still follow the
    % configured label angle unless date rotation explicitly overrides it.
    \bool_if:NF \l__crc_plot_show_labels_bool
      {\fp_zero:N \l__crc_plot_event_rotation_fp}
  }
\cs_new_protected:Npn \crc_plot_label_text:
  {
    \bool_if:NT \l__crc_plot_icons_bool
      {\textcolor{\l__crc_event_color_tl}{\l__crc_event_icon_tl}\enspace}
    \textbf{\l__crc_event_label_tl}
    \bool_if:NT \l__crc_plot_summary_bool
      {\tl_if_blank:VF \l__crc_event_summary_tl
        {\\[1.5pt]\textcolor{EventMuted}{\l__crc_event_summary_tl}}}
  }
\cs_new_protected:Npn \crc_plot_measure:n #1
  {
    \crc_plot_load:n {#1}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/fraction}
      {\fp_eval:n {max(0,min(1,(\prop_item:Nn \l__crc_event_start_positions_prop {#1}-
        \l__crc_plot_start_fp)/\l__crc_plot_span_fp))}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/end-fraction}
      {\fp_eval:n {max(0,min(1,(\prop_item:Nn \l__crc_event_end_positions_prop {#1}-
        \l__crc_plot_start_fp)/\l__crc_plot_span_fp))}}
    \seq_if_in:NVF \l__crc_plot_categories_seq \l__crc_event_category_tl
      {\seq_put_right:NV \l__crc_plot_categories_seq \l__crc_event_category_tl}
    \cs_if_exist:cF {l__crc_plot_label_#1_box}{\box_new:c {l__crc_plot_label_#1_box}}
    \cs_if_exist:cF {l__crc_plot_date_#1_box}{\box_new:c {l__crc_plot_date_#1_box}}
    \hbox_set:cn {l__crc_plot_label_#1_box}
      {
        \tl_use:N \l__crc_plot_event_font_tl
        \bool_if:NTF \l__crc_plot_show_labels_bool
          {\dim_compare:nNnTF {\l__crc_plot_event_width_dim}>{0pt}
            {\parbox{\l__crc_plot_event_width_dim}{\raggedright\crc_plot_label_text:}}
            {\shortstack[l]{\crc_plot_label_text:}}}
          {\bool_if:NT \l__crc_plot_icons_bool {\l__crc_event_icon_tl}}
      }
    \hbox_set:cn {l__crc_plot_date_#1_box}
      {\bool_if:NT \l__crc_plot_show_dates_bool
        {\tl_use:N \l__crc_plot_date_font_tl\l__crc_event_date_label_tl}}
    % Measure the selected digit's top centre relative to the north-east text
    % corner. Dates extend left from their last digit, or right from their first.
    % For a range, use the start date's first digit or the end date's last digit.
    \hbox_set:Nn \l__crc_plot_date_digit_box
      {\bool_if:NT \l__crc_plot_show_dates_bool
        {\tl_use:N \l__crc_plot_date_font_tl
         \str_if_eq:VnTF \l__crc_plot_date_direction_tl {right}
           {\tl_item:Nn \l__crc_event_date_tl {1}}
           {\tl_item:Nn \l__crc_event_end_date_tl {-1}}}}
    \dim_set:Nn \l__crc_plot_date_anchor_offset_dim
      {-.5\box_wd:N \l__crc_plot_date_digit_box}
    \str_if_eq:VnT \l__crc_plot_date_direction_tl {right}
      {\dim_set:Nn \l__crc_plot_date_anchor_offset_dim
        {-\box_wd:c {l__crc_plot_date_#1_box}+.5\box_wd:N \l__crc_plot_date_digit_box}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-connector-dx}
      {\fp_to_dim:n {\dim_to_fp:n {\l__crc_plot_date_anchor_offset_dim}*
        cosd(\l__crc_plot_event_date_rotation_fp)}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-connector-dy}
      {\fp_to_dim:n {\dim_to_fp:n {\l__crc_plot_date_anchor_offset_dim}*
        sind(\l__crc_plot_event_date_rotation_fp)}}
    % Rotated corner coordinates in points; the complete label stays above
    % the axis even for negative rotations. Measured boxes drive collision lanes.
    \fp_set:Nn \l__crc_plot_a_fp
      {\dim_to_fp:n {\box_wd:c {l__crc_plot_label_#1_box}}*cosd(\l__crc_plot_event_rotation_fp)}
    \fp_set:Nn \l__crc_plot_b_fp
      {\dim_to_fp:n {\box_wd:c {l__crc_plot_label_#1_box}}*sind(\l__crc_plot_event_rotation_fp)}
    \fp_set:Nn \l__crc_plot_c_fp
      {-(\dim_to_fp:n {\box_ht:c {l__crc_plot_label_#1_box}+\box_dp:c {l__crc_plot_label_#1_box}})*sind(\l__crc_plot_event_rotation_fp)}
    \fp_set:Nn \l__crc_plot_d_fp
      {(\dim_to_fp:n {\box_ht:c {l__crc_plot_label_#1_box}+\box_dp:c {l__crc_plot_label_#1_box}})*cosd(\l__crc_plot_event_rotation_fp)}
    \dim_set:Nn \l__crc_plot_min_x_dim
      {\fp_to_dim:n {min(0,\l__crc_plot_a_fp,\l__crc_plot_c_fp,\l__crc_plot_a_fp+\l__crc_plot_c_fp)}}
    \dim_set:Nn \l__crc_plot_max_x_dim
      {\fp_to_dim:n {max(0,\l__crc_plot_a_fp,\l__crc_plot_c_fp,\l__crc_plot_a_fp+\l__crc_plot_c_fp)}}
    \dim_set:Nn \l__crc_plot_min_y_dim
      {\fp_to_dim:n {min(0,\l__crc_plot_b_fp,\l__crc_plot_d_fp,\l__crc_plot_b_fp+\l__crc_plot_d_fp)}}
    \dim_set:Nn \l__crc_plot_max_y_dim
      {\fp_to_dim:n {max(0,\l__crc_plot_b_fp,\l__crc_plot_d_fp,\l__crc_plot_b_fp+\l__crc_plot_d_fp)}}
    % An icon-only node is centred above its point rather than left-aligned.
    \bool_if:NF \l__crc_plot_show_labels_bool
      {\dim_set:Nn \l__crc_plot_min_x_dim {-.5\box_wd:c {l__crc_plot_label_#1_box}}
       \dim_set:Nn \l__crc_plot_max_x_dim {.5\box_wd:c {l__crc_plot_label_#1_box}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/min-x}{\dim_use:N \l__crc_plot_min_x_dim}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/max-x}{\dim_use:N \l__crc_plot_max_x_dim}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/min-y}{\dim_use:N \l__crc_plot_min_y_dim}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-cx}
      {\fp_eval:n {\bool_if:NTF \l__crc_plot_show_labels_bool
        {(.5)*(\l__crc_plot_a_fp+\l__crc_plot_c_fp)}{0}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-cy}{\fp_eval:n {(.5)*(\l__crc_plot_b_fp+\l__crc_plot_d_fp)}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-hw}{\fp_eval:n {.5*\dim_to_fp:n {\box_wd:c {l__crc_plot_label_#1_box}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-hh}{\fp_eval:n {.5*\dim_to_fp:n {\box_ht:c {l__crc_plot_label_#1_box}+\box_dp:c {l__crc_plot_label_#1_box}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-cos}{\fp_eval:n {cosd(\l__crc_plot_event_rotation_fp)}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-sin}{\fp_eval:n {sind(\l__crc_plot_event_rotation_fp)}}
    \dim_set:Nn \l__crc_plot_height_dim
      {\dim_max:nn {\l__crc_plot_height_dim}{\box_ht:c {l__crc_plot_label_#1_box}+\box_dp:c {l__crc_plot_label_#1_box}}}
    % Date geometry is relative to the selected digit's top centre. The text's
    % north-east corner is shifted so this centre stays on the connector.
    \fp_set:Nn \l__crc_plot_a_fp {-\dim_to_fp:n {\box_wd:c {l__crc_plot_date_#1_box}}*cosd(\l__crc_plot_event_date_rotation_fp)}
    \fp_set:Nn \l__crc_plot_b_fp {-\dim_to_fp:n {\box_wd:c {l__crc_plot_date_#1_box}}*sind(\l__crc_plot_event_date_rotation_fp)}
    \fp_set:Nn \l__crc_plot_c_fp {\dim_to_fp:n {\box_ht:c {l__crc_plot_date_#1_box}+\box_dp:c {l__crc_plot_date_#1_box}}*sind(\l__crc_plot_event_date_rotation_fp)}
    \fp_set:Nn \l__crc_plot_d_fp {-\dim_to_fp:n {\box_ht:c {l__crc_plot_date_#1_box}+\box_dp:c {l__crc_plot_date_#1_box}}*cosd(\l__crc_plot_event_date_rotation_fp)}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-cx}
      {\fp_eval:n {.5*(\l__crc_plot_a_fp+\l__crc_plot_c_fp)-
        \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dx}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-cy}
      {\fp_eval:n {.5*(\l__crc_plot_b_fp+\l__crc_plot_d_fp)-
        \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dy}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-hw}{\fp_eval:n {.5*\dim_to_fp:n {\box_wd:c {l__crc_plot_date_#1_box}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-hh}{\fp_eval:n {.5*\dim_to_fp:n {\box_ht:c {l__crc_plot_date_#1_box}+\box_dp:c {l__crc_plot_date_#1_box}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-cos}{\fp_eval:n {cosd(\l__crc_plot_event_date_rotation_fp)}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-sin}{\fp_eval:n {sind(\l__crc_plot_event_date_rotation_fp)}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-min-y}
      {\fp_to_dim:n {min(0,\l__crc_plot_b_fp,\l__crc_plot_d_fp,\l__crc_plot_b_fp+\l__crc_plot_d_fp)-
        \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dy}}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-max-y}
      {\fp_to_dim:n {max(0,\l__crc_plot_b_fp,\l__crc_plot_d_fp,\l__crc_plot_b_fp+\l__crc_plot_d_fp)-
        \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dy}}}}
    \dim_set:Nn \l__crc_plot_date_height_dim
      {\dim_max:nn {\l__crc_plot_date_height_dim}{\box_ht:c {l__crc_plot_date_#1_box}+\box_dp:c {l__crc_plot_date_#1_box}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/fit-min}
      {\fp_eval:n {min(-\dim_to_fp:n {\l__crc_plot_dot_dim+.2pt},
        \bool_if:nTF {\l__crc_plot_show_labels_bool || \l__crc_plot_icons_bool}
          {\dim_to_fp:n {\l__crc_plot_xshift_dim+\l__crc_plot_min_x_dim}}{0},
        \bool_if:NTF \l__crc_plot_show_dates_bool
          {\dim_to_fp:n {\l__crc_plot_date_xshift_dim-
            \prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dx}}+
            min(0,\l__crc_plot_a_fp,\l__crc_plot_c_fp,\l__crc_plot_a_fp+\l__crc_plot_c_fp)}{0})}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/fit-max}
      {\fp_eval:n {max(\dim_to_fp:n {\l__crc_plot_dot_dim+.2pt},
        \bool_if:nTF {\l__crc_plot_show_labels_bool || \l__crc_plot_icons_bool}
          {\dim_to_fp:n {\l__crc_plot_xshift_dim+\l__crc_plot_max_x_dim}}{0},
        \bool_if:NTF \l__crc_plot_show_dates_bool
          {\dim_to_fp:n {\l__crc_plot_date_xshift_dim-
            \prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dx}}+
            max(0,\l__crc_plot_a_fp,\l__crc_plot_c_fp,\l__crc_plot_a_fp+\l__crc_plot_c_fp)}{0})}}
  }
% Maximise the common date scale subject to every event's actual left/right
% extent. Calendar endpoints also stay inside the requested width. Reserving
% the longest label at both endpoints wastes space when it occurs mid-chart.
\cs_new_protected:Npn \crc_plot_fit_pair:nn #1#2
  {
    \fp_compare:nT {\prop_item:Nn \l__crc_plot_geometry_prop {#2/fraction}>
                   \prop_item:Nn \l__crc_plot_geometry_prop {#1/fraction}}
      {\fp_set:Nn \l__crc_plot_fit_span_fp
        {min(\l__crc_plot_fit_span_fp,
          (\dim_to_fp:n {\l__crc_plot_width_dim-4mm}+
           \prop_item:Nn \l__crc_plot_geometry_prop {#1/fit-min}-
           \prop_item:Nn \l__crc_plot_geometry_prop {#2/fit-max})/
          (\prop_item:Nn \l__crc_plot_geometry_prop {#2/fraction}-
           \prop_item:Nn \l__crc_plot_geometry_prop {#1/fraction}))}}
  }
\cs_new_protected:Npn \crc_plot_fit:
  {
    \seq_set_eq:NN \l__crc_plot_fit_seq \l__crc_plot_events_seq
    \seq_put_left:Nn \l__crc_plot_fit_seq {start}
    \seq_put_right:Nn \l__crc_plot_fit_seq {end}
    \prop_put:Nnn \l__crc_plot_geometry_prop {start/fraction}{0}
    \prop_put:Nnn \l__crc_plot_geometry_prop {end/fraction}{1}
    \clist_map_inline:nn {start,end}
      {\prop_put:Nnn \l__crc_plot_geometry_prop {##1/fit-min}{0}
       \prop_put:Nnn \l__crc_plot_geometry_prop {##1/fit-max}{0}}
    \fp_set:Nn \l__crc_plot_fit_span_fp {\dim_to_fp:n {\l__crc_plot_width_dim-4mm}}
    \seq_map_inline:Nn \l__crc_plot_fit_seq
      {\seq_map_inline:Nn \l__crc_plot_fit_seq {\crc_plot_fit_pair:nn {##1}{####1}}}
    \dim_set:Nn \l__crc_plot_axis_span_dim {\fp_to_dim:N \l__crc_plot_fit_span_fp}
    \dim_set:Nn \l__crc_plot_left_dim {2mm}
    \seq_map_inline:Nn \l__crc_plot_fit_seq
      {\dim_set:Nn \l__crc_plot_left_dim
        {\dim_max:nn {\l__crc_plot_left_dim}{\fp_to_dim:n {\dim_to_fp:n {2mm}-
          \prop_item:Nn \l__crc_plot_geometry_prop {##1/fit-min}-
          \prop_item:Nn \l__crc_plot_geometry_prop {##1/fraction}*\l__crc_plot_fit_span_fp}}}}
    \bool_set_false:N \l__crc_plot_conflict_bool
    \dim_compare:nNnF {\l__crc_plot_axis_span_dim}>{0pt}
      {\bool_set_true:N \l__crc_plot_conflict_bool}
    \seq_map_inline:Nn \l__crc_plot_fit_seq
      {\fp_compare:nT
        {\dim_to_fp:n {\l__crc_plot_left_dim}+
         \prop_item:Nn \l__crc_plot_geometry_prop {##1/fraction}*\l__crc_plot_fit_span_fp+
         \prop_item:Nn \l__crc_plot_geometry_prop {##1/fit-max}>
         \dim_to_fp:n {\l__crc_plot_width_dim-2mm}+.01}
        {\bool_set_true:N \l__crc_plot_conflict_bool}}
    \bool_if:NT \l__crc_plot_conflict_bool
      {\msg_error:nnn {crc-events}{bad-input}{Timeline~width~is~too~small~for~its~labels.}}
  }
% Separating-axis checks let parallel rotated labels share vertical space.
% Each cached box is an oriented rectangle; only true intersections add lanes.
\fp_new:N \l__crc_plot_dx_fp
\fp_new:N \l__crc_plot_dy_fp
\fp_new:N \l__crc_plot_nx_fp
\fp_new:N \l__crc_plot_ny_fp
\fp_new:N \l__crc_plot_radius_a_fp
\fp_new:N \l__crc_plot_radius_b_fp
\tl_new:N \l__crc_plot_sat_type_tl
\tl_new:N \l__crc_plot_sat_a_tl
\tl_new:N \l__crc_plot_sat_b_tl
\bool_new:N \l__crc_plot_intersects_bool
\cs_new_protected:Npn \crc_plot_candidate_y:nn #1#2
  {
    \str_if_eq:nnTF {#1}{label}
      {\dim_set:Nn \l__crc_plot_y_dim
        {\l__crc_plot_distance_dim+\l__crc_plot_candidate_int\l__crc_plot_step_dim+
         \l__crc_plot_yshift_dim-\prop_item:Nn \l__crc_plot_geometry_prop {#2/min-y}}}
      {\dim_set:Nn \l__crc_plot_y_dim
        {-\l__crc_plot_date_distance_dim-\l__crc_plot_candidate_int\l__crc_plot_date_step_dim+
         \l__crc_plot_date_yshift_dim-\prop_item:Nn \l__crc_plot_geometry_prop {#2/date-max-y}}}
  }
\cs_new_protected:Npn \crc_plot_sat_axis:nn #1#2
  {
    \bool_if:NT \l__crc_plot_intersects_bool
      {
        \fp_set:Nn \l__crc_plot_nx_fp {#1}
        \fp_set:Nn \l__crc_plot_ny_fp {#2}
        \fp_set:Nn \l__crc_plot_radius_a_fp
          {\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-hw}
           *abs(\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-cos}*\l__crc_plot_nx_fp+
                \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-sin}*\l__crc_plot_ny_fp)+
           \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-hh}
           *abs(-\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-sin}*\l__crc_plot_nx_fp+
                 \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_a_tl/\l__crc_plot_sat_type_tl-cos}*\l__crc_plot_ny_fp)}
        \fp_set:Nn \l__crc_plot_radius_b_fp
          {\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-hw}
           *abs(\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-cos}*\l__crc_plot_nx_fp+
                \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-sin}*\l__crc_plot_ny_fp)+
           \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-hh}
           *abs(-\prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-sin}*\l__crc_plot_nx_fp+
                 \prop_item:Ne \l__crc_plot_geometry_prop {\l__crc_plot_sat_b_tl/\l__crc_plot_sat_type_tl-cos}*\l__crc_plot_ny_fp)}
        \fp_compare:nT
          {abs(\l__crc_plot_dx_fp*\l__crc_plot_nx_fp+\l__crc_plot_dy_fp*\l__crc_plot_ny_fp)
           >=\l__crc_plot_radius_a_fp+\l__crc_plot_radius_b_fp+\dim_to_fp:n {\l__crc_plot_gap_dim}}
          {\bool_set_false:N \l__crc_plot_intersects_bool}
      }
  }
\cs_new_protected:Npn \crc_plot_intersects:nnn #1#2#3
  {
    \tl_set:Nn \l__crc_plot_sat_type_tl {#1}
    \tl_set:Nn \l__crc_plot_sat_a_tl {#2}
    \tl_set:Nn \l__crc_plot_sat_b_tl {#3}
    \fp_set:Nn \l__crc_plot_dx_fp
      {\dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#2/#1-x}}+
       \prop_item:Nn \l__crc_plot_geometry_prop {#2/#1-cx}-
       \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#3/#1-x}}-
       \prop_item:Nn \l__crc_plot_geometry_prop {#3/#1-cx}}
    \fp_set:Nn \l__crc_plot_dy_fp
      {\dim_to_fp:n {\l__crc_plot_y_dim}+\prop_item:Nn \l__crc_plot_geometry_prop {#2/#1-cy}-
       \dim_to_fp:n {\prop_item:Nn \l__crc_plot_geometry_prop {#3/#1-y}}-
       \prop_item:Nn \l__crc_plot_geometry_prop {#3/#1-cy}}
    \bool_set_true:N \l__crc_plot_intersects_bool
    \clist_map_inline:nn {#2,#3}
      {
        \crc_plot_sat_axis:nn
          {\prop_item:Nn \l__crc_plot_geometry_prop {##1/#1-cos}}
          {\prop_item:Nn \l__crc_plot_geometry_prop {##1/#1-sin}}
        \crc_plot_sat_axis:nn
          {-\prop_item:Nn \l__crc_plot_geometry_prop {##1/#1-sin}}
          {\prop_item:Nn \l__crc_plot_geometry_prop {##1/#1-cos}}
      }
  }
\cs_new_protected:Npn \crc_plot_find_lane:nn #1#2
  {
    \tl_if_eq:NnTF \l__crc_plot_request_tl {auto}
      {
        \int_zero:N \l__crc_plot_candidate_int
        \str_if_eq:nnT {#1}{label}
          {\seq_map_inline:Nn \l__crc_plot_events_seq
            {\int_compare:nNnT {##1}<{#2}
              {\str_if_eq:eeT {\prop_item:Nn \l__crc_event_dates_prop {##1}}
                               {\prop_item:Nn \l__crc_event_dates_prop {#2}}
                {\prop_get:NnNT \l__crc_plot_geometry_prop {##1/label-lane}\l_tmpa_tl
                  {\int_set:Nn \l__crc_plot_candidate_int
                    {\int_max:nn {\l__crc_plot_candidate_int}{\l_tmpa_tl+1}}}}}}}
        \bool_set_true:N \l__crc_plot_conflict_bool
        \int_zero:N \l__crc_plot_attempts_int
        \bool_while_do:nn {\l__crc_plot_conflict_bool}
          {
            \int_incr:N \l__crc_plot_attempts_int
            \bool_set_false:N \l__crc_plot_conflict_bool
            \crc_plot_candidate_y:nn {#1}{#2}
            \seq_map_inline:Nn \l__crc_plot_events_seq
              {
                \prop_if_in:NnT \l__crc_plot_geometry_prop {##1/#1-y}
                  {\crc_plot_intersects:nnn {#1}{#2}{##1}
                   \bool_if:NT \l__crc_plot_intersects_bool
                     {\bool_set_true:N \l__crc_plot_conflict_bool\seq_map_break:}}
              }
            \bool_if:NT \l__crc_plot_conflict_bool {\int_incr:N \l__crc_plot_candidate_int}
            \int_compare:nNnT {\l__crc_plot_attempts_int}>{999}
              {\bool_if:NT \l__crc_plot_conflict_bool
                {\msg_error:nnn {crc-events}{bad-input}
                  {Automatic~placement~exceeded~1000~attempts;~increase~lane~spacing~or~set~a~lane.}
                 \bool_set_false:N \l__crc_plot_conflict_bool}}
          }
      }
      {
        \exp_args:NnV \regex_match:nnTF {\A[0-9]+\Z}\l__crc_plot_request_tl
          {\int_set:Nn \l__crc_plot_candidate_int {\l__crc_plot_request_tl}}
          {\msg_error:nnn {crc-events}{bad-input}{Use~lane=auto~or~a~nonnegative~integer.}}
        \crc_plot_candidate_y:nn {#1}{#2}
      }
    \prop_put:Nnx \l__crc_plot_geometry_prop {#2/#1-lane}{\int_use:N \l__crc_plot_candidate_int}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#2/#1-y}{\dim_use:N \l__crc_plot_y_dim}
  }
\cs_new_protected:Npn \crc_plot_place:n #1
  {
    \crc_plot_load:n {#1}
    \dim_set:Nn \l__crc_plot_x_dim
      {\fp_to_dim:n {\dim_to_fp:n {\l__crc_plot_left_dim}+
        \prop_item:Nn \l__crc_plot_geometry_prop {#1/fraction}*\dim_to_fp:n {\l__crc_plot_axis_span_dim}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/x}{\dim_use:N \l__crc_plot_x_dim}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/end-x}
      {\fp_to_dim:n {\dim_to_fp:n {\l__crc_plot_left_dim}+
        \prop_item:Nn \l__crc_plot_geometry_prop {#1/end-fraction}*\dim_to_fp:n {\l__crc_plot_axis_span_dim}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-x}
      {\dim_eval:n {\l__crc_plot_x_dim+\l__crc_plot_xshift_dim}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-left}
      {\dim_eval:n {\l__crc_plot_x_dim+\l__crc_plot_xshift_dim+\prop_item:Nn \l__crc_plot_geometry_prop {#1/min-x}}}
    \prop_put:Nnx \l__crc_plot_geometry_prop {#1/label-right}
      {\dim_eval:n {\l__crc_plot_x_dim+\l__crc_plot_xshift_dim+\prop_item:Nn \l__crc_plot_geometry_prop {#1/max-x}}}
    \prop_put:NnV \l__crc_plot_geometry_prop {#1/lane-request}\l__crc_plot_lane_tl
    % Count shared starts separately from full date-range labels: different end
    % dates need distinct labels even when their start point is shared.
    \prop_if_in:NVTF \l__crc_plot_dates_prop \l__crc_event_date_tl
      {\prop_get:NVN \l__crc_plot_dates_prop \l__crc_event_date_tl \l_tmpa_tl
       \tl_set:Nx \l_tmpa_tl {\int_eval:n {\l_tmpa_tl+1}}
       \prop_put:NVV \l__crc_plot_dates_prop \l__crc_event_date_tl \l_tmpa_tl}
      {\prop_put:NVn \l__crc_plot_dates_prop \l__crc_event_date_tl {1}}
    \prop_put:Nnn \l__crc_plot_geometry_prop {#1/date-show}{false}
    \bool_if:NT \l__crc_plot_show_dates_bool
      {
        \tl_set:Nx \l_tmpa_tl {\l__crc_event_date_tl/\l__crc_event_end_date_tl}
        \prop_if_in:NVF \l__crc_plot_date_labels_prop \l_tmpa_tl
          {
            \prop_put:NVn \l__crc_plot_date_labels_prop \l_tmpa_tl {used}
            \prop_put:Nnn \l__crc_plot_geometry_prop {#1/date-show}{true}
            \prop_put:Nnx \l__crc_plot_geometry_prop {#1/date-x}
              {\dim_eval:n {\l__crc_plot_x_dim+\l__crc_plot_date_xshift_dim}}
            \tl_set_eq:NN \l__crc_plot_request_tl \l__crc_plot_date_lane_tl
            \crc_plot_find_lane:nn {date}{#1}
            \dim_set:Nn \l__crc_plot_bottom_dim
              {\dim_min:nn {\l__crc_plot_bottom_dim}
                {\l__crc_plot_y_dim+\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-min-y}}}
          }
      }
  }
% Respect same-date predecessors even when width-based packing visits a shorter
% later label first. Each label is placed once; explicit lanes remain authoritative.
\cs_new_protected:Npn \crc_plot_place_label:n #1
  {
    \prop_if_in:NnF \l__crc_plot_geometry_prop {#1/label-y}
      {
        \str_if_eq:eeT {\prop_item:Nn \l__crc_plot_geometry_prop {#1/lane-request}}{auto}
          {\seq_map_inline:Nn \l__crc_plot_events_seq
            {\int_compare:nNnT {##1}<{#1}
              {\str_if_eq:eeT {\prop_item:Nn \l__crc_event_dates_prop {##1}}
                               {\prop_item:Nn \l__crc_event_dates_prop {#1}}
                {\crc_plot_place_label:n {##1}}}}}
        \crc_plot_load:n {#1}
        \tl_set_eq:NN \l__crc_plot_request_tl \l__crc_plot_lane_tl
        \crc_plot_find_lane:nn {label}{#1}
      }
  }
\cs_new_protected:Npn \crc_plot_place_labels:
  {
    \seq_set_eq:NN \l__crc_plot_label_order_seq \l__crc_plot_events_seq
    \seq_sort:Nn \l__crc_plot_label_order_seq
      {
        \str_if_eq:eeTF {\prop_item:Nn \l__crc_plot_geometry_prop {##1/lane-request}}{auto}
          {\str_if_eq:eeTF {\prop_item:Nn \l__crc_plot_geometry_prop {##2/lane-request}}{auto}
            {\dim_compare:nNnTF {\box_wd:c {l__crc_plot_label_##1_box}}>
                               {\box_wd:c {l__crc_plot_label_##2_box}}
              {\sort_return_swapped:}{\sort_return_same:}}
            {\sort_return_swapped:}}
          {\sort_return_same:}
      }
    \seq_map_inline:Nn \l__crc_plot_label_order_seq
      {\crc_plot_place_label:n {##1}}
  }
\cs_new_protected:Npn \crc_plot_draw_range:n #1
  {
    \fp_compare:nT {\prop_item:Nn \l__crc_event_end_positions_prop {#1}>
                    \prop_item:Nn \l__crc_event_start_positions_prop {#1}}
      {
        \crc_plot_load:n {#1}
        \tl_clear:N \l__crc_plot_range_arrows_tl
        \fp_compare:nT {\prop_item:Nn \l__crc_event_start_positions_prop {#1}<\l__crc_plot_start_fp}
          {\tl_set:Nn \l__crc_plot_range_arrows_tl {<-}}
        \fp_compare:nT {\prop_item:Nn \l__crc_event_end_positions_prop {#1}>
                        \l__crc_plot_start_fp+\l__crc_plot_span_fp}
          {\tl_if_empty:NTF \l__crc_plot_range_arrows_tl
            {\tl_set:Nn \l__crc_plot_range_arrows_tl {->}}
            {\tl_set:Nn \l__crc_plot_range_arrows_tl {<->}}}
        \tikzset{crc~event/range/.style/.expand~once=\l__crc_plot_range_arrows_tl}
        \draw[\l__crc_event_color_tl,line~width=\l__crc_plot_range_width_dim,crc~event/range]
          (\prop_item:Nn \l__crc_plot_geometry_prop {#1/x},0)
          -- (\prop_item:Nn \l__crc_plot_geometry_prop {#1/end-x},0);
        \fp_compare:nT {\prop_item:Nn \l__crc_event_end_positions_prop {#1}<=
                        \l__crc_plot_start_fp+\l__crc_plot_span_fp}
          {\draw[\l__crc_event_color_tl,line~width=\l__crc_plot_range_width_dim]
            (\prop_item:Nn \l__crc_plot_geometry_prop {#1/end-x},-\l__crc_plot_dot_dim)
            -- (\prop_item:Nn \l__crc_plot_geometry_prop {#1/end-x},\l__crc_plot_dot_dim);}
      }
  }
\cs_new_protected:Npn \crc_plot_draw_connector:n #1
  {
    \crc_plot_load:n {#1}
    \bool_if:NT \l__crc_plot_show_labels_bool
      {\draw[\l__crc_event_color_tl!35,line~width=\l__crc_plot_connector_width_dim]
        (\prop_item:Nn \l__crc_plot_geometry_prop {#1/x},0)
        -- (\prop_item:Nn \l__crc_plot_geometry_prop {#1/label-x},
            \prop_item:Nn \l__crc_plot_geometry_prop {#1/label-y});}
    \str_if_eq:eeT {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-show}}{true}
      {\draw[EventMuted!40,line~width=\l__crc_plot_date_connector_width_dim,shorten~>=1pt]
        (\prop_item:Nn \l__crc_plot_geometry_prop {#1/x},0)
        -- (\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-x},
            \prop_item:Nn \l__crc_plot_geometry_prop {#1/date-y});}
  }
\cs_new_protected:Npn \crc_plot_draw_label:n #1
  {
    \crc_plot_load:n {#1}
    \tikzset{crc~event/custom/.style/.expand~once=\l__crc_plot_options_tl}

    \bool_if:NTF \l__crc_plot_show_labels_bool
      {
        % Show slanted labels with icons
        \node[
          anchor=south~west,
          rotate=\fp_use:N \l__crc_plot_event_rotation_fp,
          inner~sep=0pt,
          outer~sep=0pt,
          fill=white,
          crc~event/custom
        ]
        at (
          \prop_item:Nn \l__crc_plot_geometry_prop {#1/label-x},
          \prop_item:Nn \l__crc_plot_geometry_prop {#1/label-y}
        )
        {\box_use:c {l__crc_plot_label_#1_box}};
      }
      {
        % Hide slanted labels but keep icons
        \bool_if:NT \l__crc_plot_icons_bool
          {
            \node[
              anchor=south,
              inner~sep=0pt,
              outer~sep=0pt,
              text=\l__crc_event_color_tl
            ]
            at (
              \prop_item:Nn \l__crc_plot_geometry_prop {#1/label-x},
              \prop_item:Nn \l__crc_plot_geometry_prop {#1/label-y}
            )
            {\box_use:c {l__crc_plot_label_#1_box}};
          }
      }

    \str_if_eq:eeT
      {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-show}}
      {true}
      {
        \node[
          anchor=north~east,
          rotate=\fp_use:N \l__crc_plot_event_date_rotation_fp,
          inner~sep=0pt,
          outer~sep=0pt,
          text=EventMuted
        ]
        at (
          \dim_eval:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-x}-
                       \prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dx}},
          \dim_eval:n {\prop_item:Nn \l__crc_plot_geometry_prop {#1/date-y}-
                       \prop_item:Nn \l__crc_plot_geometry_prop {#1/date-connector-dy}}
        )
        {\box_use:c {l__crc_plot_date_#1_box}};
      }
    % A range that began before the selected year has a continuation arrow,
    % rather than an artificial event point at the start of January.
    \fp_compare:nT {\prop_item:Nn \l__crc_event_start_positions_prop {#1}>=\l__crc_plot_start_fp}
      {\int_compare:nNnTF
        {\prop_item:Ne \l__crc_plot_dates_prop {\l__crc_event_date_tl}}>{1}
        {\tl_set:Nn \l_tmpa_tl {black}}
        {\tl_set_eq:NN \l_tmpa_tl \l__crc_event_color_tl}
       \filldraw[fill=\l_tmpa_tl,draw=white,line~width=.4pt]
         (\prop_item:Nn \l__crc_plot_geometry_prop {#1/x},0)
         circle[radius=\l__crc_plot_dot_dim];}
  }
\cs_new_protected:Npn \crc_plot_legend:
  {
    \seq_map_indexed_inline:Nn \l__crc_plot_categories_seq
      {\int_compare:nNnT {##1}>{1}{\quad}
       {\color{\prop_item:Nn \g__crc_event_category_colors_prop {##2}}
        \prop_item:Nn \g__crc_event_category_icons_prop {##2}}\,
       \prop_item:Nn \g__crc_event_category_labels_prop {##2}}
  }
\NewDocumentCommand \printEventTimeline {O{}}
  {
    \mode_if_vertical:T {\noindent}
    \group_begin:
    \prop_clear:N \l__crc_plot_overrides_prop
    \prop_clear:N \l__crc_plot_geometry_prop
    \prop_clear:N \l__crc_plot_dates_prop
    \prop_clear:N \l__crc_plot_date_labels_prop
    \keys_set:nn {crc/timeline}
      {width=\linewidth,year=all,rotation=30,date~rotation=auto,labels=label,summary=false,icons=true,
       legend=true,show~labels=true,show~dates=true,
       label~width=0pt,label~distance=1.8mm,lane=auto,lane~spacing=auto,
       date~lane=auto,date~distance=1.8mm,date~lane~spacing=auto,gap=.8mm,
       font={\sffamily\fontsize{7.4}{9}\selectfont},
       date~font={\sffamily\fontsize{6.5}{8}\selectfont},
       line~color=EventMuted!40,line~width=.6pt,connector~width=.35pt,
       date~connector~width=.3pt,range~width=1.2pt,dot~radius=.9mm}
    \keys_set:nn {crc/timeline}{#1}
    \crc_plot_validate:
    \crc_event_select_year:NN \l__crc_plot_events_seq \l__crc_plot_year_tl
    \seq_clear:N \l__crc_plot_categories_seq
    \seq_if_empty:NTF \l__crc_plot_events_seq
      {\emph{No~events~for~the~selected~year.}}
      {
        \str_if_eq:VnTF \l__crc_plot_year_tl {all}
          {
            \fp_set:Nn \l__crc_plot_start_fp
              {floor(\prop_item:Ne \l__crc_event_start_positions_prop
                {\seq_item:Nn \l__crc_plot_events_seq {1}})}
            \fp_set_eq:NN \l__crc_plot_span_fp \l__crc_plot_start_fp
            \seq_map_inline:Nn \l__crc_plot_events_seq
              {\fp_set:Nn \l__crc_plot_span_fp
                {max(\l__crc_plot_span_fp,ceil(\prop_item:Nn \l__crc_event_end_positions_prop {##1}))}}
            \fp_sub:Nn \l__crc_plot_span_fp {\l__crc_plot_start_fp}
          }
          {\fp_set:Nn \l__crc_plot_start_fp {12*\l__crc_plot_year_tl}
           \fp_set:Nn \l__crc_plot_span_fp {12}}
        \dim_zero:N \l__crc_plot_height_dim
        \dim_zero:N \l__crc_plot_date_height_dim
        \dim_zero:N \l__crc_plot_bottom_dim
        \seq_map_inline:Nn \l__crc_plot_events_seq {\crc_plot_measure:n {##1}}
        \crc_plot_fit:
        \tl_if_eq:NnTF \l__crc_plot_lane_spacing_tl {auto}
          {\dim_set:Nn \l__crc_plot_step_dim {\l__crc_plot_height_dim+\l__crc_plot_gap_dim}}
          {\dim_set:Nn \l__crc_plot_step_dim {\l__crc_plot_lane_spacing_tl}}
        \tl_if_eq:NnTF \l__crc_plot_date_spacing_tl {auto}
          {\dim_set:Nn \l__crc_plot_date_step_dim {\l__crc_plot_date_height_dim+\l__crc_plot_gap_dim}}
          {\dim_set:Nn \l__crc_plot_date_step_dim {\l__crc_plot_date_spacing_tl}}
        \crc_plot_positive:Nn \l__crc_plot_step_dim {lane~spacing}
        \crc_plot_positive:Nn \l__crc_plot_date_step_dim {date~lane~spacing}
        \seq_map_inline:Nn \l__crc_plot_events_seq {\crc_plot_place:n {##1}}
        \bool_if:nT {\l__crc_plot_show_labels_bool || \l__crc_plot_icons_bool}
          {\crc_plot_place_labels:}
        \begin{tikzpicture}
          \draw[\l__crc_plot_line_color_tl,line~width=\l__crc_plot_line_width_dim]
            (\dim_eval:n {.5\l__crc_plot_line_width_dim},0)
            -- (\dim_eval:n {\l__crc_plot_width_dim-.5\l__crc_plot_line_width_dim},0);
          \seq_map_inline:Nn \l__crc_plot_events_seq {\crc_plot_draw_range:n {##1}}
          \seq_map_inline:Nn \l__crc_plot_events_seq {\crc_plot_draw_connector:n {##1}}
          \seq_map_inline:Nn \l__crc_plot_events_seq {\crc_plot_draw_label:n {##1}}
          \bool_if:NT \l__crc_plot_legend_bool
            {\node[anchor=north~west,text~width=\l__crc_plot_width_dim,
              align=left,inner~sep=0pt,outer~sep=0pt,text=EventMuted,font=\sffamily\scriptsize]
              at (0,\dim_eval:n {\l__crc_plot_bottom_dim-3mm}) {\crc_plot_legend:};}
        \end{tikzpicture}
      }
    \group_end:
  }

\tl_new:N \l__crc_event_details_format_tl
\tl_new:N \l__crc_event_details_year_tl
\seq_new:N \l__crc_event_details_seq
\bool_new:N \l__crc_event_details_icons_bool
\bool_new:N \l__crc_event_details_show_dates_bool
\bool_new:N \l__crc_event_details_aggregated_bool
\prop_new:N \l__crc_event_details_overrides_prop
\tl_new:N \l__crc_event_details_override_category_tl
\cs_generate_variant:Nn \prop_put:Nnn {Nxn}
\cs_new_protected:Npn \crc_event_details_category_missing:n #1
  {\msg_error:nnn {crc-events}{bad-input}
    {Supply~category~details~as~category={title=...,description=...}.}}
\cs_new_protected:Npn \crc_event_details_category_set:nn #1#2
  {
    \tl_set:Nn \l__crc_event_details_override_category_tl {#1}
    \tl_trim_spaces:N \l__crc_event_details_override_category_tl
    \prop_if_in:NVTF \g__crc_event_category_labels_prop
      \l__crc_event_details_override_category_tl
      {\keys_set:nn {crc/event-details-category}{#2}}
      {\msg_error:nnx {crc-events}{bad-input}{Unknown~details~category~'#1'.}}
  }
\keys_define:nn {crc/event-details-category}
  {
    title .code:n =
      {\prop_put:Nxn \l__crc_event_details_overrides_prop
        {\l__crc_event_details_override_category_tl/title}{#1}},
    title .value_required:n = true,
    description .code:n =
      {\prop_put:Nxn \l__crc_event_details_overrides_prop
        {\l__crc_event_details_override_category_tl/description}{#1}},
    description .value_required:n = true
  }
\keys_define:nn {crc/event-details}
  {
    format .choices:nn = {list,prose}
      {\tl_set_eq:NN \l__crc_event_details_format_tl \l_keys_choice_tl},
    year .code:n = {\crc_event_set_year:Nn \l__crc_event_details_year_tl {#1}},
    icons .bool_set:N = \l__crc_event_details_icons_bool,
    show~dates .bool_set:N = \l__crc_event_details_show_dates_bool,
    nodate .bool_set_inverse:N = \l__crc_event_details_show_dates_bool,
    aggregated .bool_set:N = \l__crc_event_details_aggregated_bool,
    categories .code:n =
      {\keyval_parse:NNn \crc_event_details_category_missing:n
        \crc_event_details_category_set:nn {#1}},
    categories .value_required:n = true
  }
\cs_new_protected:Npn \crc_event_details_list:
  {
    \footnotesize
    \begin{description}[leftmargin=0pt,labelindent=0pt,labelwidth=\linewidth,
      labelsep=0pt,style=nextline,itemsep=4pt,parsep=0pt]
    \seq_map_inline:Nn \l__crc_event_details_seq
      {
        \crc_event_load:n {##1}
        \item[{\bool_if:NT \l__crc_event_details_icons_bool
          {\textcolor{\crcEventColor}{\crcEventIcon}\enspace}
          \bool_if:NT \l__crc_event_details_show_dates_bool
            {\l__crc_event_date_label_tl\quad}
          \l__crc_event_title_tl}]
          \l__crc_event_description_tl
      }
    \end{description}
  }
\cs_new_protected:Npn \crc_event_details_prose:
  {
    \seq_map_indexed_inline:Nn \l__crc_event_details_seq
      {
        \int_compare:nNnT {##1}>{1}{\space}
        \crc_event_load:n {##2}
        \bool_if:NT \l__crc_event_details_icons_bool
          {\textcolor{\crcEventColor}{\crcEventIcon}\enspace}
        \textbf{\l__crc_event_title_tl
          \bool_if:NT \l__crc_event_details_show_dates_bool
            {\space(\l__crc_event_date_label_tl)}.}
        \tl_if_blank:VF \l__crc_event_description_tl
          {\space\tl_use:N \l__crc_event_description_tl}
      }
  }
% Group only selected events. Titles and descriptions remain unexpanded while
% comparing/storing variants, so formatting macros do not run during grouping.
\seq_new:N \l__crc_event_details_categories_seq
\prop_new:N \l__crc_event_details_category_events_prop
\seq_new:N \l__crc_event_details_title_ids_seq
\seq_new:N \l__crc_event_details_variant_ids_seq
\prop_new:N \l__crc_event_details_variant_titles_prop
\prop_new:N \l__crc_event_details_variant_descriptions_prop
\prop_new:N \l__crc_event_details_variant_dates_prop
\clist_new:N \l__crc_event_details_dates_clist
\clist_new:N \l__crc_event_details_all_dates_clist
\tl_new:N \l__crc_event_details_category_tl
\tl_new:N \l__crc_event_details_heading_tl
\tl_new:N \l__crc_event_details_summary_tl
\tl_new:N \l__crc_event_details_variant_id_tl
\tl_new:N \l__crc_event_details_title_tl
\tl_new:N \l__crc_event_details_description_tl
\tl_new:N \l__crc_event_details_compare_title_tl
\tl_new:N \l__crc_event_details_compare_description_tl
\bool_new:N \l__crc_event_details_summary_bool
\bool_new:N \l__crc_event_details_title_found_bool
\bool_new:N \l__crc_event_details_output_bool
\cs_new_protected:Npn \crc_event_details_groups_prepare:
  {
    \seq_clear:N \l__crc_event_details_categories_seq
    \prop_clear:N \l__crc_event_details_category_events_prop
    \seq_map_inline:Nn \l__crc_event_details_seq
      {
        \crc_event_load:n {##1}
        \seq_if_in:NVF \l__crc_event_details_categories_seq \l__crc_event_category_tl
          {
            \seq_put_right:NV \l__crc_event_details_categories_seq \l__crc_event_category_tl
            \prop_put:NVn \l__crc_event_details_category_events_prop
              \l__crc_event_category_tl {}
          }
        \prop_get:NVN \l__crc_event_details_category_events_prop
          \l__crc_event_category_tl \l_tmpa_tl
        \tl_if_empty:NF \l_tmpa_tl {\tl_put_right:Nn \l_tmpa_tl {,}}
        \tl_put_right:Nn \l_tmpa_tl {##1}
        \prop_put:NVV \l__crc_event_details_category_events_prop
          \l__crc_event_category_tl \l_tmpa_tl
      }
  }
\cs_new_protected:Npn \crc_event_details_add_date:N #1
  {
    \clist_if_in:NVF #1 \l__crc_event_date_label_tl
      {\clist_put_right:NV #1 \l__crc_event_date_label_tl}
  }
\cs_new_protected:Npn \crc_event_details_collect:n #1
  {
    \crc_event_load:n {#1}
    \crc_event_details_add_date:N \l__crc_event_details_all_dates_clist
    \bool_if:NF \l__crc_event_details_summary_bool
      {
        \tl_clear:N \l__crc_event_details_variant_id_tl
        \seq_map_inline:Nn \l__crc_event_details_variant_ids_seq
          {
            \prop_get:NnN \l__crc_event_details_variant_titles_prop {##1}
              \l__crc_event_details_compare_title_tl
            \prop_get:NnN \l__crc_event_details_variant_descriptions_prop {##1}
              \l__crc_event_details_compare_description_tl
            \tl_if_eq:NNT \l__crc_event_title_tl \l__crc_event_details_compare_title_tl
              {
                \tl_if_eq:NNT \l__crc_event_description_tl
                  \l__crc_event_details_compare_description_tl
                  {
                    \tl_set:Nn \l__crc_event_details_variant_id_tl {##1}
                    \seq_map_break:
                  }
              }
          }
        \tl_if_empty:NT \l__crc_event_details_variant_id_tl
          {
            \tl_set:Nn \l__crc_event_details_variant_id_tl {#1}
            \seq_put_right:Nn \l__crc_event_details_variant_ids_seq {#1}
            \prop_put:NnV \l__crc_event_details_variant_titles_prop {#1}
              \l__crc_event_title_tl
            \prop_put:NnV \l__crc_event_details_variant_descriptions_prop {#1}
              \l__crc_event_description_tl
            \prop_put:Nnn \l__crc_event_details_variant_dates_prop {#1}{}
            \bool_set_false:N \l__crc_event_details_title_found_bool
            \seq_map_inline:Nn \l__crc_event_details_title_ids_seq
              {
                \prop_get:NnN \l__crc_event_details_variant_titles_prop {##1}
                  \l__crc_event_details_compare_title_tl
                \tl_if_eq:NNT \l__crc_event_title_tl \l__crc_event_details_compare_title_tl
                  {
                    \bool_set_true:N \l__crc_event_details_title_found_bool
                    \seq_map_break:
                  }
              }
            \bool_if:NF \l__crc_event_details_title_found_bool
              {\seq_put_right:Nn \l__crc_event_details_title_ids_seq {#1}}
          }
        \prop_get:NVN \l__crc_event_details_variant_dates_prop
          \l__crc_event_details_variant_id_tl \l_tmpa_tl
        \clist_set:NV \l__crc_event_details_dates_clist \l_tmpa_tl
        \crc_event_details_add_date:N \l__crc_event_details_dates_clist
        \prop_put:NVV \l__crc_event_details_variant_dates_prop
          \l__crc_event_details_variant_id_tl \l__crc_event_details_dates_clist
      }
  }
\cs_new_protected:Npn \crc_event_details_category_prepare:n #1
  {
    \tl_set:Nn \l__crc_event_details_category_tl {#1}
    \seq_clear:N \l__crc_event_details_title_ids_seq
    \seq_clear:N \l__crc_event_details_variant_ids_seq
    \prop_clear:N \l__crc_event_details_variant_titles_prop
    \prop_clear:N \l__crc_event_details_variant_descriptions_prop
    \prop_clear:N \l__crc_event_details_variant_dates_prop
    \clist_clear:N \l__crc_event_details_all_dates_clist
    \exp_args:NNx \prop_get:NnNTF \l__crc_event_details_overrides_prop
      {#1/title}\l__crc_event_details_heading_tl {}
      {\prop_get:NnN \g__crc_event_category_labels_prop {#1}
        \l__crc_event_details_heading_tl}
    \exp_args:NNx \prop_get:NnNTF \l__crc_event_details_overrides_prop
      {#1/description}\l__crc_event_details_summary_tl
      {\bool_set_true:N \l__crc_event_details_summary_bool}
      {\bool_set_false:N \l__crc_event_details_summary_bool}
    \prop_get:NnN \l__crc_event_details_category_events_prop {#1}\l_tmpa_tl
    \exp_args:NV \clist_map_function:nN \l_tmpa_tl \crc_event_details_collect:n
  }
\cs_new_protected:Npn \crc_event_details_group_label:
  {
    \bool_if:NT \l__crc_event_details_icons_bool
      {\exp_args:NV \EventCategoryIcon \l__crc_event_details_category_tl \enspace}
    \tl_use:N \l__crc_event_details_heading_tl
  }
\cs_new_protected:Npn \crc_event_details_separator:
  {
    \str_if_eq:VnTF \l__crc_event_details_format_tl {prose}
      {\space}
      {\bool_if:NT \l__crc_event_details_output_bool {\par}}
    \bool_set_true:N \l__crc_event_details_output_bool
  }
\cs_new_protected:Npn \crc_event_details_dates:N #1
  {(\clist_use:Nn #1 {,~})}
\cs_new_protected:Npn \crc_event_details_variant:n #1
  {
    \prop_get:NnN \l__crc_event_details_variant_descriptions_prop {#1}
      \l__crc_event_details_description_tl
    \bool_if:nT
      {\l__crc_event_details_show_dates_bool ||
        !\tl_if_blank_p:V \l__crc_event_details_description_tl}
      {
        \crc_event_details_separator:
        \bool_if:NT \l__crc_event_details_show_dates_bool
          {
            \prop_get:NnN \l__crc_event_details_variant_dates_prop {#1}\l_tmpa_tl
            \clist_set:NV \l__crc_event_details_dates_clist \l_tmpa_tl
            \crc_event_details_dates:N \l__crc_event_details_dates_clist
            \tl_if_blank:VF \l__crc_event_details_description_tl {\space}
          }
        \tl_use:N \l__crc_event_details_description_tl
      }
  }
\cs_new_protected:Npn \crc_event_details_group_body:
  {
    \bool_set_false:N \l__crc_event_details_output_bool
    \bool_if:NTF \l__crc_event_details_summary_bool
      {
        \bool_if:NT \l__crc_event_details_show_dates_bool
          {
            \crc_event_details_separator:
            \crc_event_details_dates:N \l__crc_event_details_all_dates_clist
          }
        \tl_if_blank:VF \l__crc_event_details_summary_tl
          {\crc_event_details_separator:\tl_use:N \l__crc_event_details_summary_tl}
      }
      {
        \seq_map_inline:Nn \l__crc_event_details_title_ids_seq
          {
            \prop_get:NnN \l__crc_event_details_variant_titles_prop {##1}
              \l__crc_event_details_title_tl
            \tl_if_eq:NNF \l__crc_event_details_title_tl \l__crc_event_details_heading_tl
              {
                \tl_if_blank:VF \l__crc_event_details_title_tl
                  {\crc_event_details_separator:
                   \textbf{\l__crc_event_details_title_tl}}
              }
            \seq_map_inline:Nn \l__crc_event_details_variant_ids_seq
              {
                \prop_get:NnN \l__crc_event_details_variant_titles_prop {####1}
                  \l__crc_event_details_compare_title_tl
                \tl_if_eq:NNT \l__crc_event_details_title_tl
                  \l__crc_event_details_compare_title_tl
                  {\crc_event_details_variant:n {####1}}
              }
          }
      }
  }
\cs_new_protected:Npn \crc_event_details_group_list:
  {
    \footnotesize
    \begin{description}[leftmargin=0pt,labelindent=0pt,labelwidth=\linewidth,
      labelsep=0pt,style=nextline,itemsep=4pt,parsep=0pt]
    \seq_map_inline:Nn \l__crc_event_details_categories_seq
      {
        \crc_event_details_category_prepare:n {##1}
        \item[{\crc_event_details_group_label:}]
        \crc_event_details_group_body:
      }
    \end{description}
  }
\cs_new_protected:Npn \crc_event_details_group_prose:
  {
    \seq_map_indexed_inline:Nn \l__crc_event_details_categories_seq
      {
        \int_compare:nNnT {##1}>{1}{\space}
        \crc_event_details_category_prepare:n {##2}
        \textbf{\crc_event_details_group_label:}
        \crc_event_details_group_body:
      }
  }
\NewDocumentCommand \printEventDetails {O{}}
  {
    \group_begin:
    \prop_clear:N \l__crc_event_details_overrides_prop
    \keys_set:nn {crc/event-details}
      {format=list,icons=true,year=all,show~dates=true,aggregated=false}
    \keys_set:nn {crc/event-details}{#1}
    \crc_event_select_year:NN \l__crc_event_details_seq \l__crc_event_details_year_tl
    \seq_if_empty:NF \l__crc_event_details_seq
      {
        \bool_if:NTF \l__crc_event_details_aggregated_bool
          {
            \crc_event_details_groups_prepare:
            \str_if_eq:VnTF \l__crc_event_details_format_tl {prose}
              {\crc_event_details_group_prose:}{\crc_event_details_group_list:}
          }
          {\str_if_eq:VnTF \l__crc_event_details_format_tl {prose}
            {\crc_event_details_prose:}{\crc_event_details_list:}}
      }
    \group_end:
  }
\ExplSyntaxOff

% Category declarations: key, legend label, colour, and icon (overridable per event).
\DeclareEventCategory{retreat}{Annual retreat}{EventRetreat}{\faUsers}
\DeclareEventCategory{progress}{Progress day}{EventProgress}{\faComments}
\DeclareEventCategory{networking}{Networking}{EventNetworking}{\faHandshake}
\DeclareEventCategory{graduate}{Graduate school retreat}{EventGraduate}{\faGraduationCap}
\DeclareEventCategory{symposium}{International symposium}{EventSymposium}{\faGlobe}

% Per-call examples are documented at the top of this file.
%    \end{macrocode}
% \iffalse
%</timeline-package>
%<*distribution-package>
% \fi
% \subsection{Reusable package: dfg-distribution.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesPackage{dfg-distribution}[2026/11/24 v0.4.0 Segmented distribution charts]
% Segmented career-destination charts, RWTH colours, and setup examples.
% Loaded from preamble/dfg-customization.tex.

% Segmented career-destination charts, integrated from tmp/distribution.
% Edit appearance here; set counts beside each figure:
%   \setDistribution{postdoc=9,industry=9,other=5}
%   \DistributionChart
% Each segment represents one person. Geometry can be changed globally with
% \distributionSetup{...}, or locally with \DistributionChart[...].
\RequirePackage{tikz}
\RequirePackage{xparse}
\RequirePackage{expl3}

% All geometry is independent of the counts. One segment = one person.
% RWTH violet, magenta, and orange; project areas use blue, green, and grey.
\providecolor{DistributionPostdoc}{cmyk/RGB/HTML}{.70,1,.35,.15/97,33,88/612158}% violet-100
\providecolor{DistributionIndustry}{cmyk/RGB/HTML}{0,1,.25,0/227,0,102/E30066}% magenta-100
\providecolor{DistributionOther}{cmyk/RGB/HTML}{0,.4,1,0/246,168,0/F6A800}% orange-100
\providecolor{DistributionText}{cmyk/RGB/HTML}{.70,1,.35,.15/97,33,88/612158}% violet-100
\providecolor{DistributionAxis}{cmyk/RGB/HTML}{.70,1,.35,.15/97,33,88/612158}% violet-100

\newif\ifcrcDistributionLabelLeft
\pgfkeys{
  /distribution/.is family,
  /distribution,
  unit width/.store in=\crcDistributionUnitWidth,
  bar height/.store in=\crcDistributionBarHeight,
  row spacing/.store in=\crcDistributionRowSpacing,
  label x/.store in=\crcDistributionLabelX,
  label width/.store in=\crcDistributionLabelWidth,
  label drop/.store in=\crcDistributionLabelDrop,
  label position/.is choice,
  label position/below/.code={\crcDistributionLabelLeftfalse},
  label position/left/.code={\crcDistributionLabelLefttrue},
  label gap/.store in=\crcDistributionLabelGap,
  icon radius/.store in=\crcDistributionIconRadius,
  icon raise/.store in=\crcDistributionIconRaise,
  value gap/.store in=\crcDistributionValueGap,
  axis padding/.store in=\crcDistributionAxisPadding,
  axis width/.store in=\crcDistributionAxisWidth,
  axis dot radius/.store in=\crcDistributionDotRadius,
  separator width/.store in=\crcDistributionSeparatorWidth,
  text color/.store in=\crcDistributionTextColor,
  axis color/.store in=\crcDistributionAxisColor,
  label font/.store in=\crcDistributionLabelFont,
  value font/.store in=\crcDistributionValueFont,
  order/.code={\crcDistributionSetOrder{#1}},
  unit width=7.5mm,
  bar height=7.8mm,
  row spacing=10mm,
  label x=-8mm,
  label width=15mm,
  label drop=4.8mm,
  label position=left,
  label gap=2mm,
  icon radius=3.4mm,
  icon raise=auto, % below: 2.3mm; left: aligned with the bar centres
  value gap=3mm,
  axis padding=2mm, % extension beyond the first/last bar edges
  axis width=.45pt,
  axis dot radius=.4mm,
  separator width=.4pt,
  text color=DistributionText,
  axis color=DistributionAxis,
  label font={\sffamily\bfseries\fontsize{8.8}{10}\selectfont},
  value font={\sffamily\bfseries\fontsize{11}{12}\selectfont}
}
\newcommand{\distributionSetup}[1]{%
  \pgfkeys{/distribution/.cd,#1}%
}

% Vector icons. Coordinates run approximately from -1 to +1.
% The coloured circle is drawn by the chart; icons draw only their symbol.
\newcommand{\DeclareDistributionIcon}[2]{%
  \expandafter\def\csname crcDistributionIcon/#1\endcsname{#2}%
}
\DeclareDistributionIcon{cap}{%
  \fill[white] (-.68,.13) -- (0,.42) -- (.68,.13)
    -- (0,-.14) -- cycle;
  \fill[white] (-.37,-.10) -- (0,-.26) -- (.37,-.10)
    -- (.37,-.34) .. controls (.18,-.51) and (-.18,-.51) ..
    (-.37,-.34) -- cycle;
  \draw[white,line width=.45pt,line cap=round]
    (.59,.08) -- (.59,-.37);
  \fill[white] (.54,-.33) -- (.64,-.33) -- (.68,-.49)
    -- (.50,-.49) -- cycle;
}
\DeclareDistributionIcon{factory}{%
  \fill[white] (-.61,-.52) -- (.60,-.52) -- (.60,.24)
    -- (.25,.03) -- (.25,.26) -- (-.08,.06)
    -- (-.08,.57) -- (-.25,.57) -- (-.25,-.12)
    -- (-.40,-.12) -- (-.40,.69) -- (-.58,.69)
    -- cycle;
  \foreach \x in {-.40,-.08,.24}{%
    \fill[\crcDistributionCurrentColor] (\x,-.35) rectangle ++(.17,.18);
  }%
}
\DeclareDistributionIcon{bulb}{%
  \draw[white,line width=.38pt,line cap=round,line join=round]
    (-.20,-.36) -- (-.20,-.23)
    .. controls (-.21,-.09) and (-.43,-.02) .. (-.43,.25)
    .. controls (-.43,.77) and (.43,.77) .. (.43,.25)
    .. controls (.43,-.02) and (.21,-.09) .. (.20,-.23)
    -- (.20,-.36) -- cycle;
  \draw[white,line width=.38pt,line cap=round]
    (-.18,-.48) -- (.18,-.48)
    (-.12,-.59) -- (.12,-.59)
    (-.09,-.31) -- (-.13,.17) -- (0,.06) -- (.13,.17) -- (.09,-.31)
    (0,.77) -- (0,.91)
    (-.52,.63) -- (-.62,.73)
    (.52,.63) -- (.62,.73)
    (-.62,.25) -- (-.77,.25)
    (.62,.25) -- (.77,.25)
    (-.53,-.14) -- (-.64,-.23)
    (.53,-.14) -- (.64,-.23);
}
\DeclareDistributionIcon{none}{}

% Drawing helpers use conventional TeX syntax, so TikZ keys retain spaces.
\newcommand{\crcDistributionBeginChart}[1]{%
  % Resolve automatic geometry after global and per-chart options are applied.
  \def\crcDistributionAutoRaise{auto}%
  \ifx\crcDistributionIconRaise\crcDistributionAutoRaise
    \ifcrcDistributionLabelLeft
      \def\crcDistributionEffectiveIconRaise{0pt}%
    \else
      \def\crcDistributionEffectiveIconRaise{2.3mm}%
    \fi
  \else
    \let\crcDistributionEffectiveIconRaise\crcDistributionIconRaise
  \fi
  \pgfmathsetlengthmacro{\crcDistributionHalfHeight}{.5*\crcDistributionBarHeight}%
  \pgfmathsetlengthmacro{\crcDistributionAxisTop}{\crcDistributionHalfHeight+\crcDistributionAxisPadding}%
  \pgfmathsetlengthmacro{\crcDistributionBottom}{-(#1-1)*\crcDistributionRowSpacing-\crcDistributionAxisTop}%
  \begin{tikzpicture}
}
\newcommand{\crcDistributionDrawRow}[5]{%
  % #1 label, #2 colour, #3 icon name, #4 count, #5 row index
  \pgfmathsetlengthmacro{\crcDistributionRowY}{-(#5-1)*\crcDistributionRowSpacing}%
  \pgfmathsetlengthmacro{\crcDistributionBarLength}{#4*\crcDistributionUnitWidth}%
  \pgfmathsetlengthmacro{\crcDistributionValueX}{\crcDistributionBarLength+\crcDistributionValueGap}%
  \begin{scope}[yshift=\crcDistributionRowY]
    \def\crcDistributionCurrentColor{#2}%
    \ifnum#4>0\relax
      \fill[#2] (0,-\crcDistributionHalfHeight)
        rectangle (\crcDistributionBarLength,\crcDistributionHalfHeight);
    \fi
    \ifnum#4>1\relax
      \edef\crcDistributionLastSeparator{\number\numexpr#4-1\relax}%
      \foreach \crcDistributionSegmentIndex in {1,...,\crcDistributionLastSeparator}{%
        \pgfmathsetlengthmacro{\crcDistributionSegmentX}{\crcDistributionSegmentIndex*\crcDistributionUnitWidth}%
        \draw[white,line width=\crcDistributionSeparatorWidth]
          (\crcDistributionSegmentX,-\crcDistributionHalfHeight)
          -- (\crcDistributionSegmentX,\crcDistributionHalfHeight);
      }%
    \fi
    \begin{scope}[shift={(\crcDistributionLabelX,\crcDistributionEffectiveIconRaise)},
                  x=\crcDistributionIconRadius,y=\crcDistributionIconRadius]
      \fill[#2] (0,0) circle[radius=\crcDistributionIconRadius];
      \csname crcDistributionIcon/#3\endcsname
    \end{scope}
    \ifcrcDistributionLabelLeft
      \pgfmathsetlengthmacro{\crcDistributionTextX}{\crcDistributionLabelX-\crcDistributionIconRadius-\crcDistributionLabelGap}%
      \node[anchor=east,font=\crcDistributionLabelFont,text=\crcDistributionTextColor,
            text width=\crcDistributionLabelWidth,align=right,inner sep=0pt,outer sep=0pt]
        at (\crcDistributionTextX,\crcDistributionEffectiveIconRaise) {#1};
    \else
      \node[font=\crcDistributionLabelFont,text=\crcDistributionTextColor,
            text width=\crcDistributionLabelWidth,align=center,inner sep=0pt]
        at (\crcDistributionLabelX,-\crcDistributionLabelDrop) {#1};
    \fi
    \node[anchor=west,font=\crcDistributionValueFont,text=\crcDistributionTextColor,
          inner sep=0pt,outer sep=0pt]
      at (\crcDistributionValueX,0) {#4};
  \end{scope}
}
\newcommand{\crcDistributionEndChart}{%
  \draw[\crcDistributionAxisColor,line width=\crcDistributionAxisWidth]
    (0,\crcDistributionAxisTop) -- (0,\crcDistributionBottom);
  \fill[\crcDistributionAxisColor] (0,\crcDistributionAxisTop)
    circle[radius=\crcDistributionDotRadius];
  \fill[\crcDistributionAxisColor] (0,\crcDistributionBottom)
    circle[radius=\crcDistributionDotRadius];
  \end{tikzpicture}%
}

\ExplSyntaxOn
\prop_new:N \l__dc_labels_prop
\prop_new:N \l__dc_colors_prop
\prop_new:N \l__dc_icons_prop
\prop_new:N \l__dc_values_prop
\prop_new:N \l__dc_candidate_prop
\clist_new:N \l__dc_order_clist
\clist_new:N \l__dc_candidate_order_clist
\seq_new:N \l__dc_seen_seq
\bool_new:N \l__dc_valid_bool
\int_new:N \l__dc_row_int
\tl_new:N \l__dc_label_tl
\tl_new:N \l__dc_color_tl
\tl_new:N \l__dc_icon_tl
\tl_new:N \l__dc_value_tl

\msg_new:nnn {distributionchart}{bad-input}
  {#1}
\cs_new_protected:Npn \__dc_error:n #1
  {
    \bool_set_false:N \l__dc_valid_bool
    \msg_error:nnn {distributionchart}{bad-input}{#1}
  }

\NewDocumentCommand \DeclareDistributionCategory {mmmm}
  {
    \cs_if_exist:cTF {crcDistributionIcon/#4}
      {
        \prop_if_in:NnF \l__dc_labels_prop {#1}
          {\clist_put_right:Nn \l__dc_order_clist {#1}}
        \prop_put:Nnn \l__dc_labels_prop {#1}{#2}
        \prop_put:Nnn \l__dc_colors_prop {#1}{#3}
        \prop_put:Nnn \l__dc_icons_prop {#1}{#4}
      }
      {\__dc_error:n {Unknown~icon~'#4'.~Declare~it~first.}}
  }

\cs_new_protected:Npn \crcDistributionSetOrder #1
  {
    \bool_set_true:N \l__dc_valid_bool
    \seq_clear:N \l__dc_seen_seq
    \clist_set:Nn \l__dc_candidate_order_clist {#1}
    \clist_if_empty:NT \l__dc_candidate_order_clist
      {\__dc_error:n {The~category~order~must~not~be~empty.}}
    \clist_map_inline:Nn \l__dc_candidate_order_clist
      {
        \prop_if_in:NnF \l__dc_labels_prop {##1}
          {\__dc_error:n {Unknown~category~'##1'~in~order.}}
        \seq_if_in:NnTF \l__dc_seen_seq {##1}
          {\__dc_error:n {Repeated~category~'##1'~in~order.}}
          {\seq_put_right:Nn \l__dc_seen_seq {##1}}
      }
    \bool_if:NT \l__dc_valid_bool
      {\clist_set_eq:NN \l__dc_order_clist \l__dc_candidate_order_clist}
  }

\cs_new_protected:Npn \__dc_missing_value:n #1
  {\__dc_error:n {Missing~count~for~'#1'.~Use~category=integer.}}
\cs_new_protected:Npn \__dc_set_pair:nn #1#2
  {
    \prop_if_in:NnTF \l__dc_labels_prop {#1}
      {
        \prop_if_in:NnTF \l__dc_candidate_prop {#1}
          {\__dc_error:n {Repeated~category~'#1'~in~the~data.}}
          {
            \regex_match:nnTF {\A[0-9]+\Z} {#2}
              {\prop_put:Nnx \l__dc_candidate_prop {#1}{\int_eval:n {#2}}}
              {\__dc_error:n {Count~for~'#1'~must~be~a~nonnegative~integer.}}
          }
      }
      {\__dc_error:n {Unknown~category~'#1'.~Declare~it~first.}}
  }
\NewDocumentCommand \setDistribution {m}
  {
    % Commit only a valid complete replacement; omitted categories become 0.
    \prop_clear:N \l__dc_candidate_prop
    \bool_set_true:N \l__dc_valid_bool
    \keyval_parse:NNn \__dc_missing_value:n \__dc_set_pair:nn {#1}
    \bool_if:NT \l__dc_valid_bool
      {\prop_set_eq:NN \l__dc_values_prop \l__dc_candidate_prop}
  }

\cs_new_protected:Npn \__dc_draw_row:n #1
  {
    \int_incr:N \l__dc_row_int
    \prop_get:NnN \l__dc_labels_prop {#1}\l__dc_label_tl
    \prop_get:NnN \l__dc_colors_prop {#1}\l__dc_color_tl
    \prop_get:NnN \l__dc_icons_prop {#1}\l__dc_icon_tl
    \prop_get:NnNTF \l__dc_values_prop {#1}\l__dc_value_tl
      {}{\tl_set:Nn \l__dc_value_tl {0}}
    \crcDistributionDrawRow
      {\l__dc_label_tl}{\l__dc_color_tl}{\l__dc_icon_tl}
      {\l__dc_value_tl}{\int_use:N \l__dc_row_int}
  }
\NewDocumentCommand \DistributionChart {O{}}
  {
    \group_begin:
      \distributionSetup{#1}
      \int_zero:N \l__dc_row_int
      \crcDistributionBeginChart{\clist_count:N \l__dc_order_clist}
        \clist_map_function:NN \l__dc_order_clist \__dc_draw_row:n
      \crcDistributionEndChart
    \group_end:
  }
\ExplSyntaxOff

% Default categories; appearance overrides can be added below.
\DeclareDistributionCategory{postdoc}{Postdoc}{DistributionPostdoc}{cap}
\DeclareDistributionCategory{industry}{Industry}{DistributionIndustry}{factory}
\DeclareDistributionCategory{other}{Other}{DistributionOther}{bulb}
% Example: uncomment to change the appearance of all subsequent charts.
% Counts are still set separately with \setDistribution beside each figure.
% \distributionSetup{
%   order={industry,postdoc,other}, % display order, independent of data order
%   unit width=6mm,                % width of one person / segment
%   bar height=7mm,
%   row spacing=16mm,
%   label position=left,          % use below for labels underneath the icons
%   label gap=2mm,                % horizontal gap for labels on the left
%   icon radius=3mm,
%   icon raise=auto,              % below: 2.3mm; left: 0pt; or set a dimension
%   value gap=3mm,                 % gap between a bar and its count
%   axis padding=2mm,             % extension beyond the first/last bar edges
%   text color=DistributionText,
%   axis color=DistributionAxis,
%   label font={\sffamily\bfseries\small},
%   value font={\sffamily\bfseries\normalsize}
% }
% Or change one chart only (the global setup is restored afterwards):
% \DistributionChart[label position=left]
% For labels below the icons, label drop sets the vertical label offset.
% Q03 scales the completed chart to 6cm with \resizebox, including its text.
% END segmented distribution charts

%    \end{macrocode}
% \iffalse
%</distribution-package>
%<*icons-package>
% \fi
% \subsection{Reusable package: dfg-icons.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesPackage{dfg-icons}[2026/11/24 v0.4.0 Registered paragraph icons]
% Paragraph icons wrap text on the left without floating away from the call.
% \getIcon{name} selects its registered square asset; [vertical] selects its variant.
% Comma-separated names share one wrapping area and print side by side.
% Names and asset variants are registered with \DeclareIcon; no fixed list applies.
% height=<line count> spans the first capital to the last line's baseline.
% Defaults are four/five lines; other graphics options are forwarded.
% gap controls the spacing between icons and before the paragraph text.
% Place the command before font commands such as \textbf{...}.
\RequirePackage{graphicx}
\RequirePackage{etoolbox}
\RequirePackage{wrapstuff}
\ExplSyntaxOn
% wrapstuff 0.3 expects a decimal point when converting heights to line counts.
% Append one so exact multiples of baselineskip (including zero) also work.
\cs_if_exist:NT \__wstf_unit_aux:w
  {\patchcmd{\__wstf_unit:n}{\s_stop}{.\s_stop}{}{}}
\tl_new:N \l__crc_icon_file_tl
\str_new:N \l__crc_icon_dir_str
\str_new:N \l__crc_icon_name_str
\str_new:N \l__crc_icon_ext_str
\tl_new:N \l__crc_icon_shape_tl
\tl_new:N \l__crc_icon_graphics_tl
\dim_new:N \l__crc_icon_height_dim
\dim_new:N \l__crc_icon_gap_dim
\int_new:N \l__crc_icon_lines_int
\box_new:N \l__crc_icon_box
\box_new:N \g__crc_icon_paragraph_box
\bool_new:N \l__crc_icon_found_bool
\msg_new:nnn {crc-icons} {not-supported}
  {Icon~'#1'~is~not~registered;~using~an~example-image~placeholder.}
\msg_new:nnn {crc-icons} {not-found}
  {Icon~file~'#1'~was~not~found;~using~an~example-image~placeholder.}
\msg_new:nnn {crc-icons} {invalid-height}
  {Icon~height~must~be~a~positive~integer~number~of~lines;~received~'#1'.}
\keys_define:nn {crc/icons}
  {
    shape .choices:nn = {square,vertical}
      {\tl_set_eq:NN \l__crc_icon_shape_tl \l_keys_choice_tl},
    square .meta:n = {shape=square},
    vertical .meta:n = {shape=vertical},
    square .value_forbidden:n = true,
    vertical .value_forbidden:n = true,
    gap .dim_set:N = \l__crc_icon_gap_dim,
    height .code:n =
      {
        \exp_args:Nne \regex_match:nnTF {\A[1-9][0-9]*\Z} {#1}
          {\int_set:Nn \l__crc_icon_lines_int {#1}}
          {\msg_error:nnn {crc-icons} {invalid-height} {#1}}
      },
    height .value_required:n = true,
  }
\cs_new_protected:Npn \__crc_icon_find_file:
  {
    % Match graphicx's search paths and supported extension order.
    \cs_set_eq:cc {input@path} {Ginput@path}
    \IfFileExists{\l__crc_icon_file_tl}
      {\bool_set_true:N \l__crc_icon_found_bool}
      { }
    \bool_if:NF \l__crc_icon_found_bool
      {
        \clist_map_inline:cn {Gin@extensions}
          {
            \IfFileExists{\l__crc_icon_file_tl##1}
              {
                \bool_set_true:N \l__crc_icon_found_bool
                \clist_map_break:
              }
              { }
          }
      }
    \bool_if:NF \l__crc_icon_found_bool
      {
        \exp_args:NnnV \msg_warning:nnn {crc-icons} {not-found}
          \l__crc_icon_file_tl
      }
  }
\cs_new_protected:Npn \__crc_icon_place:nn #1#2
  {
    \noindent
    \hbox_overlap_right:n
      {
        \tex_kern:D -#1 \scan_stop:
        \raisebox{#2}[0pt][0pt]{\box_use:N \g__crc_icon_paragraph_box}
      }
    \box_gclear:N \g__crc_icon_paragraph_box
  }

\prop_new:N \g__dfgicons_files_prop
\prop_new:N \g__dfgicons_aliases_prop
\prop_new:N \g__dfgicons_explicit_prop
\bool_new:N \l__dfgicons_valid_bool
\tl_new:N \l__dfgicons_name_tl
\tl_new:N \l__dfgicons_owner_tl
\tl_new:N \l__dfgicons_square_tl
\tl_new:N \l__dfgicons_vertical_tl
\tl_new:N \l__dfgicons_default_tl
\clist_new:N \l__dfgicons_aliases_clist
\keys_define:nn {dfgicons/declare}
  {
    file .tl_set:N = \l__dfgicons_default_tl,
    square .tl_set:N = \l__dfgicons_square_tl,
    vertical .tl_set:N = \l__dfgicons_vertical_tl,
    aliases .clist_set:N = \l__dfgicons_aliases_clist,
  }
\msg_new:nnn {crc-icons}{empty-registration}{Icon~'#1'~needs~a~file,~square,~or~vertical~asset.}
\msg_new:nnn {crc-icons}{empty-name}{An~icon~name~must~not~be~empty.}
\msg_new:nnn {crc-icons}{alias-conflict}
  {Icon~name~or~alias~'#1'~already~belongs~to~'#2'.~Registration~was~not~changed.}
% Automatic filename aliases never replace an existing name or alias.
\cs_new_protected:Npn \__dfgicons_alias:nn #1#2
  {\prop_if_in:NnF \g__dfgicons_aliases_prop {#1}
    {\prop_gput:Nnn \g__dfgicons_aliases_prop {#1}{#2}}}
\cs_new_protected:Npn \__dfgicons_check_alias:nn #1#2
  {
    \prop_get:NnNT \g__dfgicons_explicit_prop {#1}\l__dfgicons_owner_tl
      {\tl_if_eq:NnF \l__dfgicons_owner_tl {#2}
        {\bool_set_false:N \l__dfgicons_valid_bool
         \msg_error:nnee {crc-icons}{alias-conflict}{\exp_not:n{#1}}{\exp_not:V\l__dfgicons_owner_tl}}}
  }
\cs_new_protected:Npn \__dfgicons_explicit_alias:nn #1#2
  {\prop_gput:Nnn \g__dfgicons_explicit_prop {#1}{#2}
   \prop_gput:Nnn \g__dfgicons_aliases_prop {#1}{#2}}
\cs_generate_variant:Nn \__dfgicons_alias:nn {en}
\cs_new_protected:Npn \__dfgicons_register_variant:nnN #1#2#3
  {
    \prop_gput:NnV \g__dfgicons_files_prop {#1/#2}#3
    \__dfgicons_alias:en {\tl_use:N#3}{#1}
    \file_parse_full_name:VNNN #3\l__crc_icon_dir_str\l__crc_icon_name_str\l__crc_icon_ext_str
    \__dfgicons_alias:en {\l__crc_icon_name_str\l__crc_icon_ext_str}{#1}
    \__dfgicons_alias:en {\l__crc_icon_name_str}{#1}
    % A registered PDF may also be referred to by its SVG source filename.
    \str_if_eq:VnT \l__crc_icon_ext_str {.pdf}
      {\__dfgicons_alias:en {\l__crc_icon_name_str.svg}{#1}
       \str_if_empty:NF \l__crc_icon_dir_str
         {\__dfgicons_alias:en {\l__crc_icon_dir_str/\l__crc_icon_name_str.svg}{#1}}}
  }
\cs_new_protected:Npn \__dfgicons_declare:nn #1#2
  {
    \bool_set_true:N \l__dfgicons_valid_bool
    \tl_if_blank:nT {#1}
      {\bool_set_false:N \l__dfgicons_valid_bool
       \msg_error:nn {crc-icons}{empty-name}}
    \keys_set:nn {dfgicons/declare}{file={},square={},vertical={},aliases={},#2}
    \tl_if_blank:VT \l__dfgicons_square_tl
      {\tl_set_eq:NN \l__dfgicons_square_tl \l__dfgicons_default_tl}
    \tl_if_blank:VT \l__dfgicons_vertical_tl
      {\tl_set_eq:NN \l__dfgicons_vertical_tl \l__dfgicons_default_tl}
    \tl_if_blank:VT \l__dfgicons_square_tl
      {\tl_set_eq:NN \l__dfgicons_square_tl \l__dfgicons_vertical_tl}
    \tl_if_blank:VT \l__dfgicons_vertical_tl
      {\tl_set_eq:NN \l__dfgicons_vertical_tl \l__dfgicons_square_tl}
    \tl_if_blank:VT \l__dfgicons_square_tl
      {\bool_set_false:N \l__dfgicons_valid_bool
       \msg_error:nnn {crc-icons}{empty-registration}{#1}}
    \__dfgicons_check_alias:nn {#1}{#1}
    \clist_map_inline:Nn \l__dfgicons_aliases_clist
      {\__dfgicons_check_alias:nn {##1}{#1}}
    \bool_if:NT \l__dfgicons_valid_bool
      {
        % Remove only this icon's previous aliases, after all checks pass.
        \prop_map_inline:Nn \g__dfgicons_aliases_prop
          {\str_if_eq:nnT {##2}{#1}
            {\prop_gremove:Nn \g__dfgicons_aliases_prop {##1}
             \prop_gremove:Nn \g__dfgicons_explicit_prop {##1}}}
        \__dfgicons_explicit_alias:nn {#1}{#1}
        \clist_map_inline:Nn \l__dfgicons_aliases_clist
          {\__dfgicons_explicit_alias:nn {##1}{#1}}
        \__dfgicons_register_variant:nnN {#1}{square}\l__dfgicons_square_tl
        \__dfgicons_register_variant:nnN {#1}{vertical}\l__dfgicons_vertical_tl
      }
  }
\NewDocumentCommand \DeclareIcon {mm}
  {
    \group_begin:
    \tl_set:Nn \l__dfgicons_name_tl {#1}
    \tl_trim_spaces:N \l__dfgicons_name_tl
    \exp_args:NV \__dfgicons_declare:nn \l__dfgicons_name_tl {#2}
    \group_end:
  }
\NewDocumentCommand \IconIfRegisteredTF {mmm}
  {
    \group_begin:
    \tl_set:Nn \l__dfgicons_name_tl {#1}
    \tl_trim_spaces:N \l__dfgicons_name_tl
    \prop_if_in:NVTF \g__dfgicons_aliases_prop \l__dfgicons_name_tl
      {\group_end: #2}{\group_end: #3}
  }

\cs_new_protected:Npn \__crc_icon_image:n #1
  {
    \group_begin:

      \tl_set:Nn \l__crc_icon_file_tl {#1}
      \tl_trim_spaces:N \l__crc_icon_file_tl
      \prop_get:NVNTF \g__dfgicons_aliases_prop \l__crc_icon_file_tl \l_tmpa_tl
        {\tl_set_eq:NN \l__crc_icon_file_tl \l_tmpa_tl}{}
      \bool_set_false:N \l__crc_icon_found_bool
      \exp_args:NNx \prop_get:NnNTF \g__dfgicons_files_prop
        {\l__crc_icon_file_tl/\l__crc_icon_shape_tl}\l_tmpa_tl
        {\tl_set_eq:NN \l__crc_icon_file_tl \l_tmpa_tl\__crc_icon_find_file:}
        {\exp_args:NnnV \msg_warning:nnn {crc-icons}{not-supported}\l__crc_icon_file_tl}
      \bool_if:NF \l__crc_icon_found_bool
        {
          \tl_set:Ne \l__crc_icon_file_tl
            {
              \str_if_eq:VnTF \l__crc_icon_shape_tl {square}
                {example-image-1x1} {example-image-9x16}
            }
        }
      \use:e
        {
          \exp_not:N \includegraphics
            [\exp_not:V \l__crc_icon_graphics_tl,
             totalheight=\dim_use:N \l__crc_icon_height_dim]
            {\exp_not:V \l__crc_icon_file_tl}
        }
    \group_end:
  }
\NewDocumentCommand{\getIcon}{ O{} m }
  {
    \par
    \group_begin:
      \tl_set:Nn \l__crc_icon_shape_tl {square}
      \dim_set:Nn \l__crc_icon_gap_dim {.6em}
      \int_zero:N \l__crc_icon_lines_int
      \keys_set_known:nnN {crc/icons} {#1} \l__crc_icon_graphics_tl
      \int_compare:nNnT {\l__crc_icon_lines_int} = {0}
        {
          \int_set:Nn \l__crc_icon_lines_int
            {\str_if_eq:VnTF \l__crc_icon_shape_tl {square} {4} {5}}
        }
      \dim_set:Nn \l__crc_icon_height_dim
        {
          \fontcharht\font`H
          + \baselineskip * \int_eval:n {\l__crc_icon_lines_int - 1}
        }
      \hbox_set:Nn \l__crc_icon_box
        {
          \clist_if_empty:nTF {#2}
            {\__crc_icon_image:n {}}
            {
              \clist_map_inline:nn {#2}
                {
                  \__crc_icon_image:n {##1}
                  \tex_kern:D \l__crc_icon_gap_dim
                }
              \tex_unkern:D
            }
        }
      % Keep a pending list label at its margin rather than beside the image.
      \legacy_if:nT {@inlabel}
        {
          \hbox_gset:cn {@labels}
            {
              \tex_kern:D -\dim_eval:n
                {\box_wd:N \l__crc_icon_box + \l__crc_icon_gap_dim}
              \box_use_drop:c {@labels}
              \tex_kern:D \dim_eval:n
                {\box_wd:N \l__crc_icon_box + \l__crc_icon_gap_dim}
            }
        }
      % wrapstuff reserves the column; place the visible graphic relative to
      % the first text baseline, independent of its vertical centring.
      \box_gset_eq:NN \g__crc_icon_paragraph_box \l__crc_icon_box
      \use:e
        {
          \exp_not:N \begin{wrapstuff}
            [l,top=0,lines=\int_use:N \l__crc_icon_lines_int,
             leftsep=0pt,rightsep=\dim_use:N \l__crc_icon_gap_dim,
             abovesep=0pt,belowsep=0pt]
        }
        \phantom{\box_use:N \l__crc_icon_box}
      \end{wrapstuff}
      \use:e
        {
          \group_end:
          \exp_not:N \__crc_icon_place:nn
            {\dim_eval:n {\box_wd:N \l__crc_icon_box + \l__crc_icon_gap_dim}}
            {
              \dim_eval:n
                {\box_dp:N \l__crc_icon_box
                 - \baselineskip * \int_eval:n {\l__crc_icon_lines_int - 1}}
            }
        }
    \ignorespaces
  }
\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</icons-package>

%<*bib-highlights-package>
% \fi
% \subsection{Reusable package: dfg-bib-highlights.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplPackage{dfg-bib-highlights}{2026-11-24}{0.4.0}{Independent biblatex name and entry emphasis}
\ExplSyntaxOff
\RequirePackage{biblatex}
\RequirePackage{xcolor}
\ExplSyntaxOn
\bool_new:N \l__dfgbib_backend_bool
\bool_set_true:N \l__dfgbib_backend_bool
\DeclareOption{noauthors}{\bool_set_false:N\l__dfgbib_backend_bool}
\ProcessOptions\relax
\bool_new:N \l__dfgbib_authors_bool
\bool_new:N \l__dfgbib_entries_bool
\bool_set_true:N \l__dfgbib_authors_bool
\bool_set_true:N \l__dfgbib_entries_bool
\tl_new:N \l__dfgbib_color_tl
\tl_set:Nn \l__dfgbib_color_tl {black}
\tl_new:N \l__dfg_bibentry_highlight_keyword_tl
\ProvideExpandableDocumentCommand \DFGBoldNamesFile {}{\jobname-boldAuthors.bib}
\NewDocumentCommand \DFGBibIfAuthorsTF {mm}{\bool_if:NTF\l__dfgbib_authors_bool{#1}{#2}}
\NewDocumentCommand \DFGBibIfEntriesTF {mm}{\bool_if:NTF\l__dfgbib_entries_bool{#1}{#2}}
\NewExpandableDocumentCommand \DFGBibNameColor {}{\tl_use:N\l__dfgbib_color_tl}
\keys_define:nn {dfgbib/setup}
  {emphasizeAuthors .bool_set:N=\l__dfgbib_authors_bool,
   emphasizeEntries .bool_set:N=\l__dfgbib_entries_bool,
   keyword .tl_set:N=\l__dfg_bibentry_highlight_keyword_tl,
   color .tl_set:N=\l__dfgbib_color_tl}
\NewDocumentCommand \BibHighlightSetup {m}{\keys_set:nn{dfgbib/setup}{#1}}
\AtEveryBibitem{\DFGBibIfEntriesTF
  {\tl_if_empty:NF\l__dfg_bibentry_highlight_keyword_tl
    {\exp_args:NV\ifkeyword\l__dfg_bibentry_highlight_keyword_tl{\bfseries}{}}}{}}
\NewDocumentCommand \printHighlightedBibliography {O{} m}
  {\group_begin:\tl_set:Nn\l__dfg_bibentry_highlight_keyword_tl{#2}
   \printbibliography[#1]\group_end:}
\int_new:N  \g__dfg_boldnames_int
\iow_new:N  \g__dfg_boldnames_iow
\prop_new:N \g__dfg_boldnames_hashes_prop
\tl_new:N   \l__dfg_boldnames_name_tl

% Initialize the backend whenever publications are available. The switch is
% evaluated when a name is printed so project setup can enable it later.
\bool_if:NT \l__dfgbib_backend_bool
{
  % ---------- Auxiliary .bib file -----------------------------------

  \tl_const:Ne \c__dfg_boldnames_bibfile_tl {\DFGBoldNamesFile}
  \iow_open:Nn \g__dfg_boldnames_iow { \c__dfg_boldnames_bibfile_tl }
  \iow_now:Nn  \g__dfg_boldnames_iow { @comment{Auto-generated~file} }
  \AtEndDocument { \iow_close:N \g__dfg_boldnames_iow }
  \addbibresource{\c__dfg_boldnames_bibfile_tl}

  % ---------- Writing a single name ---------------------------------
  %
  % We need:
  %   - the entry KEY  (nhblx@name@<N>)  fully expanded
  %   - the AUTHOR field written verbatim (so \"a etc. survive)
  %
  % \iow_now:Nn  → no expansion
  % \iow_now:Nx  → full expansion (breaks accents in names)
  % \iow_now:Nn + \exp_not:n on the name = best of both via \iow_now:Nx

  \cs_new_protected:Npn \__dfg_boldnames_write:n #1
  {
    \int_gincr:N \g__dfg_boldnames_int
    % Stash the name so it survives the x-expansion intact.
    \tl_set:Nn \l__dfg_boldnames_name_tl { #1 }
    \iow_now:Nx \g__dfg_boldnames_iow
    {
      @misc{nhblx@name@\int_use:N \g__dfg_boldnames_int,
          author~=~{\exp_not:V \l__dfg_boldnames_name_tl},
          options~=~{dataonly=true},
        }
    }
    % Schedule hash extraction after biblatex has loaded the entry.
    \exp_args:Nx \AfterPreamble
    {
      \exp_not:N \hbox_set:Nn \exp_not:N \l_tmpa_box
      { \exp_not:N \nhblx@getmethehash
        { nhblx@name@ \int_use:N \g__dfg_boldnames_int } }
    }
  }

  % ---------- User-level commands -----------------------------------

  \NewDocumentCommand \addboldnames { m }
  { \clist_map_function:nN { #1 } \__dfg_boldnames_write:n }

  \NewDocumentCommand \resetboldnames { }
  { \prop_gclear:N \g__dfg_boldnames_hashes_prop }

  % ---------- biblatex glue -----------------------------------------

  \DeclareNameFormat{nhblx@hashextract}
  {
    \prop_gput:Nen \g__dfg_boldnames_hashes_prop { \thefield{hash} } { }
  }

  \DeclareCiteCommand{\nhblx@getmethehash}
  {}{ \printnames[nhblx@hashextract][1-999]{author} }{}{}

  \cs_new_protected:Npn \__dfg_boldnames_mark:n #1
  {
    \DFGBibIfAuthorsTF
    {
      \prop_if_in:NeTF \g__dfg_boldnames_hashes_prop { \thefield{hash} }
        { \mkbibbold { \textcolor{\DFGBibNameColor} { #1 } } }
        { #1 }
    }
    { #1 }
  }

  \cs_set_eq:NN \mkboldifhashinlist \__dfg_boldnames_mark:n

  \DeclareNameWrapperFormat{boldifhashinlist}
  { \renewcommand*{\mkbibcompletename}{\mkboldifhashinlist} #1 }

  \DeclareNameWrapperAlias{sortname}{default}
  \DeclareNameWrapperAlias{default}{boldifhashinlist}
}

% We need the fallback of the commands in case the functionality isnt used at all.
\providecommand { \addboldnames   } [1] { }
\providecommand { \resetboldnames }     { }

\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</bib-highlights-package>
%<*thumbindex-package>
% \fi
% \subsection{Reusable package: dfg-thumbindex.sty}
% Independent package code shared by the class and standard documents.
%    \begin{macrocode}
%% Copyright 2026 Lukas C. Bossert. LPPL 1.3c or later.
%% Generated from dfg-crc.dtx.
\NeedsTeXFormat{LaTeX2e}[2022-06-01]
\ProvidesExplPackage{dfg-thumbindex}{2026-11-24}{0.4.0}{Independent page-edge thumb index}
\ExplSyntaxOff
\RequirePackage{tikz}
\RequirePackage{scrlayer-scrpage}
\providecolor{thumbIndexBG}{gray}{0}
\providecolor{thumbIndexFont}{gray}{1}
\ExplSyntaxOn
% The class predeclares these live settings; standalone use supplies defaults.
\cs_if_exist:NF \l__dfg_custom_thumbindex_bool
  {
    \bool_new:N \l__dfg_custom_thumbindex_bool
    \bool_set_true:N \l__dfg_custom_thumbindex_bool
    \int_new:N \l__dfg_custom_thumbindexpattern_int
    \int_set:Nn \l__dfg_custom_thumbindexpattern_int {8}
    \dim_new:N \l__dfg_custom_thumbindex_width_dim
    \dim_set:Nn \l__dfg_custom_thumbindex_width_dim {12mm}
    \tl_new:N \l__dfg_custom_thumbindex_font_tl
    \tl_set:Nn \l__dfg_custom_thumbindex_font_tl {\sffamily\bfseries}
    \tl_new:N \l__dfg_custom_thumbIndexBG_tl
    \tl_set:Nn \l__dfg_custom_thumbIndexBG_tl {black}
    \tl_new:N \l__dfg_custom_thumbIndexFont_tl
    \tl_set:Nn \l__dfg_custom_thumbIndexFont_tl {white}
    \bool_new:N \l__dfg_custom_thumbindex_topmargin_set_bool
    \bool_new:N \l__dfg_custom_thumbindex_bottommargin_set_bool
    \dim_new:N \l__dfg_custom_thumbindex_topmargin_dim
    \dim_new:N \l__dfg_custom_thumbindex_bottommargin_dim
    \int_new:N \l__dfg_custom_thumbindex_rotation_int
  }
\keys_define:nn {dfgthumb/setup}
  {
    enabled .bool_set:N = \l__dfg_custom_thumbindex_bool,
    pattern .code:n = {\int_compare:nNnTF {#1}>{0}
      {\int_set:Nn\l__dfg_custom_thumbindexpattern_int{#1}}
      {\msg_error:nn{dfg-thumbindex}{bad-pattern}}},
    width .dim_set:N = \l__dfg_custom_thumbindex_width_dim,
    font .tl_set:N = \l__dfg_custom_thumbindex_font_tl,
    bg .tl_set:N = \l__dfg_custom_thumbIndexBG_tl,
    fg .tl_set:N = \l__dfg_custom_thumbIndexFont_tl,
    orientation .choice:,
    orientation / outwards .code:n = {\int_zero:N\l__dfg_custom_thumbindex_rotation_int},
    orientation / inwards .code:n = {\int_set:Nn\l__dfg_custom_thumbindex_rotation_int{180}},
    topmargin .code:n = {\str_if_eq:nnTF{#1}{auto}
      {\bool_set_false:N\l__dfg_custom_thumbindex_topmargin_set_bool}
      {\bool_set_true:N\l__dfg_custom_thumbindex_topmargin_set_bool
       \dim_set:Nn\l__dfg_custom_thumbindex_topmargin_dim{#1}}},
    bottommargin .code:n = {\str_if_eq:nnTF{#1}{auto}
      {\bool_set_false:N\l__dfg_custom_thumbindex_bottommargin_set_bool}
      {\bool_set_true:N\l__dfg_custom_thumbindex_bottommargin_set_bool
       \dim_set:Nn\l__dfg_custom_thumbindex_bottommargin_dim{#1}}},
  }
\msg_new:nnn {dfg-thumbindex}{bad-pattern}{The~number~of~slots~must~be~positive.}
\NewDocumentCommand \ThumbIndexSetup {m}{\keys_set:nn{dfgthumb/setup}{#1}}
\int_new:N \l_thumb_index_int
\int_zero:N \l_thumb_index_int
% The effective margins follow the current text block unless overridden with
% explicit page-edge dimensions.  Calculate them when drawing each tab rather
% than at class load time, when page geometry may not yet be final.
\dim_new:N \l_thumb_height_dim
\dim_new:N \l_thumb_topmargin_dim
\dim_new:N \l_thumb_bottommargin_dim
\cs_new_protected:Npn \thumb_compute_height:
{
  \bool_if:NTF \l__dfg_custom_thumbindex_topmargin_set_bool
    { \dim_set_eq:NN \l_thumb_topmargin_dim
        \l__dfg_custom_thumbindex_topmargin_dim }
    {
      \dim_set:Nn \l_thumb_topmargin_dim
        { 1in + \voffset + \topmargin + \headheight + \headsep }
    }
  \bool_if:NTF \l__dfg_custom_thumbindex_bottommargin_set_bool
    { \dim_set_eq:NN \l_thumb_bottommargin_dim
        \l__dfg_custom_thumbindex_bottommargin_dim }
    {
      \dim_set:Nn \l_thumb_bottommargin_dim
        {
          \paperheight
          - ( 1in + \voffset + \topmargin + \headheight + \headsep )
          - \textheight
        }
    }
  \dim_set:Nn \l_thumb_height_dim
    {
      ( \paperheight - \l_thumb_topmargin_dim
        - \l_thumb_bottommargin_dim )
      / \l__dfg_custom_thumbindexpattern_int
    }
}
% defining now the layout of the thumb index. Be aware of the stripped spaces in
% the LaTeX3 environment.
\tikzset
{
  thumb/.style=
    {
      fill   = thumbIndexBG ,      % colour may be changed later
      text   = thumbIndexFont,
      minimum~ height = \dim_use:N \l_thumb_height_dim,
    minimum~ width  = \dim_eval:n
      { \l__dfg_custom_thumbindex_width_dim + 7pt },
    outer~ sep      = 0pt,
      font            = \tl_use:N \l__dfg_custom_thumbindex_font_tl,
    inner~ sep      = 1mm,
    }
}
% we need a couple of helper commands though.
%   The <even/odd> macros are now tiny wrappers around a single
%   protected function that does the arithmetic in expl3.
\box_new:N \g__dfg_thumb_shipout_box
\cs_new_protected:Npn \thumb_place_node:nnnn #1#2#3#4
{
  % Build in the running head to retain its fonts, colour and page style.
  \thumb_compute_height:
  \hbox_gset:Nn \g__dfg_thumb_shipout_box
  {
    \begin{tikzpicture}[overlay]
      \node[thumb,anchor=#1,rectangle,rounded~corners=7pt,xshift=#2]
        at (0,0)
      {
        \str_if_eq:nnTF {#1}{west}{\kern2mm}{\kern-2mm}
        \rotatebox[origin=c]{#3}{#4}
        \str_if_eq:nnTF {#1}{west}{\kern-2mm}{\kern2mm}
      };
    \end{tikzpicture}
  }
  % Freeze the page-edge coordinates; no previous-pass picture origin is used.
  \use:x
  {
    \exp_not:N \AddToHookNext {shipout/background}
    {
      \exp_not:N \put
        (\dim_eval:n {\str_if_eq:nnTF {#1}{west}{0pt}{\paperwidth}-\hoffset},
         \dim_eval:n {\voffset-\l_thumb_topmargin_dim
           -\l_thumb_height_dim*(\l_thumb_index_int-1)-\l_thumb_height_dim/2})
        {\exp_not:N\box_use_drop:N \exp_not:N\g__dfg_thumb_shipout_box}
    }
  }
}

\NewDocumentCommand{\evenpageletterthumb}{m}
{
  \thumb_place_node:nnnn {west}{-7pt}
    {\int_eval:n {90 + \l__dfg_custom_thumbindex_rotation_int}}{#1}
}
\NewDocumentCommand{\oddpageletterthumb}{m}
{
  \thumb_place_node:nnnn {east}{7pt}
    {\int_eval:n {-90 + \l__dfg_custom_thumbindex_rotation_int}}{#1}
}
% Now the key command |\printThumbIndex|.
\tl_new:N \l__dfg_thumb_index_options_tl
\keys_define:nn { dfg / thumb-index }
{
  bg .code:n = { \colorlet{thumbIndexBG}{#1} },
  bg .value_required:n = true,
  fg .code:n = { \colorlet{thumbIndexFont}{#1} },
  fg .value_required:n = true,
}
\NewDocumentCommand{\printThumbIndex}{ O{} m }
{
  \bool_if:NT \l__dfg_custom_thumbindex_bool
  {
    \colorlet{thumbIndexBG}{\l__dfg_custom_thumbIndexBG_tl}
    \colorlet{thumbIndexFont}{\l__dfg_custom_thumbIndexFont_tl}
    \tl_set:Ne \l__dfg_thumb_index_options_tl {#1}
    \tl_if_in:VnTF \l__dfg_thumb_index_options_tl {=}
      { \keys_set:nV { dfg / thumb-index } \l__dfg_thumb_index_options_tl }
      {
        \tl_if_blank:VF \l__dfg_thumb_index_options_tl
          { \colorlet{thumbIndexBG}{\l__dfg_thumb_index_options_tl} }
      }

    % ---- reset index if we have reached the bottom of the column -----
    \int_compare:nNnT { \l_thumb_index_int } = { \l__dfg_custom_thumbindexpattern_int }
    { \int_zero:N \l_thumb_index_int }

    % ---- step to the *next* position -----------------------------------
    \int_incr:N \l_thumb_index_int

    % Install the selected tab in normal and plain running heads.
    \lehead[\evenpageletterthumb{#2}]{\evenpageletterthumb{#2}}
    \lohead[\oddpageletterthumb{#2}]{\oddpageletterthumb{#2}}
  }
}
\NewDocumentCommand{\resetThumbIndex}{}
{
  \int_zero:N \l_thumb_index_int
}
\NewDocumentCommand{\printThumbIndexOff}{}
{
  \lehead[]{}
  \lohead[]{}
}

\ExplSyntaxOff
%    \end{macrocode}
% \iffalse
%</thumbindex-package>
%<*test-module-options>
% \fi
%    \begin{macrocode}
"""Check that every package-owned option has a maintained reference entry."""

import json
from pathlib import Path
import re
import unittest


ROOT = Path(__file__).resolve().parent
if ROOT.name == "scripts" and ROOT.parent.name == "__admin":
    ROOT = ROOT.parent.parent
CATALOG = ROOT / "docs/module-options.json"
if not CATALOG.exists():
    CATALOG = ROOT / "dfg-module-options.json"


def balanced(text, start):
    depth = 1
    for pos in range(start, len(text)):
        if text[pos] in "{}" and (pos == 0 or text[pos - 1] != "\\"):
            depth += 1 if text[pos] == "{" else -1
            if depth == 0:
                return text[start:pos]
    raise ValueError("Unclosed option definition")


def normalize(value):
    return re.sub(r"\s*/\s*", "/", " ".join(value.replace("~", " ").split()))


def implemented_keys(package):
    text = re.sub(r"(?<!\\)%[^\n]*", "", package.read_text())
    families = {}
    for match in re.finditer(r"\\keys_define:nn\s*\{([^}]+)\}\s*\{", text):
        body = balanced(text, match.end())
        keys = {normalize(m[1]).split("/")[0].strip() for m in
                re.finditer(r"^\s*([\w /~-]+)\s+\.[\w:]+\s*=", body, re.M)}
        families.setdefault(normalize(match[1]), set()).update(keys - {"unknown"})
    if package.name == "dfg-distribution.sty":
        body = balanced(text, re.search(r"\\pgfkeys\s*\{", text).end())
        families['/distribution'] = {normalize(m[1]).split("/")[0].strip() for m in
            re.finditer(r"^\s*([\w /~-]+)\s*/\.[\w ]+\s*=", body, re.M)
            if not m[1].strip().startswith("/")}
    loading = set(re.findall(r"\\DeclareOption\{([^}]+)\}", text))
    if loading:
        families['package-options'] = loading
    return families


class ModuleOptionDocumentation(unittest.TestCase):
    def test_every_owned_key_is_documented_with_values_defaults_and_effect(self):
        catalog = json.loads(CATALOG.read_text())
        self.assertEqual(len(catalog), 8)
        for module, groups in catalog.items():
            with self.subTest(package=module):
                documented = {}
                for group in groups:
                    self.assertTrue(group['scope'])
                    for option in group['options']:
                        for field in ('name', 'values', 'default', 'effect'):
                            self.assertTrue(option[field], (module, field))
                    for family in group['families']:
                        documented.setdefault(family, set()).update(o['name'] for o in group['options'])
                for family, actual in implemented_keys(ROOT / ('dfg-' + module + '.sty')).items():
                    self.assertIn(family, documented, (module, family))
                    self.assertFalse(actual - documented[family],
                                     (module, family, 'Missing options', actual - documented[family]))

    def test_catalog_and_generated_references_stay_in_sync(self):
        catalog = json.loads(CATALOG.read_text())
        guide = ROOT / 'docs/reusable-modules.md'
        if not guide.exists():
            guide = ROOT / 'dfg-modules.md'
        markdown = guide.read_text()
        dtx = ROOT.parent / 'dfg-crc.dtx'
        if not dtx.exists():
            self.skipTest('Source DTX is needed to check manual generation')
        source = dtx.read_text()
        start = source.index('%<*module-option-catalog>') + len('%<*module-option-catalog>')
        end = source.index('%</module-option-catalog>', start)
        self.assertEqual(catalog, json.loads(source[start:end]))
        for module, groups in catalog.items():
            with self.subTest(package=module):
                first = source.index('% BEGIN MODULE OPTIONS ' + module)
                last = source.index('% END MODULE OPTIONS ' + module, first)
                rendered = source[first:last]
                options = [o for g in groups for o in g['options']]
                self.assertEqual(rendered.count(r'\begin{docKey}'), len(options))
                for option in options:
                    self.assertIn(']{' + option['name'] + '}', rendered)
                    self.assertIn('Initially `' + option['default'] + '`', markdown)
                    self.assertIn(option['effect'], markdown)


if __name__ == '__main__':
    unittest.main()

%    \end{macrocode}
% \iffalse
%</test-module-options>
%<*update-module-options>
"""Generate manual and Markdown option references from the maintained catalog."""

import argparse
import json
from pathlib import Path
import re


def escape(text):
    return ''.join({'\\': r'\textbackslash{}', '{': r'\{', '}': r'\}',
                    '#': r'\#', '$': r'\$', '%': r'\%', '&': r'\&',
                    '_': r'\_', '~': r'\textasciitilde{}', '^': r'\textasciicircum{}'}.get(c, c)
                   for c in text)


def code(text):
    # Break between TeX commands while keeping each command and its arguments together.
    tokens = re.findall(r'\\[A-Za-z]+(?:\{[^{}]*\})*|[^\\]+', text)
    return r'\texttt{' + r'\allowbreak'.join(escape(token) for token in tokens) + '}'


def prose(text):
    return ''.join(r'\texttt{' + escape(p) + '}' if p.startswith('\\') else escape(p)
                   for p in re.split(r'(\\[A-Za-z]+)', text) if p)


def tex_reference(module, groups):
    lines = ['% BEGIN MODULE OPTIONS ' + module]
    commands = [command for group in groups for command in group.get('commands', [])]
    if commands:
        lines.append(r'\section{Commands}')
        for command in commands:
            lines += [r'\begin{docCommand}[doc label={module-' + module + '-command-' + command['name'] +
                      '}]{' + command['name'] + '}{' + command['signature'] + '}',
                      prose(command['description']), r'\end{docCommand}']
    lines += [r'\section{Complete option reference}',
             'Defaults below describe standalone use. Boolean keys accept true or false;\n'
             'a bare boolean key means true, with inverse aliases described explicitly.']
    for index, group in enumerate(groups):
        scope = prose(group['scope']).replace('. ', '.' + r'\par' + '\n')
        lines += [r'\subsection{' + escape(group['title']) + '}', scope]
        if group['options']:
            for option in group['options']:
                slug = re.sub(r'[^A-Za-z0-9-]+', '-', option['name'])
                label = f'module-{module}-{index}-{slug}'
                signature = '' if option['values'].startswith('Bare') else r'=\meta{value}'
                if option['values'].startswith('true or false'):
                    signature = r'\docKeyChoices{true,false}'
                initial = option['default']
                compact = len(initial) <= 20 and '\\' not in initial and ' ' not in initial
                heading = r'initially \texttt{' + escape(initial) + '}' if compact else ''
                lines += [r'\begin{docKey}[][doc label={' + label + '}]{' +
                          escape(option['name']) + '}{' + signature + '}{' + heading + '}',
                          prose(option['effect']),
                          'Accepts ' + prose(option['values']) + '.']
                if not compact:
                    lines.append('Initially ' + code(initial) + '.')
                lines.append(r'\end{docKey}')
    lines += ['% END MODULE OPTIONS ' + module, '']
    return '\n'.join(lines)


def markdown_reference(catalog):
    lines = ['<!-- BEGIN COMPLETE MODULE OPTIONS -->', '## Complete option reference', '',
             'These are standalone defaults. Use command options rather than package-load',
             'options, except for `noauthors` on `dfg-bib-highlights`. Boolean keys accept',
             '`true`/`false`; a bare boolean key means `true`, with inverse aliases noted.', '']
    for module, groups in catalog.items():
        lines += ['### `dfg-' + module + '`', '']
        for group in groups:
            for command in group.get('commands', []):
                signature = re.sub(r'\\marg\{([^}]+)\}', r'{\1}', command['signature'])
                signature = re.sub(r'\\oarg\{([^}]+)\}', r'[\1]', signature)
                lines += ['`\\' + command['name'] + signature + '`', '', command['description'], '']
        for group in groups:
            lines += ['#### ' + group['title'], '', group['scope'], '']
            for option in group['options']:
                lines += ['##### `' + option['name'] + '`', '', option['effect'],
                          'Accepts ' + option['values'] + '. Initially `' + option['default'] + '`.', '']
    lines += ['<!-- END COMPLETE MODULE OPTIONS -->', '']
    return '\n'.join(lines)


def main():
    root = Path(__file__).resolve().parent
    if root.name == 'scripts' and root.parent.name == '__admin':
        root = root.parent.parent
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--dtx', type=Path, default=root.parent / 'dfg-crc.dtx')
    catalog = root / 'docs/module-options.json'
    guide = root / 'docs/reusable-modules.md'
    if not catalog.exists():
        catalog = root / 'dfg-module-options.json'
        guide = root / 'dfg-modules.md'
    parser.add_argument('--catalog', type=Path, default=catalog)
    parser.add_argument('--guide', type=Path, default=guide)
    args = parser.parse_args()
    catalog = json.loads(args.catalog.read_text())
    source = args.dtx.read_text()
    for module, groups in catalog.items():
        start = '% BEGIN MODULE OPTIONS ' + module
        end = '% END MODULE OPTIONS ' + module
        rendered = tex_reference(module, groups)
        if start in source:
            first, last = source.index(start), source.index(end) + len(end)
            source = source[:first] + rendered.rstrip('\n') + source[last:]
        else:
            marker = r'\dfgModuleListing{dfg-' + module + '-example.'
            if module == 'bib-highlights':
                marker = r'\dfgModuleListing{dfg-bib-highlights-example.bib}'
            at = source.index(marker)
            source = source[:at] + rendered + '\n' + source[at:]
    guide = args.guide.read_text()
    first = guide.find('<!-- BEGIN COMPLETE MODULE OPTIONS -->')
    if first >= 0:
        last = guide.index('<!-- END COMPLETE MODULE OPTIONS -->', first) + len('<!-- END COMPLETE MODULE OPTIONS -->')
        guide = guide[:first] + markdown_reference(catalog).rstrip('\n') + guide[last:]
    else:
        at = guide.index('## Other candidates')
        guide = guide[:at] + markdown_reference(catalog) + '\n' + guide[at:]
    args.guide.write_text(guide)
    guard = 'modules-guide'
    first = source.index('%<*' + guard + '>') + len('%<*' + guard + '>')
    last = source.index('%</' + guard + '>', first)
    source = source[:first] + '\n' + guide.rstrip() + '\n\n' + source[last:]
    args.dtx.write_text(source)


if __name__ == '__main__':
    main()
%</update-module-options>
%<*build-module-script>
% \fi
%    \begin{macrocode}
"""Compile the manual's complete package examples in isolated directories."""

import argparse
import json
from pathlib import Path
import re
import shutil
import subprocess
import sys


EXAMPLES = {
    "plots": ("dfg-plots", "dfg-collaboration", "dfg-gantt"),
    "collaboration": ("dfg-plots", "dfg-collaboration"),
    "gantt": ("dfg-plots", "dfg-gantt"),
    "timeline": ("dfg-timeline",),
    "distribution": ("dfg-distribution",),
    "icons": ("dfg-icons",),
    "bib-highlights": ("dfg-bib-highlights",),
    "thumbindex": ("dfg-thumbindex",),
}
EXAMPLES.update({name + '-options': packages for name, packages in list(EXAMPLES.items())})


def run(command, directory):
    result = subprocess.run(command, cwd=directory, capture_output=True,
                            text=True, timeout=180)
    if result.returncode:
        raise RuntimeError(" ".join(map(str, command)) + "\n" +
                           result.stdout[-5000:] + result.stderr[-2000:])


def visible_bbox(pdf, directory, page=1):
    """Measure visible page ink; PDF font boxes can include off-page artwork."""
    prefix = directory / 'visible-preview'
    run(['pdftoppm', '-f', str(page), '-singlefile', '-gray', '-r', '72',
         str(pdf), str(prefix)], directory)
    data = prefix.with_suffix('.pgm').read_bytes()
    tokens = []
    position = 0
    while len(tokens) < 4:
        match = re.match(rb'(?:\s+|\#[^\n]*\n)*(\S+)', data[position:])
        if not match:
            raise RuntimeError('Invalid preview raster header')
        tokens.append(match[1])
        position += match.end()
    magic, width, height, maximum = tokens
    if magic != b'P5' or maximum != b'255':
        raise RuntimeError('Unsupported preview raster format')
    width, height = int(width), int(height)
    pixels = data[-width * height:]
    left, top, right, bottom = width, height, -1, -1
    for index, gray in enumerate(pixels):
        if gray < 250:
            x, y = index % width, index // width
            left, right = min(left, x), max(right, x)
            top, bottom = min(top, y), max(bottom, y)
    if right < left:
        raise RuntimeError('Example preview contains no visible content')
    # At 72 dpi pixels correspond to PDF big points; margins cover rounding.
    return f'{left} {height-bottom-1} {right+1} {height-top}'


def main():
    script = Path(__file__).resolve()
    root = script.parent
    if root.name == "scripts" and root.parent.name == "__admin":
        root = root.parent.parent
    candidates = [root / "docs/examples", root / "module-examples", root]
    source = next((p for p in candidates if (p / "dfg-plots-example.tex").exists()), root)
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source-dir", type=Path, default=source)
    parser.add_argument("--package-dir", type=Path, default=root)
    parser.add_argument("--output-dir", type=Path, default=root / "output/module-examples")
    parser.add_argument("--engine", choices=("lualatex", "pdflatex"), default="lualatex")
    args = parser.parse_args()
    source, packages, output = (p.resolve() for p in
                                (args.source_dir, args.package_dir, args.output_dir))
    for command in ("latexmk", args.engine, "biber"):
        if not shutil.which(command):
            parser.error("Required build tool not found: " + command)
    crop = shutil.which("pdfcrop") if shutil.which("gs") else None
    output.mkdir(parents=True, exist_ok=True)
    manifest = {"engine": args.engine, "examples": {}}
    for name, dependencies in EXAMPLES.items():
        stem = "dfg-" + name + "-example"
        job = output / (stem + "-build")
        job.mkdir(exist_ok=True)
        for filename in [stem + ".tex", *[p.name for p in source.glob("*.bib")],
                         *[p.name for p in source.glob("*.csv")]]:
            shutil.copyfile(source / filename, job / filename)
        for dependency in dependencies:
            shutil.copyfile(packages / (dependency + ".sty"), job / (dependency + ".sty"))
        print("Building " + stem, flush=True)
        flag = "-lualatex" if args.engine == "lualatex" else "-pdf"
        run(["latexmk", flag, "-interaction=nonstopmode", "-halt-on-error", stem + ".tex"], job)
        pdf = output / (stem + ".pdf")
        preview = output / (stem + "-preview.pdf")
        shutil.copyfile(job / (stem + ".pdf"), pdf)
        # Page edges are part of the thumbindex example and must stay visible.
        if crop and not name.startswith("thumbindex"):
            options = []
            if shutil.which('pdftoppm'):
                two_pages = name.endswith('-options') or name == 'collaboration'
                if two_pages:
                    options = ['--bbox-odd', visible_bbox(pdf, job, 1),
                               '--bbox-even', visible_bbox(pdf, job, 2), '--clip']
                else:
                    options = ['--bbox', visible_bbox(pdf, job), '--clip']
            if name.startswith('timeline') and not options:
                shutil.copyfile(pdf, preview)
            else:
                run([crop, '--margins', '4', *options, str(pdf), str(preview)], job)
        else:
            shutil.copyfile(pdf, preview)
        manifest["examples"][name] = {
            "source": stem + ".tex", "packages": list(dependencies),
            "pdf": pdf.name, "preview": preview.name,
        }
    (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
    print(f"Built {len(EXAMPLES)} independent package examples in {output}")


if __name__ == "__main__":
    try:
        main()
    except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
        print(str(error), file=sys.stderr)
        raise SystemExit(1)

%    \end{macrocode}
% \iffalse
%</build-module-script>
%<*test-module-script>
"""Exercise reusable modules in isolated projects with no proposal files."""

import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest


ROOT = Path(__file__).resolve().parent
if ROOT.name == "scripts" and ROOT.parent.name == "__admin":
    ROOT = ROOT.parent.parent
EXAMPLES = ROOT / "docs/examples"
if not EXAMPLES.exists():
    EXAMPLES = ROOT / "module-examples"
ENGINES = [name for name in ("pdflatex", "lualatex") if shutil.which(name)]


@unittest.skipUnless(ENGINES, "Requires a LaTeX engine")
class StandaloneModules(unittest.TestCase):
    def compile(self, name, source, extra=None, biber=False, success=True, packages=None):
        results = []
        for engine in ENGINES:
            temporary = tempfile.TemporaryDirectory(prefix="dfg-module-")
            self.addCleanup(temporary.cleanup)
            directory = Path(temporary.name)
            package_files = (ROOT.glob("dfg-*.sty") if packages is None else
                             [ROOT / (package + ".sty") for package in packages])
            for package in package_files:
                shutil.copyfile(package, directory / package.name)
            for filename, text in (extra or {}).items():
                (directory / filename).write_text(text)
            (directory / "main.tex").write_text(source)
            command = [engine, "-interaction=nonstopmode", "-halt-on-error", "main.tex"]
            output = subprocess.run(command, cwd=directory, capture_output=True, text=True, timeout=90)
            if biber and output.returncode == 0:
                processed = subprocess.run(["biber", "main"], cwd=directory,
                                           capture_output=True, text=True, timeout=90)
                self.assertEqual(processed.returncode, 0, processed.stdout[-5000:])
                output = subprocess.run(command, cwd=directory, capture_output=True, text=True, timeout=90)
                if output.returncode == 0:
                    output = subprocess.run(command, cwd=directory, capture_output=True, text=True, timeout=90)
            elif success and output.returncode == 0:
                output = subprocess.run(command, cwd=directory, capture_output=True, text=True, timeout=90)
            if success:
                self.assertEqual(output.returncode, 0, engine + "\n" + output.stdout[-6000:] + output.stderr)
            else:
                self.assertNotEqual(output.returncode, 0, engine)
            log = (directory / "main.log").read_text()
            results.append((engine, log, directory))
            if destination := os.environ.get("MODULE_TEST_ARTIFACTS"):
                shutil.copytree(directory, Path(destination) / name / engine, dirs_exist_ok=True)
        return results

    def test_collaboration_overrides_selection_and_independent_datasets(self):
        source = r"""\documentclass{article}
\usepackage{dfg-collaboration}
\ExplSyntaxOn
\cs_new_eq:NN \OriginalCollaborationPicture \__dfg_collaboration_plot_picture:
\cs_set_protected:Npn \__dfg_collaboration_plot_picture:
  {\iow_term:x{GRAPH|\Case|\seq_use:Nn\l__dfg_collaboration_plot_nodes_seq{,}|\seq_use:Nn\l__dfg_collaboration_plot_edges_seq{,}}
   \OriginalCollaborationPicture}
\ExplSyntaxOff
\begin{document}
\def\Case{oneoff}
\printPlot[nonFloat,arcs=true,collaboration={A01,A02,A01,Q01}]{{collaboration}{Q01}}
\clearpage
\DeclareCollaborationProject{Q01}{collaboration={A02}}
\DeclareCollaborationProject{A01}{collaborations={Q01}}
\DeclareCollaborationProject{A02}{}
\DeclareCollaborationProject{A03}{}
\DeclareCollaborationProject{X01}{active=false}
\def\Case{override}
\printPlot[nonFloat,arcs=true,collaboration={A03}]{{collaboration}{Q01}}
\clearpage
\def\Case{empty}
\printPlot[nonFloat,collaboration={}]{{collaboration}{Q01}}
\clearpage
\def\Case{reset}
\printPlot[nonFloat,layout=heatmap]{{collaboration}{Q01}}
\clearpage
\def\Case{selection}
\printPlot[nonFloat,show-projects={A01}]{{collaboration}{Q01}}
\clearpage
\def\Case{aliases}
\printPlot[nonFloat,projects={A02},collaborations={A02}]{{collaborations}{Q01}}
\end{document}
"""
        for engine, log, _ in self.compile("collaboration", source):
            rows = {name: (nodes, edges) for name, nodes, edges in
                    re.findall(r"GRAPH\|([^|\s]+)\|([^|\s]*)\|([^\s]*)", log)}
            self.assertEqual(rows["oneoff"], ("A01,A02,Q01", "A01/Q01,A02/Q01"), engine)
            self.assertEqual(rows["override"][1], "A03/Q01", engine)
            self.assertEqual(rows["empty"][1], "", engine)
            self.assertEqual(rows["reset"][1], "A01/Q01,A02/Q01", engine)
            self.assertEqual(rows["selection"], ("A01,Q01", "A01/Q01"), engine)
            self.assertEqual(rows["aliases"], ("A02,Q01", "A02/Q01"), engine)
            self.assertNotIn("X01", rows["reset"][0])
            self.assertNotIn("Overfull", log)

    def test_gantt_nested_workpackages_custom_grid_and_references(self):
        source = r"""\documentclass{article}
\usepackage{dfg-gantt}
\NewCommandCopy{\OriginalGanttTitle}{\gantttitle}
\RenewDocumentCommand{\gantttitle}{O{}mm}{%
  \typeout{QUARTERSTYLE|\GridCase|#1|#2}%
  \OriginalGanttTitle[#1]{#2}{#3}}
\begin{document}
\GanttProject{Study}
\begin{workpackages}
\addWP{methods}{title={Methods},gantt={label={Set up},start=1,end=3}}
Develop the methods.
\begin{workpackages}
\addWP{validation}{gantt={label={Validation},start=2,end=4,style=striped}}
Validate the methods.
\end{workpackages}
\addWP{analysis}{title={Analysis},gantt={label={Analysis},start=3,end=8,style=important}}
Analyse the data.
\end{workpackages}
See \getWP{methods,validation,analysis}.

\def\GridCase{eight}
\printPlot[nonFloat,slots=8,first-quarter=1,year-labels={2027,2028}]{{gantt}}
\clearpage
\def\GridCase{legacy}
\noindent\GanttChart[slots=16,first-quarter=3]{Study}
\end{document}
"""
        for _, log, directory in self.compile("gantt", source):
            self.assertNotIn("Overfull", log)
            self.assertNotIn("undefined", log.lower())
            text = subprocess.check_output(["pdftotext", str(directory / "main.pdf"), "-"], text=True)
            for value in ("2027", "2028", "Validation", "Analysis", "WP 1a"):
                self.assertIn(value, text)
            self.assertIn("Methods Develop the methods.", " ".join(text.split()))
            for case, boundaries in (("eight", [4, 8]), ("legacy", [2, 6, 10, 14])):
                styles = re.findall(r"QUARTERSTYLE\|" + case + r"\|(dfgTitleBottom(?:Right)?Rule)\|", log)
                self.assertEqual([i + 1 for i, style in enumerate(styles)
                                  if style == "dfgTitleBottomRightRule"], boundaries)

    def test_gantt_rejects_reversed_periods(self):
        source = r"""\documentclass{article}\usepackage{dfg-gantt}
\begin{document}\DeclareWorkPackage{P}{bad}{gantt={start=5,end=2}}\end{document}"""
        for _, log, _ in self.compile("gantt-invalid", source, success=False):
            self.assertIn("Invalid period range", log)

    def test_gantt_validates_grid_before_calculating_geometry(self):
        for options in ("slots=0", "slots=-1", "first-quarter=0", "first-quarter=5"):
            with self.subTest(options=options):
                source = r"""\documentclass{article}\usepackage{dfg-gantt}
\begin{document}
\DeclareWorkPackage{P}{methods}{gantt={start=1,end=3}}
\GanttChart[OPTIONS]{P}
\end{document}""".replace("OPTIONS", options)
                for _, log, _ in self.compile("gantt-grid", source, success=False):
                    self.assertIn("Use positive slots", log)
                    self.assertNotIn("Arithmetic overflow", log)
                    self.assertNotIn("Dimension too large", log)

    def test_distribution_dynamic_categories(self):
        source = r"""\documentclass{article}\usepackage{dfg-distribution}
\DeclareDistributionIcon{triangle}{\fill[white](-.5,-.4)--(.5,-.4)--(0,.5)--cycle;}
\DeclareDistributionCategory{academic}{Academic}{blue}{triangle}
\distributionSetup{order={academic,industry},unit width=5mm}
\begin{document}\setDistribution{academic=4,industry=2}\DistributionChart\end{document}"""
        for _, log, _ in self.compile("distribution", source):
            self.assertNotIn("Overfull", log)

    def test_icons_accept_new_registered_names_and_aliases(self):
        source = r"""\documentclass{article}\usepackage{dfg-icons}
\DeclareIcon{custom-brand}{file={example-image-a},aliases={logo}}
\DeclareIcon{custom-portrait}{square={example-image-1x1},vertical={example-image-9x16}}
\IconIfRegisteredTF{logo}{}{\errmessage{Registration missing}}
\begin{document}
\getIcon[height=3]{logo,custom-brand}
This document declares its own icon names and assets. They are independent of
the proposal's built-in images. This paragraph contains enough text to wrap
alongside the icons and then continue below them at the full line width.
The image files are ordinary graphics supplied by the TeX installation.
\par\bigskip
\getIcon[vertical,height=3]{custom-portrait}
A different registered variant is selected for this paragraph. The package
uses the declared file rather than a whitelist of permitted icon names.
The text wraps beside the portrait and returns to the normal paragraph width.
\end{document}"""
        for _, log, _ in self.compile("icons", source):
            self.assertNotIn("Package crc-icons Warning", log)
            self.assertNotIn("Overfull", log)

    def test_icon_redeclaration_replaces_aliases_and_preserves_canonical_names(self):
        source = r"""\documentclass{article}\usepackage{dfg-icons}
\DeclareIcon{brand}{file=example-image-a,aliases={old-name}}
\DeclareIcon{brand}{file=example-image-b,aliases={new-name}}
\IconIfRegisteredTF{old-name}{\errmessage{Stale alias survived}}{}
\IconIfRegisteredTF{new-name}{}{\errmessage{New alias missing}}
\DeclareIcon{example-image-a}{file=example-image-b}
\DeclareIcon{another}{file=example-image-a}
\let\OriginalGraphics\includegraphics
\RenewDocumentCommand\includegraphics{O{} m}{%
  \typeout{REGISTEREDASSET|#2}\OriginalGraphics[#1]{#2}}
\begin{document}
\getIcon[height=2]{example-image-a}
The explicitly registered name keeps its own asset even when another icon
uses that name as an automatic filename alias. Text wraps beside the image.
\end{document}"""
        for _, log, _ in self.compile("icon-redeclare", source):
            self.assertIn("REGISTEREDASSET|example-image-b", log)
            self.assertNotIn("REGISTEREDASSET|example-image-a", log)

    def test_icon_conflicting_explicit_alias_does_not_change_the_registry(self):
        source = r"""\documentclass{article}\usepackage{dfg-icons}
\DeclareIcon{brand}{file=example-image-a,aliases={shared}}
\ExplSyntaxOn
\msg_redirect_name:nnn{crc-icons}{alias-conflict}{warning}
\ExplSyntaxOff
\DeclareIcon{other}{file=example-image-b,aliases={shared}}
\IconIfRegisteredTF{other}{\errmessage{Rejected icon was registered}}{}
\let\OriginalGraphics\includegraphics
\RenewDocumentCommand\includegraphics{O{} m}{%
  \typeout{REGISTEREDASSET|#2}\OriginalGraphics[#1]{#2}}
\begin{document}
\getIcon[height=2]{shared}
The existing alias still selects the original icon after a conflicting
registration. The failed registration leaves the complete registry unchanged.
\end{document}"""
        for _, log, _ in self.compile("icon-alias-conflict", source):
            self.assertIn("already belongs", log)
            self.assertIn("REGISTEREDASSET|example-image-a", log)
            self.assertNotIn("REGISTEREDASSET|example-image-b", log)

    def test_thumbindex_standard_twosided_article(self):
        source = r"""\documentclass[twoside]{article}\usepackage{dfg-thumbindex}
\pagestyle{scrheadings}
\ThumbIndexSetup{pattern=4,topmargin=20mm,bottommargin=20mm,width=10mm,bg=blue}
\begin{document}
\printThumbIndex{First}Odd page.\newpage Even page.\newpage
\printThumbIndex[bg=red,fg=white]{Second}Another section.\newpage
\printThumbIndexOff No tab here.
\end{document}"""
        for _, log, _ in self.compile("thumbindex", source):
            self.assertNotIn("Undefined control sequence", log)

    def test_documented_examples(self):
        dependencies = {
            "plots": ("dfg-plots", "dfg-collaboration", "dfg-gantt"),
            "collaboration": ("dfg-plots", "dfg-collaboration"),
            "gantt": ("dfg-plots", "dfg-gantt"),
            **{name: ("dfg-" + name,) for name in
               ("timeline", "distribution", "icons", "bib-highlights", "thumbindex")},
        }
        dependencies.update({name + '-options': packages for name, packages in list(dependencies.items())})
        examples = {path.name: path for path in EXAMPLES.glob("dfg-*-example.tex")}
        self.assertEqual(set(examples), {"dfg-" + name + "-example.tex" for name in dependencies})
        for name, packages in dependencies.items():
            path = examples["dfg-" + name + "-example.tex"]
            with self.subTest(example=name):
                extra = {p.name: p.read_text() for suffix in ("*.bib", "*.csv")
                         for p in EXAMPLES.glob(suffix)}
                for _, log, _ in self.compile("example-" + path.stem,
                        path.read_text(), extra, biber=name.startswith("bib-highlights"), packages=packages):
                    self.assertNotIn("Overfull", log)

    def test_all_packages_together_in_a_report(self):
        source = r"""\documentclass[twoside]{report}
\usepackage{dfg-collaboration,dfg-gantt,dfg-timeline,dfg-distribution,
 dfg-icons,dfg-bib-highlights,dfg-thumbindex}
\pagestyle{scrheadings}
\begin{document}
\chapter{Independent modules}
Independent plots, events, and distributions.
\dfgPlotSetup{plotOptions={nonFloat},collaborationPlotOptions={arcs=true}}
\printPlot[collaboration={A01}]{{collaboration}{Q01}}
\clearpage
\GanttProject{Study}
\DeclareWorkPackage{Study}{methods}{title={Methods},gantt={start=1,end=4}}
\printPlot[slots=4,first-quarter=1]{{gantt}}
\clearpage
\addEvent{date=2027-03,category=progress,title={Progress}}
\printEventTimeline[width=\linewidth]
\par\bigskip
\setDistribution{postdoc=2,industry=1}\DistributionChart
\end{document}"""
        for _, log, _ in self.compile("combined", source):
            self.assertNotIn("Overfull", log)

    @unittest.skipUnless(shutil.which("biber"), "Requires Biber")
    def test_bibliography_author_hashes_and_whole_entry_highlights(self):
        source = r"""\documentclass{article}
\usepackage[backend=biber,style=numeric]{biblatex}
\usepackage{dfg-bib-highlights}
\addbibresource{refs.bib}
\addboldnames{{Doe, Jane}}
\BibHighlightSetup{keyword=important}
\makeatletter
\AtEveryBibitem{\typeout{BIBENTRY|\thefield{entrykey}|\f@series}}
\makeatother
\begin{document}\nocite{highlight,normal}\printbibliography
\ExplSyntaxOn
\file_if_exist:nT{\jobname.bbl}
 {\int_compare:nNnF{\prop_count:N\g__dfg_boldnames_hashes_prop}>{0}
   {\errmessage{No Biber author hashes loaded}}}
\ExplSyntaxOff
\end{document}"""
        bib = "@article{highlight,author={Doe, Jane and Roe, John},title={Highlighted paper},journaltitle={Journal},date={2026},keywords={important}}\n@article{normal,author={Roe, John},title={Normal paper},journaltitle={Journal},date={2025}}\n"
        for _, log, _ in self.compile("bibliography", source, {"refs.bib": bib}, biber=True):
            self.assertRegex(log, r"BIBENTRY\|highlight\|b(?:x)?")
            self.assertIn("BIBENTRY|normal|m", log)


if __name__ == "__main__":
    unittest.main()
%</test-module-script>
%<*example-options-plots>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-collaboration,dfg-gantt}
\dfgPlotSetup{plotOptions={style=proposalPlots,nonFloat},
  collaborationPlotOptions={arcs=true,caption={Shared defaults.}},
  ganttPlotOptions={caption={Default chart note.}}}
\GanttSetup{slots=8,first-quarter=1,year-labels={Pilot,Study}}
\pagestyle{empty}
\begin{document}
\dfgPlotProject{Q01}
\printPlot[collaboration={A01,B01},width=.85\linewidth]{{collaboration}}
\clearpage
\DeclareWorkPackage{Q01}{methods}{gantt={label={Methods},start=1,end=8}}
\printPlot[capPos=bottom,floatCapSep=4pt,caption={} ]{{gantt}}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-plots>
%<*example-options-collaboration>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-collaboration}
\DeclareCollaborationProject{Q01}{area=Service,collaboration={A01,B01}}
\DeclareCollaborationProject{A01}{area=Research}
\DeclareCollaborationProject{B01}{area=Clinical}
\DeclareCollaborationProject{X01}{area=External,active=false}
\CollaborationSetup{area-colors={Research=orange,Clinical=blue,Service=teal}}
\pagestyle{empty}
\begin{document}
\printPlot[nonFloat,arcs,capPos=top,show-projects={A01,B01},
  caption={The focus is included automatically.}]{{collaboration}{Q01}}
\clearpage
\printPlot[nonFloat,layout=heatmap,collaboration={},show-projects={A01},
  caption={No connections; only the selected project and focus.}]
  {{collaboration}{Q01}}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-collaboration>
%<*example-options-gantt>
\documentclass{article}
\usepackage{dfg-gantt}
\GanttSetup{slots=12,first-quarter=2,
  year-labels={Pilot,Study,Follow-up,Evaluation}}
\DeclareWorkPackage{Study}{setup}{gantt={label={Setup},start=1,end=3,
  style=important}}
\DeclareWorkPackage{Study}{trial}{gantt={label={Trial},start=3,end=9,
  style=striped}}
\DeclareWorkPackage{Study}{analysis}{gantt={label={Analysis},start=8,end=11,
  style=crosshatch}}
\pagestyle{empty}
\begin{document}
\printPlot[nonFloat,capPos=top,caption={Starting in Q2.}]{{gantt}{Study}}
\clearpage
\noindent\GanttChart[slots=16,first-quarter=1,
  year-labels={Phase 1,Phase 2,Phase 3,Phase 4}]{Study}
\end{document}
%</example-options-gantt>
%<*example-options-timeline>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-timeline}
\addEvent{id=kickoff,date=2027-01,category=progress,title={Start},
  label={Launch},abbreviation={K},summary={Agree on methods},
  description={The first methods review.}}
\addEvent{id=annual,start date=2027-08-10,end date=2027-08-12,
  category=symposium,title={Summer meeting},abbreviation={SM},
  summary={Discuss results},description={A joint symposium.}}
\addEvent{date=2028-02,category=progress,title={Review},
  description={The next methods review.}}
\pagestyle{empty}
\begin{document}
\printEventTimeline[year=2027,labels=abbreviation,summary=true,icons=false,
  rotation=45,date rotation=0,label width=25mm,legend=false,
  events={kickoff={lane=0,date lane=1,xshift=1mm},
    annual={lane=1,date lane=0,node options={text=blue!70!black}}}]
\clearpage
\printEventDetails[format=list,aggregated=true,nodate,
  categories={progress={title={Research milestones},
    description={Shared review of progress.}}}]
\bigskip
\printEventDetails[year=2027,format=prose,icons=false]
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-timeline>
%<*example-options-distribution>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-distribution}
\DeclareDistributionCategory{study}{Study}{blue}{cap}
\DeclareDistributionCategory{clinical}{Clinical}{teal}{bulb}
\distributionSetup{order={study,clinical},unit width=6mm,
  label position=below,row spacing=18mm,bar height=5mm,
  label x=-14mm,label width=18mm,icon radius=2.8mm,
  text color=black,axis color=gray}
\pagestyle{empty}
\begin{document}
\setDistribution{study=5,clinical=2}
\DistributionChart
\clearpage
\DistributionChart[label position=left,icon raise=auto,
  order={clinical,study},row spacing=11mm,unit width=10mm,
  label width=20mm,label gap=3mm,separator width=.8pt]
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-distribution>
%<*example-options-icons>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-icons}
\DeclareIcon{logo}{file=example-image-a,aliases={partner}}
\DeclareIcon{portrait}{square=example-image-1x1,vertical=example-image-9x16}
\pagestyle{empty}
\begin{document}
\getIcon[square,height=2,gap=1em,trim={2 2 2 2},clip]{partner,portrait}
The square variants share a short area beside this paragraph. The line count
sets their common height, and the gap separates both icons and the text.
Graphic options such as trim and clip are forwarded to each image. The text
continues at full width after the reserved lines, keeping all of it visible.
\clearpage
\getIcon[vertical,height=4,gap=8pt]{portrait,logo}
The portrait variant now occupies four lines. The logo has only one asset,
so that same file supplies either shape. Both graphics remain side by side
and the paragraph wraps beside their combined width. Further text shows
how the paragraph returns to its normal full width after the images.
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-icons>
%<*example-options-bib-highlights>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage[backend=biber,style=numeric]{biblatex}
\usepackage{dfg-bib-highlights}
\addbibresource{dfg-bib-highlights-example.bib}
\addboldnames{{Doe, Jane}}
\pagestyle{empty}
\begin{document}
\nocite{highlight,normal}
\BibHighlightSetup{emphasizeAuthors=true,emphasizeEntries=false,color=blue}
\printbibliography[heading=subbibliography,title={Only selected authors}]
\clearpage
\resetboldnames
\BibHighlightSetup{emphasizeAuthors=false,emphasizeEntries=true}
\printHighlightedBibliography[heading=subbibliography,
  title={Whole entries with the selected keyword}]{important}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-bib-highlights>
%<*example-options-thumbindex>
% \fi
%    \begin{macrocode}
\documentclass[twoside]{article}
\usepackage{dfg-thumbindex}
\pagestyle{scrheadings}
\ThumbIndexSetup{pattern=2,width=8mm,orientation=inwards,
  font={\small\sffamily},bg=black,fg=white}
\begin{document}
\printThumbIndex[bg=orange,fg=black]{Start}
Odd page: inward orientation and local colours.
\newpage
Even page: the same tab appears on the opposite edge.
\clearpage
\printThumbIndex[blue]{Methods}
The second slot uses blue with the default white text.
\clearpage
\resetThumbIndex
\printThumbIndex[bg=green!50!black]{Appendix}
The slot sequence starts again at the top.
\clearpage
\printThumbIndexOff
No tab remains on this page.
\end{document}

%    \end{macrocode}
% \iffalse
%</example-options-thumbindex>
%<*example-module-plots>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-collaboration,dfg-gantt}
\dfgPlotSetup{
  plotOptions={nonFloat,capPos=top},
  collaborationPlotOptions={arcs=true},
  ganttPlotOptions={caption={Shared plot defaults.}}
}
\pagestyle{empty}
\begin{document}
\dfgPlotProject{Q01}
\printPlot[collaboration={A01,A02}]{{collaboration}}
\bigskip
\DeclareWorkPackage{Q01}{methods}{gantt={label={Methods},start=1,end=4}}
\printPlot[slots=4,first-quarter=1]{{gantt}}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-plots>

%<*example-module-readme>
% \fi
%    \begin{macrocode}
# Independent package examples

Each `dfg-*-example.tex` is a complete document using `article`. Copy the
listed `.sty` files and any companion data beside an example, then run
`latexmk -lualatex dfg-gantt-example.tex` (substitute its filename).
`latexmk -pdf` also works. Bibliography highlighting needs Biber.
The icon example uses the standard TeX `mwe` sample graphics.

| Example | Package files to copy | Companion data |
|---|---|---|
| `dfg-plots-example.tex` | `dfg-plots.sty`, `dfg-collaboration.sty`, `dfg-gantt.sty` | None |
| `dfg-collaboration-example.tex` | `dfg-plots.sty`, `dfg-collaboration.sty` | None |
| `dfg-gantt-example.tex` | `dfg-plots.sty`, `dfg-gantt.sty` | None |
| `dfg-timeline-example.tex` | `dfg-timeline.sty` | None |
| `dfg-distribution-example.tex` | `dfg-distribution.sty` | None |
| `dfg-icons-example.tex` | `dfg-icons.sty` | None |
| `dfg-bib-highlights-example.tex` | `dfg-bib-highlights.sty` | `dfg-bib-highlights-example.bib` |
| `dfg-thumbindex-example.tex` | `dfg-thumbindex.sty` | None |

In the proposal repository, `make module-examples` builds all sixteen examples
in isolated directories under `output/module-examples`. The maintained DTX
contains their sources; both installers export the same example files.
The main PDF manual includes these files and their independently compiled
results in its final part, **Independent LaTeX packages**.

## Option combinations

Each variant uses the same package files as its minimal example above.

| Configured example | Options illustrated |
|---|---|
| `dfg-plots-options-example.tex` | Shared styles, per-type captions, local float overrides |
| `dfg-collaboration-options-example.tex` | Area colours, selected nodes, empty connections |
| `dfg-gantt-options-example.tex` | Quarter grids, year titles, bar styles, graphic-only output |
| `dfg-timeline-options-example.tex` | Year filters, abbreviations, lanes, aggregated details |
| `dfg-distribution-options-example.tex` | Label position, geometry, row order, separators |
| `dfg-icons-options-example.tex` | Variants, grouping, reserved lines, graphic cropping |
| `dfg-bib-highlights-options-example.tex` | Author colour, entry emphasis, local keywords |
| `dfg-thumbindex-options-example.tex` | Inward orientation, colours, slot reset, off switch |

%    \end{macrocode}
% \iffalse
%</example-module-readme>
%<*example-module-bibliography>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage[backend=biber,style=numeric]{biblatex}
\usepackage{dfg-bib-highlights}
\addbibresource{dfg-bib-highlights-example.bib}
\addboldnames{{Doe, Jane}}
\BibHighlightSetup{emphasizeAuthors=true,emphasizeEntries=true,keyword=important}
\pagestyle{empty}
\begin{document}
\nocite{highlight,normal}
\printbibliography
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-bibliography>
%<*example-module-collaboration>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-collaboration}
\DeclareCollaborationProject{Q01}{area=Services,collaboration={A01}}
\DeclareCollaborationProject{A01}{area=Research}
\DeclareCollaborationProject{A02}{area=Research,collaboration={Q01}}
\pagestyle{empty}
\begin{document}
\printPlot[nonFloat,arcs=true,collaboration={A02}]{{collaboration}{Q01}}
\clearpage
\printPlot[nonFloat,layout=heatmap]{{collaboration}{Q01}}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-collaboration>

%<*example-module-distribution>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-distribution}
\DeclareDistributionIcon{triangle}{%
  \fill[white](-.5,-.4)--(.5,-.4)--(0,.5)--cycle;}
\DeclareDistributionCategory{academic}{Academic}{blue}{triangle}
\distributionSetup{order={academic,industry},unit width=5mm}
\pagestyle{empty}
\begin{document}
\setDistribution{academic=4,industry=2}
\DistributionChart
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-distribution>
%<*example-module-gantt>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-gantt}
\GanttSetup{slots=8,first-quarter=1,year-labels={2027,2028}}
\pagestyle{empty}
\begin{document}
\GanttProject{Study}
\begin{workpackages}
  \addWP{methods}{title={Methods},gantt={label={Set up},start=1,end=3}}
  Develop the methods.
  \begin{workpackages}
    \addWP{validation}{gantt={label={Validation},start=2,end=4,style=striped}}
    Validate the methods.
  \end{workpackages}
  \addWP{analysis}{title={Analysis},gantt={start=4,end=8,style=important}}
  Analyse the results.
\end{workpackages}
See \getWP{methods,validation,analysis}.

\printPlot[nonFloat]{{gantt}}
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-gantt>
%<*example-module-icons>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-icons}
\DeclareIcon{my-brand}{file={example-image-a},aliases={brand}}
\DeclareIcon{portrait}{square={example-image-1x1},vertical={example-image-9x16}}
\pagestyle{empty}
\begin{document}
\getIcon[height=3]{brand,portrait}
This example registers its own icon names and assets. There is no fixed list
of permitted icon names. A single asset can serve both shapes, or separate
square and vertical variants can be declared. The paragraph wraps alongside
the complete icon group and continues at its full width below the graphics.
Further text makes the transition visible in this short standalone example.
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-icons>
%<*example-module-references>
% \fi
%    \begin{macrocode}
@article{highlight,
  author = {Doe, Jane and Roe, John},
  title = {A highlighted entry},
  journaltitle = {Example Journal},
  date = {2026},
  keywords = {important}
}
@article{normal,
  author = {Doe, Jane and Roe, John},
  title = {A regular entry with an emphasized author},
  journaltitle = {Example Journal},
  date = {2025}
}

%    \end{macrocode}
% \iffalse
%</example-module-references>
%<*example-module-thumbindex>
% \fi
%    \begin{macrocode}
\documentclass[twoside]{article}
\usepackage{dfg-thumbindex}
\pagestyle{scrheadings}
\ThumbIndexSetup{pattern=4,width=10mm,topmargin=20mm,bottommargin=20mm,
  bg=blue,fg=white}
\begin{document}
\printThumbIndex{First}
An odd page.
\newpage
An even page in the same section.
\clearpage
\printThumbIndex[bg=red]{Second}
The next section occupies the next slot.
\clearpage
\printThumbIndexOff
This page has no tab.
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-thumbindex>
%<*example-module-timeline>
% \fi
%    \begin{macrocode}
\documentclass{article}
\usepackage{dfg-timeline}
\pagestyle{empty}
\begin{document}
\addEvent{date=2027-03-12,category=progress,title={Progress meeting},
  description={Discuss the first results.}}
\addEvent{start date=2027-06-20,end date=2027-06-22,
  category=symposium,title={Research symposium}}
\printEventTimeline[width=\linewidth,rotation=45]
\printEventDetails[format=prose]
\end{document}

%    \end{macrocode}
% \iffalse
%</example-module-timeline>
%<*main>
% \fi
% \section{Generated files and examples}
% \subsection{Main file}
% In this section we provide a skeleton of files to be used as a starting point
% for your proposal. You can adjust the content anytime.
% The following code block leads to a strange behaviour and \\ in a table are ignored,
% it can be fixed with a minipage around the table.
%    \begin{macrocode}
% \DocumentMetadata{
%   pdfstandard=A-2b,
%   lang=en-EN,
%   % tagging=structure,
%   % uncompress
% }
\documentclass[
  showtags         =true,
  showtags-tables  =false,
  showmarginalia   =true,
  % fastcompile    =true,
  % fastcompile-project =true,
  % fastcompile-project-show-images=true,
  % fastcompile-project-show-publications=false,
  % skip10pub      =true,
  % colorscheme    =rgb,
  % final          =true,
  english % <-- needed here
]{dfg-crc}
%    \end{macrocode}
% Use |\frontmatter| before the title pages and table of contents. It selects
% lowercase Roman page numbers and unnumbered chapters. Use |\mainmatter|
% before General information: it clears the preliminary pages, restores
% numbered chapters, and restarts Arabic page numbering at 1.
% When updating an existing proposal, also copy the page-numbering setup below
% into its customized proposal drivers: the update targets preserve these files.
% We use |includeonly| for the case to compile only one, two or n-many chapters.
% This speeds up the compiling time in case you are working mainly and currently
% on one specific chapter.
%    \begin{macrocode}
%% % \includeonly{
%% %   content/01_general-information,
%% %   content/02_existing-funds-and-requested-funds,
%% %   content/03_project,
%% %   content/04_bylaws-of-the-crc,
%% %   content/05_declarations
%% %}
\begin{document}
% Preliminary pages use lowercase Roman page numbers.
\frontmatter
\dfgIfFastCompileProjectF{\input{content/00_titlepage}}
% Start numbered chapters on Arabic page 1.
\mainmatter
\include{content/01_general-information}
\include{content/02_existing-funds-and-requested-funds}
\include{content/03_project}
\include{content/04_bylaws-of-the-crc}
\include{content/05_declarations}
\include{content/99_backmatter}
\end{document}
%    \end{macrocode}
% \iffalse
%</main>
%<*doc-proposal>
% \fi
% \subsection{Complete proposal included in the manual}
% The documentation build uses the same main file and chapter inputs as the
% local proposal, including its shared consortium metadata and project files. Final mode removes drafting aids. The makefile compiles this generated wrapper
% before the manual and publishes its PDF beside the manual.
%    \begin{macrocode}
\PassOptionsToClass{final=true}{dfg-crc}
\input{crc-proposal.tex}
%    \end{macrocode}
% \iffalse
%</doc-proposal>
%<*research-example>
% \fi
% \subsection{Shared research-project example}
% Each compact project file supplies its own ID and status to this reusable
% example body. All project leaders and affiliations come from shared metadata.
%    \begin{macrocode}
\providecommand{\dfgExampleResearchProject}[2]{%
  \printProjectHead{#1}
  \section{Summary}
  This project investigates \getEntry[project]{#1}{name}. Its project leaders
  combine experimental and analytical approaches within the shared research
  programme of \thisCRC.
  \ifstrequal{#2}{C}{%
    \section{Project progress to date}
    The preceding funding period established the experimental models and
    shared datasets. The next phase tests causal mechanisms and validates
    their relevance across the participating projects.
  }{%
    \section{Research rationale}
    Preliminary observations motivate a new testable hypothesis. The project
    establishes its experimental framework and independent validation strategy
    during the requested funding period.
  }
  \projectPublicationsHeading
  \projectNocite{FAIR2016}
  \printProjectBibliography[heading=none]
  \section{Project plan}
  \begin{aims}
    \addAim{1} Establish reproducible experimental and analytical workflows.
    \addAim{2} Validate the findings in complementary models and datasets.
  \end{aims}
  \begin{workpackages}
    \addWP{wp1}{
      name = {Experimental framework},
      description = {Establish models, controls, and quality criteria},
      periodStart = {1}, periodEnd = {7}, style = {default}
    }
    Define the controls, sampling strategy, and analysis workflow for \getAim{1}.
    \addWP{wp2}{
      name = {Validation and integration},
      description = {Validate results and integrate consortium datasets},
      periodStart = {6}, periodEnd = {16}, style = {important}
    }
    Test robustness and share the validated results for \getAim{2}.
  \end{workpackages}
  \printPlot{{Gantt}{#1}}
  \section{Relevance of sex, gender and/or diversity in the research project}
  Include relevant biological variables in sampling and analysis; document
  the rationale for each model and the limits of generalisation.
  \section{Role within the Collaborative Research Centre}
  Share methods, data, and validation resources with the linked projects.
  \printPlot{{ProjectCollaboration}{#1}}
  \section{Differentiation from other funded projects}
  The proposed work addresses the CRC-specific hypothesis and does not
  duplicate personnel or experiments supported by other grants.
  \section{Project funding}
  \addEntry[funding]{RequestedFunding}{
    ref-project-id = {#1}, funding-type = {staff}, category = {PhD},
    percentage = {65},
    quantity = {year1=1,year2=1,year3=1,year4=1,year5=1}
  }
  \addEntry[funding]{RequestedFunding}{
    ref-project-id = {#1}, funding-type = {costs}, category = {consumables},
    sum = {year1=1000,year2=2000,year3=2000,year4=2000,year5=1000}
  }
  \printTable{{RequestedFunding}{#1}}
  The doctoral researcher performs the experiments and integrates the data.
  Consumables cover sample preparation, assays, and independent validation.
  \printProjectTail
}
%    \end{macrocode}
% \iffalse
%</research-example>
%<*doc-projects>
% \fi
% \subsection{Complete local project index}
%    \begin{macrocode}
\chapter{Project details}
\printThumbIndex{3}
\dfgTOCprojectPart{A}{Research Projects}
\input{content/03_project_A01}
\input{content/03_project_A02}
\input{content/03_project_A03}
\input{content/03_project_A04}
\input{content/03_project_A05}
\input{content/03_project_A06}
\dfgTOCprojectPart{B}{Research Projects}
\input{content/03_project_B01}
\input{content/03_project_B02}
\input{content/03_project_B03}
\input{content/03_project_B04}
\input{content/03_project_B05}
\input{content/03_project_B06}
\dfgTOCprojectPart{Q}{Central Projects}
\input{content/03_project_Q01}
\input{content/03_project_Q02}
\input{content/03_project_Q03}
\dfgTOCprojectPart{A}{Former project}
\input{content/03_project_A00}
%    \end{macrocode}
% \iffalse
%</doc-projects>
%<*03-project-a03>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{A03}{C}
%    \end{macrocode}
% \iffalse
%</03-project-a03>
%<*03-project-a04>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{A04}{N}
%    \end{macrocode}
% \iffalse
%</03-project-a04>
%<*03-project-a05>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{A05}{C}
%    \end{macrocode}
% \iffalse
%</03-project-a05>
%<*03-project-a06>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{A06}{N}
%    \end{macrocode}
% \iffalse
%</03-project-a06>
%<*03-project-b02-new>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{B02}{N}
%    \end{macrocode}
% \iffalse
%</03-project-b02-new>
%<*03-project-b03>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{B03}{C}
%    \end{macrocode}
% \iffalse
%</03-project-b03>
%<*03-project-b04>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{B04}{N}
%    \end{macrocode}
% \iffalse
%</03-project-b04>
%<*03-project-b05>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{B05}{C}
%    \end{macrocode}
% \iffalse
%</03-project-b05>
%<*03-project-b06>
% \fi
%    \begin{macrocode}
\input{content/03_project_research-example}
\dfgExampleResearchProject{B06}{N}
%    \end{macrocode}
% \iffalse
%</03-project-b06>
%<*doc-cv>
% \fi
% \subsection{Complete CV appendix included in the manual}
% Reuse the starter CV and its metadata, suppress drafting aids, and expose
% destinations for the manual's individual-CV previews. The header wrapper
% adds an invisible target after the original header has selected its page.
%    \begin{macrocode}
\PassOptionsToClass{final=true}{dfg-crc}
\AddToHook{class/dfg-crc/after}{%
  \NewCommandCopy{\dfgDocOriginalCVHeader}{\dfgCVheader}
  \RenewDocumentCommand{\dfgCVheader}{m}{%
    \dfgDocOriginalCVHeader{#1}%
    \hypertarget{doc-cv:#1}{}%
  }%
}
\input{crc-cv.tex}
%    \end{macrocode}
% \iffalse
%</doc-cv>
%<*bib>
%<*base>
% \fi
% \subsection{Bibliography Files}
% There are at least two bibliography files in the folder |bib/|.
% One is for the common |bibtex|-entries, the others contain so called
% |strings|.
% \subsubsection{Main Bibliography File}
%    \begin{macrocode}
@Article{FAIR2016,
  	Author          = {Wilkinson, Mark D. and others},
  	Title           = {The {FAIR} Guiding Principles for scientific data management and stewardship},
  	JournalTitle    = {Scientific Data},
  	Date            = {2016-12},
  	DOI             = {10.1038/sdata.2016.18},
  	Keywords        = {{FAIR}},
  	langid          = {english},
  	Number          = {1},
  	Pages           = {160018},
  	ShortJournal    = {Sci Data},
  	URLDate         = {2021-05-31},
  	Volume          = {3}
  }

@Comment{All ExampleCV records below are fictional template examples, not real research outputs.}

@Article{ExampleCVper1,
  Author       = {Sample, Kim},
  Title        = {Illustrative study of microbial metabolites and epithelial signalling},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per1-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper1Methods,
  Author       = {Sample, Kim},
  Title        = {Reproducible methods for microbial metabolites and epithelial signalling},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per1-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper1Data,
  Author       = {Sample, Kim},
  Title        = {Fictional demonstration dataset: microbial metabolites and epithelial signalling},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per1-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper2,
  Author       = {Example, Alex},
  Title        = {Illustrative study of multimodal data integration and reproducible analysis},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per2-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper2Methods,
  Author       = {Example, Alex},
  Title        = {Reproducible methods for multimodal data integration and reproducible analysis},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per2-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper2Data,
  Author       = {Example, Alex},
  Title        = {Fictional demonstration dataset: multimodal data integration and reproducible analysis},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per2-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper3,
  Author       = {Meier, Hansi},
  Title        = {Illustrative study of microbial sensing and innate immune memory},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per3-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper3Methods,
  Author       = {Meier, Hansi},
  Title        = {Reproducible methods for microbial sensing and innate immune memory},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per3-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper3Data,
  Author       = {Meier, Hansi},
  Title        = {Fictional demonstration dataset: microbial sensing and innate immune memory},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per3-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper4,
  Author       = {Miller, Kimmi},
  Title        = {Illustrative study of epithelial repair and tissue regeneration},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per4-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper4Methods,
  Author       = {Miller, Kimmi},
  Title        = {Reproducible methods for epithelial repair and tissue regeneration},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per4-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper4Data,
  Author       = {Miller, Kimmi},
  Title        = {Fictional demonstration dataset: epithelial repair and tissue regeneration},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per4-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper5,
  Author       = {Redata, Friedhelm},
  Title        = {Illustrative study of structured doctoral training and research integrity},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per5-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper5Methods,
  Author       = {Redata, Friedhelm},
  Title        = {Reproducible methods for structured doctoral training and research integrity},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per5-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper5Data,
  Author       = {Redata, Friedhelm},
  Title        = {Fictional demonstration dataset: structured doctoral training and research integrity},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per5-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper6,
  Author       = {Hartmann, Samira},
  Title        = {Illustrative study of microbial metabolic pathways and immune adaptation},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per6-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper6Methods,
  Author       = {Hartmann, Samira},
  Title        = {Reproducible methods for microbial metabolic pathways and immune adaptation},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per6-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper6Data,
  Author       = {Hartmann, Samira},
  Title        = {Fictional demonstration dataset: microbial metabolic pathways and immune adaptation},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per6-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper7,
  Author       = {Lindberg, Noah},
  Title        = {Illustrative study of spatial immune niches and quantitative imaging},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per7-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper7Methods,
  Author       = {Lindberg, Noah},
  Title        = {Reproducible methods for spatial immune niches and quantitative imaging},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per7-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper7Data,
  Author       = {Lindberg, Noah},
  Title        = {Fictional demonstration dataset: spatial immune niches and quantitative imaging},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per7-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper8,
  Author       = {Winters-Scholz, Alexis-Marie},
  Title        = {Illustrative study of dietary perturbations and mucosal microbial communities},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per8-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper8Methods,
  Author       = {Winters-Scholz, Alexis-Marie},
  Title        = {Reproducible methods for dietary perturbations and mucosal microbial communities},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per8-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper8Data,
  Author       = {Winters-Scholz, Alexis-Marie},
  Title        = {Fictional demonstration dataset: dietary perturbations and mucosal microbial communities},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per8-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper9,
  Author       = {Navarro, Leonie},
  Title        = {Illustrative study of nutrient sensing and predictive metabolic models},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per9-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper9Methods,
  Author       = {Navarro, Leonie},
  Title        = {Reproducible methods for nutrient sensing and predictive metabolic models},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per9-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper9Data,
  Author       = {Navarro, Leonie},
  Title        = {Fictional demonstration dataset: nutrient sensing and predictive metabolic models},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per9-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper10,
  Author       = {Okafor, Daniel},
  Title        = {Illustrative study of microbial biomarkers and clinical tissue responses},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per10-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper10Methods,
  Author       = {Okafor, Daniel},
  Title        = {Reproducible methods for microbial biomarkers and clinical tissue responses},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per10-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper10Data,
  Author       = {Okafor, Daniel},
  Title        = {Fictional demonstration dataset: microbial biomarkers and clinical tissue responses},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per10-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper11,
  Author       = {Sato, Mira},
  Title        = {Illustrative study of inflammatory circuits between intestine and liver},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per11-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper11Methods,
  Author       = {Sato, Mira},
  Title        = {Reproducible methods for inflammatory circuits between intestine and liver},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per11-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper11Data,
  Author       = {Sato, Mira},
  Title        = {Fictional demonstration dataset: inflammatory circuits between intestine and liver},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per11-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper12,
  Author       = {Keller, Robin},
  Title        = {Illustrative study of patient-derived models and biomarker translation},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2025},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per12-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Article{ExampleCVper12Methods,
  Author       = {Keller, Robin},
  Title        = {Reproducible methods for patient-derived models and biomarker translation},
  JournalTitle = {Fictional Journal of Consortium Research},
  Date         = {2024},
  Volume       = {1},
  Pages        = {1--8},
  Keywords     = {per12-A},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}

@Dataset{ExampleCVper12Data,
  Author       = {Keller, Robin},
  Title        = {Fictional demonstration dataset: patient-derived models and biomarker translation},
  Date         = {2025},
  Version      = {1.0},
  Publisher    = {Example Research Repository},
  Keywords     = {per12-B},
  Note         = {Fictional reference for template demonstration only},
  LangID       = {english}
}
%    \end{macrocode}
% \iffalse
%</base>
%<*strings>
% \fi
% \subsubsection{Bibliography Strings}
% The |strings| are used for quick and consistent referencing parts repeatedly.
%    \begin{macrocode}
@String {equal      = {\textit{*equal contribution}}}
@String {sharedlast = {\textit{*shared last authorship}}}
%    \end{macrocode}
% \iffalse
%</strings>
%</bib>
%<*custom>
% \fi
% \subsection{Customization File}
% In the file \dfgFile{preamble/dfg-customization} you can adjust settings of
% this template. Further information you find in \cref{doc:customization}.
% If you want to create new commands put them in this file as well.
%    \begin{macrocode}
% \title{<Title>}
% \subtitle{<Subtitle>}
%% \changeSettings{
%% dfgLocation                 ={<Location>},
%% dfgDate                     ={<date>},
%% dfgTitle                    ={<Proposal title>},
%% InfoTeX                     ={<Compiler information>},
%% font                        =<nn>,
%% crcLogoPath                 =<file path>,
%% affiliationLogoPath         =<file path>,
%% doiAPIMail                  =<contact email for optional DOI API lookup>,
%% projectPIOncePerSection     =true,
%% projectsTableInstitutionAbbreviations=false,
%% categoryAbbreviations=false,
%% cvTableAfterSkip            ={0pt},
%% % Alternative built-in style: plotOptions={style=proposalPlots}.
%% plotOptions                 ={floatPos=!hb,capPos=bottom},
%% ganttPlotOptions            ={},
%% collaborationPlotOptions    ={},
%% salary@prof                 =126600,
%% salary@groupLeader          =105000,
%% salary@postDoc              =90600,
%% salary@medDoc               =112200,
%% salary@PhD                  =83700,
%% salary@research             =69000,
%% salary@nonResearch          =61500,
%% salary@student              =1,
%% salary@assistant            =1,
%% animalHousing@mouse         =0.75,
%% animalHousing@mouseGnotobiotic=3.9,
%% animalHousing@rat           =1.4,
%% thumbindex                  =true,
%% thumbindex@pattern          =<int>,
%% thumbindex@orientation      =outwards, % or inwards
%% thumbindex@topmargin        =auto,
%% thumbindex@bottommargin     =auto,
%% emphasizeAuthors            =true,
%% emphasizeEntries            =false,
%% journalTitle                =journaltitle, % or shortjournal
%% biblatexstyleCV             =<nn>,
%% biblatexstyleFeatureCV      ={<nn>,<nn>},
%% biblatexstyleProposal       =<nn>,
%% biblatexstyleFeatureProposal={<nn>,<nn>},
%%%%%   color section   %%%%%
%% color@reference@boldAuthor =<nn>,
%% color@reference@PI         =black, % or current / a named color
%% color@reference@WP         =<nn>,
%% color@reference@Aim        =<nn>,
%% color@table@headingsBG      =<nn>,
%% color@table@headingsBGalt   =<nn>,
%% color@table@headingsFont    =<nn>,
%% color@table@rows            =<nn>,
%% color@table@lines           =<nn>,
%% color@table@outerLines      =<nn>,
%% color@table@noValue         =<nn>,
%% color@table@firstColumn     =<nn>,
%% color@table@link            =<nn>,
%% color@table@contFootHead    =<nn>,
%% color@table@caption         =<nn>,
%% color@gantt@frame           =<nn>,
%% color@gantt@default         =<nn>,
%% color@gantt@crosshatch      =<nn>,
%% color@gantt@important       =<nn>,
%% color@gantt@stripe-one      =<nn>,
%% color@gantt@stripe-two      =<nn>,
%% color@thumbindex@bg         =<nn>,
%% color@thumbindex@font       =<nn>,
%% color@tags@font             =<nn>,
%% color@tags@line             =<nn>,
%% color@font@alternative      =<nn>,
%% color@item@i                =<nn>,
%% }
%    \end{macrocode}
% \iffalse
%</custom>
% \fi
% \subsection{DFG salary and animal-housing defaults}
%
% The DFG specifies standardised all-in salary costs (\emph{Personalmittel})
% per position category. The salary defaults use the 2027 rates. These constants are
% used in the requested-funding staff tables to calculate yearly personnel
% costs from FTE counts.
%
% The values are updated annually and published by the DFG.  Their canonical
% defaults are keys in the |dfg/custom| key family.  Override them together
% with the other proposal settings in |dfg-customization.tex|:
% \begin{dispListing*}{title={Overriding salary and animal-housing rates}}
%   \changeSettings{
%     salary@postDoc      = 90000,
%     animalHousing@mouse = 0.80,
%   }
% \end{dispListing*}
%
% Source: \url{https://www.dfg.de/resource/blob/408716/60-12-2027-de.pdf}
% (DFG personnel rates for 2027, form 60.12, version 01/27).
%
% Use \cs{getValue} with the setting key, for example
% |\num{\getValue{animalHousing@mouse}}|, to read these rates in text.
% The expandable \cs{dfgSalaryProf}, \cs{dfgSalaryGroupLeader},
% \cs{dfgSalaryPostDoc}, \cs{dfgSalaryMedDoc}, \cs{dfgSalaryPhD},
% \cs{dfgSalaryResearch}, \cs{dfgSalaryNonResearch},
% \cs{dfgSalaryStudent}, \cs{dfgSalaryAssistant}, \cs{dfgMouseHousing},
% \cs{dfgMouseHousingGnotobiotic}, and \cs{dfgRatHousing} accessors remain
% available for compatibility.  They expand to the corresponding setting.
% \iffalse
%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
% \fi
% \subsection{Shared proposal and documentation metadata}
% The manual, local proposal, and CV use one fictional consortium: six active A projects,
% six active B projects, three Q projects, twelve PIs, and one former project.
% Person/project references are reciprocal; collaboration targets exist.
% The developer installer extracts these same records into local/metadata/.
%    \begin{macrocode}
%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{meta}{
  id                   = {crc}, %<--- id (do not change)
  name                 = {Mechanisms of Host--Microbiome Communication},
  nameAddon            = {From Molecular Interactions to Organ Function},
  number               = {9999},
  fundingPeriodNumeral = {3}, % 1|2|3
  ref-affiliation-id   = {aff1}, % or {aff1,aff2} for two applicants
  fundedSince          = {2019-07-01},
  fundingYears         = {2027|2,2028,2029,2030,2031|1},
  fundingYearsPrevious = {2022|2,2023,2024,2025,2026|1}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                 = {ins1},
  name               = {Institute of Microbial Systems Medicine},
  abbreviation       = {IMSM},
  ref-affiliation-id = {aff1}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                 = {ins2},
  name               = {Department of Translational Biosciences},
  abbreviation       = {DTB},
  ref-affiliation-id = {aff2}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{affiliation}{
  id            = {aff1},
  name          = {Example University},
  abbreviation  = {EU},
  addressStreet = {University Avenue 1},
  addressZIP    = {12345},
  location      = {Example City},
  country       = {Germany}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{affiliation}{
  id            = {aff2},
  name          = {Partner University},
  abbreviation  = {PU},
  addressStreet = {Research Road 2},
  addressZIP    = {54321},
  location      = {Partner City},
  country       = {Germany}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{person}{
  id                   = {per1},
  firstname            = {Kim},
  lastname             = {Sample},
  academicdegree       = {Prof. Dr. rer. nat.},
  period               = {1,2,3},
  role                 = {PI},
  gender               = {d},
  ref-institution-id   = {ins1,ins2},
  ref-project-id       = {A01,A02},
  name-alias           = {
    {Kim Sample},
    {Sample, Kim S.}
  },
  orcid                = {0000-0000-0000-0001},
  doctorateYear        = {2000},
  doctorate            = {Dr. rer. nat., Example University},
  degree-programme     = {Biology, Example University},
  position             = {prof-W3},
  positionText         = {Professor and Director},
  url                  = {https://www.example.org/kim-sample},
  phone                = {+49 000 100-1000},
  email                = {kim.sample@example.org},
  contract-information = {
    C1  = {no},
    C2  = {yes},
    C2a = {2028-12-31},
    C2b = {2029-01-03},
    C3  = {yes},
    C3a = {2054-03-10},
    C4  = {no},
    C4a = {DFG}
  }
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                   = {per2},
  period               = {2,3},
  firstname            = {Alex},
  lastname             = {Example},
  academicdegree       = {Prof. Dr. phil.},
  position             = {groupLeader},
  positionText         = {Research group leader},
  role                 = {PI,steering-committee-member},
  doctorateYear        = {1999},
  doctorate            = {Dr. phil., Partner University},
  degree-programme     = {Data Science, Partner University},
  gender               = {m},
  ref-institution-id   = {ins2},
  ref-project-id       = {A01,B01,Q01},
  orcid                = {0000-0000-0000-0002},
  phone                = {+49 000 200-2000},
  email                = {alex.example@example.org},
  contract-information = {
    C1  = {no},
    C2  = {no},
    C2a = {},
    C2b = {},
    C3  = {no},
    C3a = {},
    C4  = {yes},
    C4a = {BMFTR}
  }
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                   = {per3},
  period               = {2,3},
  firstname            = {Hansi},
  lastname             = {Meier},
  academicdegree       = {Dr. rer. nat.},
  position             = {postDoc},
  positionText         = {Senior research scientist},
  role                 = {PI,steering-committee-member},
  doctorateYear        = {1999},
  doctorate            = {Dr. rer. nat., Partner University},
  degree-programme     = {Microbiology, Partner University},
  gender               = {f},
  ref-institution-id   = {ins2},
  ref-project-id       = {B01,B03,Q03},
  orcid                = {0000-0000-0000-0003},
  phone                = {+49 000 200-3000},
  email                = {hansi.meier@example.org},
  contract-information = {
    C1  = {yes},
    C2  = {no},
    C2a = {},
    C2b = {},
    C3  = {no},
    C3a = {},
    C4  = {yes},
    C4a = {DFG}
  }
}
%</meta|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{person}{
  id                   = {per4},
  period               = {2,3},
  firstname            = {Kimmi},
  lastname             = {Miller},
  academicdegree       = {Prof. Dr. rer. nat.},
  position             = {prof-W2},
  positionText         = {Professor of Molecular Medicine},
  role                 = {PI},
  doctorateYear        = {1999},
  doctorate            = {Dr. rer. nat., Partner University},
  degree-programme     = {Molecular Medicine, Partner University},
  gender               = {f},
  ref-institution-id   = {ins2},
  ref-project-id       = {B02,B04},
  orcid                = {0000-0000-0000-0004},
  phone                = {+49 000 200-4000},
  email                = {kimmi.mueller@example.org},
  contract-information = {
    C1  = {yes},
    C2  = {no},
    C2a = {},
    C2b = {},
    C3  = {no},
    C3a = {},
    C4  = {yes},
    C4a = {DFG}
  }
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                   = {per5},
  period               = {3},
  firstname            = {Friedhelm},
  lastname             = {Redata},
  academicdegree       = {Prof. Dr.-Ing.},
  orcid                = {0000-0000-0000-0005},
  position             = {prof-W2},
  positionText         = {Professor of Research Training},
  role                 = {PI,steering-committee-member},
  doctorateYear        = {1998},
  doctorate            = {Dr.-Ing., Example University},
  degree-programme     = {Biomedical Engineering, Example University},
  gender               = {m},
  ref-institution-id   = {ins1},
  ref-project-id       = {B05,Q02},
  phone                = {+49 000 100-5000},
  email                = {friedhelm.redata@example.org},
  contract-information = {
    C1  = {yes},
    C2  = {yes},
    C2a = {2028-12-31},
    C2b = {2029-01-03},
    C3  = {yes},
    C3a = {2054-03-10},
    C4  = {no},
    C4a = {DFG}
  }
}
%</meta|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                 = {A01},
  project-area       = {A},
  number             = {A01},
  project-status     = {C},
  consider-for-lists = {true},
  reference-only     = {false},
  name               = {Microbial signalling across epithelial barriers},
  project-type       = {research},
  research-area      = {2.21-02},
  ref-person-id      = {per1,per2},
  collaboration      = {A02,A04,A06,B01,B03,B06,Q01},
  legal-issues       = {
      L1  = yes,
      L1a = no,
      L2  = no,
      L2a = no,
      L3  = no,
      L4  = no,
      L5  = no,
      L5a = no,
      L6  = no,
      L7  = no,
      L7a = no
    }
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                 = {A02},
  project-area       = {A},
  number             = {A02},
  project-status     = {N},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {research},
  name               = {Metabolic control of tissue-resident immunity},
  research-area      = {2.21-05},
  ref-person-id      = {per1,per6},
  collaboration      = {A01,A03,B02,Q02},
  legal-issues       = {
    L1  = no,
    L1a = no,
    L2  = yes,
    L2a = no,
    L3  = yes,
    L4  = yes,
    L5  = no,
    L5a = no,
    L6  = yes,
    L7  = no,
    L7a = yes
  }
}
%</meta|doc-table-a|doc-table-pis>

%<*meta>
\addEntry{project}{
  id                 = {A00},
  project-area       = {A},
  number             = {A00},
  project-status     = {E},
  consider-for-lists = {false},
  reference-only     = {true},
  project-type       = {research},
  name               = {Former project on microbial community dynamics},
  research-area      = {},
  ref-person-id      = {per4,per10},
  collaboration      = {}
}
%</meta>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                 = {B01},
  project-area       = {B},
  number             = {B01},
  project-status     = {C},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {research},
  research-area      = {2.21-03,2.21-05,2.22-15},
  name               = {Host defence during microbiome perturbation},
  ref-person-id      = {per3,per2},
  collaboration      = {A01,B02,B03,Q02},
  legal-issues       = {
    L1  = no,
    L1a = no,
    L2  = no,
    L2a = no,
    L3  = no,
    L4  = no,
    L5  = no,
    L5a = no,
    L6  = no,
    L7  = no,
    L7a = no
  }
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                 = {B02},
  project-area       = {B},
  number             = {B02},
  project-status     = {N},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {research},
  research-area      = {2.22-15},
  name               = {Molecular signatures of tissue regeneration},
  ref-person-id      = {per4,per10},
  collaboration      = {A02,B01,B04,Q01},
  legal-issues       = {
      L1  = yes,
      L1a = no,
      L2  = yes,
      L2a = yes,
      L3  = yes,
      L4  = yes,
      L5  = yes,
      L5a = no,
      L6  = yes,
      L7  = yes,
      L7a = no
    }
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-q|doc-table-pis>
\addEntry{project}{
  id                 = {Q01},
  project-area       = {Q},
  number             = {Q01},
  project-status     = {C},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {service},
  name               = {Integrated imaging and analysis services},
  research-area      = {2.21-02,2.22-15},
  ref-person-id      = {per2,per7},
  collaboration      = {A01,A03,A04,A06,B02,B03,B05},
  legal-issues       = {
    L1  = no,
    L1a = no,
    L2  = no,
    L2a = no,
    L3  = no,
    L4  = no,
    L5  = no,
    L5a = no,
    L6  = no,
    L7  = no,
    L7a = no
  }
}
%</meta|doc-table-q|doc-table-pis>

%<*meta|doc-table-q|doc-table-pis>
\addEntry{project}{
  id                 = {Q02},
  project-area       = {Q},
  number             = {Q02},
  project-status     = {C},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {mgk},
  name               = {Integrated Research Training Group},
  research-area      = {},
  ref-person-id      = {per5,per9},
  collaboration      = {A02,A05,B01,B04,B06}
}
%</meta|doc-table-q|doc-table-pis>

%<*meta|doc-table-q|doc-table-pis>
\addEntry{project}{
  id                 = {Q03},
  project-area       = {Q},
  number             = {Q03},
  project-status     = {C},
  consider-for-lists = {true},
  reference-only     = {false},
  project-type       = {admin},
  name               = {Central coordination and data stewardship},
  research-area      = {},
  ref-person-id      = {per3,per12},
  collaboration      = {A01,A02,A03,A04,A05,A06,B01,B02,B03,B04,B05,B06,Q01,Q02}
}
%</meta|doc-table-q|doc-table-pis>

%<*meta>
\addEntry{person}{
  id                 = {spokesperson},
  role               = {spokesperson,steering-committee-member},
  period             = {1,2,3},
  lastname           = {Sample},
  firstname          = {Morgan},
  academicdegree     = {Prof. Dr. med.},
  gender             = {f},
  position           = {prof-W3},
  positionText       = {CRC spokesperson and professor of systems medicine},
  doctorateYear      = {1998},
  doctorate          = {Dr. med., Example University},
  degree-programme   = {Medicine, Example University},
  ref-institution-id = {ins1},
  ref-affiliation-id = {aff1},
  orcid              = {0000-0000-0000-0006},
  phone              = {+49 000 100-6000},
  email              = {morgan.sample@example.org}
}
%</meta>

%<*meta>
\addEntry{person}{
  id                 = {man1},
  role               = {manager},
  period             = {2,3},
  firstname          = {Jamie},
  lastname           = {Coordinator},
  academicdegree     = {Dr. rer. nat.},
  gender             = {d},
  position           = {nonResearch},
  positionText       = {Scientific manager},
  doctorateYear      = {2012},
  doctorate          = {Dr. rer. nat., Partner University},
  degree-programme   = {Life Sciences, Partner University},
  ref-institution-id = {ins2},
  ref-affiliation-id = {aff2},
  orcid              = {0000-0000-0000-0007},
  phone              = {+49 000 200-7000},
  email              = {jamie.coordinator@example.org}
}
%</meta>

%<*meta>
\addEntry{person}{
  id                 = {rector},
  role               = {rector},
  period             = {3},
  lastname           = {Rector},
  firstname          = {Robin},
  academicdegree     = {Prof. Dr.},
  gender             = {d},
  position           = {prof},
  positionText       = {Rector of Example University},
  ref-affiliation-id = {aff1},
  phone              = {+49 000 100-8000},
  email              = {rector@example.org}
}
%</meta>

%<*meta>
\addEntry{person}{
  id                 = {rector2},
  role               = {rector},
  period             = {3},
  lastname           = {President},
  firstname          = {Casey},
  academicdegree     = {Prof. Dr.},
  gender             = {d},
  position           = {prof},
  positionText       = {President of Partner University},
  ref-affiliation-id = {aff2},
  phone              = {+49 000 200-8000},
  email              = {president@partner.example.org}
}
%</meta>

%<*meta|doc-table-a|doc-table-q|doc-table-pis>
\addEntry{affiliation}{
  id                  = {aff3},
  name                = {Northbridge University},
  abbreviation        = {NU},
  addressStreet       = {Science Avenue 3},
  addressZIP          = {34567},
  location            = {Northbridge},
  country             = {Germany}
}
%</meta|doc-table-a|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{affiliation}{
  id                  = {aff4},
  name                = {Westhaven Research Centre},
  abbreviation        = {WRC},
  addressStreet       = {Science Avenue 3},
  addressZIP          = {34567},
  location            = {Westhaven},
  country             = {Germany}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                  = {ins3},
  name                = {Centre for Computational Microbiology},
  abbreviation        = {CCM},
  ref-affiliation-id  = {aff3}
}
%</meta|doc-table-a|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                  = {ins4},
  name                = {Department of Experimental Immunology},
  abbreviation        = {DEI},
  ref-affiliation-id  = {aff3}
}
%</meta|doc-table-a|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                  = {ins5},
  name                = {Institute of Metabolic Medicine},
  abbreviation        = {IMM},
  ref-affiliation-id  = {aff4}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{institution}{
  id                  = {ins6},
  name                = {Centre for Clinical Translation},
  abbreviation        = {CCT},
  ref-affiliation-id  = {aff4}
}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{person}{
  id                  = {per6},
  orcid               = {0000-0000-0000-0016},
  firstname           = {Samira},
  lastname            = {Hartmann},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI,steering-committee-member},
  gender              = {f},
  ref-institution-id  = {ins3},
  ref-project-id      = {A02,A03},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0006},
  email               = {samira@example.org}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                  = {per7},
  firstname           = {Noah},
  lastname            = {Lindberg},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {m},
  ref-institution-id  = {ins3,ins4},
  ref-project-id      = {A03,A04,Q01},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0007},
  email               = {noah@example.org}
}
%</meta|doc-table-a|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{person}{
  id                  = {per8},
  firstname           = {Alexis-Marie},
  lastname            = {Winters-Scholz},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {d},
  ref-institution-id  = {ins4},
  ref-project-id      = {A04,A05},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0008},
  email               = {alexis-marie@example.org}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                  = {per9},
  firstname           = {Leonie},
  lastname            = {Navarro},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {f},
  ref-institution-id  = {ins5},
  ref-project-id      = {A05,A06,Q02},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0009},
  email               = {leonie@example.org}
}
%</meta|doc-table-a|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-b|doc-table-pis>
\addEntry{person}{
  id                  = {per10},
  firstname           = {Daniel},
  lastname            = {Okafor},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {m},
  ref-institution-id  = {ins5,ins6},
  ref-project-id      = {A06,B02,B06},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0010},
  email               = {daniel@example.org}
}
%</meta|doc-table-a|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{person}{
  id                  = {per11},
  firstname           = {Mira},
  lastname            = {Sato},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {f},
  ref-institution-id  = {ins6},
  ref-project-id      = {B03,B04},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0011},
  email               = {mira@example.org}
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-q|doc-table-pis>
\addEntry{person}{
  id                  = {per12},
  firstname           = {Robin},
  lastname            = {Keller},
  academicdegree      = {Prof. Dr. rer. nat.},
  period              = {3},
  role                = {PI},
  gender              = {d},
  ref-institution-id  = {ins1,ins6},
  ref-project-id      = {B05,B06,Q03},
  position            = {prof-W2},
  positionText        = {Professor of Systems Medicine},
  doctorateYear       = {2010},
  doctorate           = {Dr. rer. nat., Example University},
  degree-programme    = {Life Sciences, Example University},
  phone               = {+49 000 300-0012},
  email               = {robin@example.org}
}
%</meta|doc-table-b|doc-table-q|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                  = {A03},
  project-area        = {A},
  number              = {A03},
  project-status      = {C},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Microbiome-derived metabolites and immune memory},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per6,per7},
  collaboration       = {A02,A04,B03,Q01}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                  = {A04},
  project-area        = {A},
  number              = {A04},
  project-status      = {N},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Spatial niches of host--microbe interactions},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per7,per8},
  collaboration       = {A01,A03,A05,B04,Q01}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                  = {A05},
  project-area        = {A},
  number              = {A05},
  project-status      = {C},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Dietary control of microbial community dynamics},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per8,per9},
  collaboration       = {A04,A06,B05,Q02}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-a|doc-table-pis>
\addEntry{project}{
  id                  = {A06},
  project-area        = {A},
  number              = {A06},
  project-status      = {N},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Modelling microbial resilience and recovery},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per9,per10},
  collaboration       = {A01,A05,B06,Q01}
}
%</meta|doc-table-a|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                  = {B03},
  project-area        = {B},
  number              = {B03},
  project-status      = {C},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Immune circuits linking intestine and liver},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per3,per11},
  collaboration       = {A01,A03,B01,B05,Q01}
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                  = {B04},
  project-area        = {B},
  number              = {B04},
  project-status      = {N},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Cross-organ consequences of inflammatory stress},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per4,per11},
  collaboration       = {A04,B02,B06,Q02}
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                  = {B05},
  project-area        = {B},
  number              = {B05},
  project-status      = {C},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Patient-derived models of metabolic disease},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per5,per12},
  collaboration       = {A05,B03,B06,Q01}
}
%</meta|doc-table-b|doc-table-pis>

%<*meta|doc-table-b|doc-table-pis>
\addEntry{project}{
  id                  = {B06},
  project-area        = {B},
  number              = {B06},
  project-status      = {N},
  consider-for-lists  = {true},
  reference-only      = {false},
  name                = {Translating microbial biomarkers into interventions},
  project-type        = {research},
  research-area       = {2.21-02},
  ref-person-id       = {per10,per12},
  collaboration       = {A01,A06,B04,B05,Q02}
}
%</meta|doc-table-b|doc-table-pis>

%<*!example-data>
%<*meta>
\addEntry[funding]{RequestedFunding}{
  ref-project-id={A02}, funding-type={staff}, category={PhD}, percentage={65},
  quantity={year1=1,year2=1,year3=1,year4=1,year5=1}
}
%</meta>
%<*meta>
\addEntry[funding]{RequestedFunding}{
  ref-project-id={A02}, funding-type={costs}, category={consumables},
  sum={year1=1000,year2=2000,year3=2000,year4=2000,year5=1000}
}
%</meta>
%<*meta>
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id={A02}, ref-person-id={per6},
  funding-status={existing}, staff-type={research},
  field-of-research={Microbiology}, commitment={8}, funding-source={State funds},
  description={Supervises experiments and analysis.}
}
%</meta>
%</!example-data>
%    \end{macrocode}
% \iffalse

%<doc-table-a>\printTable{{Projects}{A}{Microbiota and metabolic pathways}}
%<doc-table-b>\printTable{{Projects}{B}{Immune mechanisms and clinical translation}}
%<doc-table-q>\printTable{{Projects}{Q}{Shared services, training, and coordination}}
%<doc-table-pis>\printTable{ProjectLeaders}
%</meta|doc-table-a|doc-table-b|doc-table-q|doc-table-pis>
%<*meta-cv>
% \fi
%    \begin{macrocode}

%% Fictional CV fixtures shared by the local CV and the embedded manual PDF.

%% Each PI demonstrates three career stages and all five optional categories.


%% Kim Sample: Microbial systems medicine.

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {mandatory},
  periodStart        = {2013},
  periodEnd          = {},
  positionText       = {Professor and Director},
  position           = {Current appointment},
  description        = {Leads the mechanistic microbiome programme and
    coordinates the shared experimental strategy.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {mandatory},
  periodStart        = {2005},
  periodEnd          = {2012},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on microbial metabolites
    and epithelial signalling and developed collaborative
    methods.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {mandatory},
  periodStart        = {2001},
  periodEnd          = {2004},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    microbial metabolites and epithelial signalling.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {supplement},
  description        = {Research focus: microbial metabolites and epithelial
    signalling. A visiting fellowship at the Example
    Centre for Interdisciplinary Research supported new
    collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {activities},
  description        = {Chairs the consortium steering committee and an
    annual host--microbiome symposium. Contributes to
    peer review and open teaching materials.}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {supervision},
  description        = {Mentors laboratory and clinical doctoral researchers
    through joint thesis committees. Regular progress
    reviews include research integrity and publication
    planning.}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {distinction},
  description        = {2024: Example Academy fellowship for
    interdisciplinary microbiome research. 2021:
    consortium mentoring recognition for support of
    early-career researchers.}
}

\addEntry[cv]{cv-per1}{
  ref-person-id      = {per1},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Alex Example: Computational systems biology.

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {mandatory},
  periodStart        = {2016},
  periodEnd          = {},
  positionText       = {Research group leader},
  position           = {Current appointment},
  description        = {Develops statistical models linking molecular
    measurements with clinical phenotypes.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {mandatory},
  periodStart        = {2004},
  periodEnd          = {2015},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on multimodal data
    integration and reproducible analysis and developed
    collaborative methods.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {mandatory},
  periodStart        = {2000},
  periodEnd          = {2003},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    multimodal data integration and reproducible
    analysis.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {supplement},
  description        = {Research focus: multimodal data integration and
    reproducible analysis. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {activities},
  description        = {Leads the data standards working group and maintains
    the consortium code-review programme. Contributes to
    peer review and open teaching materials.}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {supervision},
  description        = {Supervises doctoral projects in statistics and
    biology, with paired computational and experimental
    mentors. Regular progress reviews include research
    integrity and publication planning.}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {distinction},
  description        = {2024: Partner University award for open research
    software. 2021: consortium mentoring recognition for
    support of early-career researchers.}
}

\addEntry[cv]{cv-per2}{
  ref-person-id      = {per2},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Hansi Meier: Microbiology and host defence.

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Senior research scientist},
  position           = {Current appointment},
  description        = {Coordinates experimental infection models and
    validation of immune mechanisms.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {mandatory},
  periodStart        = {2004},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on microbial sensing and
    innate immune memory and developed collaborative
    methods.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {mandatory},
  periodStart        = {2000},
  periodEnd          = {2003},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    microbial sensing and innate immune memory.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {supplement},
  description        = {Research focus: microbial sensing and innate immune
    memory. A visiting fellowship at the Example Centre
    for Interdisciplinary Research supported new
    collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {activities},
  description        = {Organises a practical course on host defence and
    serves on the laboratory methods committee.
    Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {supervision},
  description        = {Mentors early-career scientists in experimental
    design, biosafety and reproducible laboratory
    practice. Regular progress reviews include research
    integrity and publication planning.}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {distinction},
  description        = {2024: Example Society prize for translational
    infection research. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per3}{
  ref-person-id      = {per3},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Kimmi Miller: Molecular tissue regeneration.

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {},
  positionText       = {Professor of Molecular Medicine},
  position           = {Current appointment},
  description        = {Connects organoid perturbation experiments with
    molecular measurements of tissue recovery.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {mandatory},
  periodStart        = {2004},
  periodEnd          = {2014},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on epithelial repair and
    tissue regeneration and developed collaborative
    methods.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {mandatory},
  periodStart        = {2000},
  periodEnd          = {2003},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    epithelial repair and tissue regeneration.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {supplement},
  description        = {Research focus: epithelial repair and tissue
    regeneration. A visiting fellowship at the Example
    Centre for Interdisciplinary Research supported new
    collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {activities},
  description        = {Coordinates the organoid methods network and an
    interdisciplinary regeneration seminar. Contributes
    to peer review and open teaching materials.}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {supervision},
  description        = {Supervises doctoral researchers in molecular medicine
    and provides mentoring for clinician scientists.
    Regular progress reviews include research integrity
    and publication planning.}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {distinction},
  description        = {2024: Partner University award for collaborative
    tissue research. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per4}{
  ref-person-id      = {per4},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Friedhelm Redata: Biomedical research training.

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {mandatory},
  periodStart        = {2014},
  periodEnd          = {},
  positionText       = {Professor of Research Training},
  position           = {Current appointment},
  description        = {Directs the graduate programme and evaluates
    interdisciplinary training formats.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {mandatory},
  periodStart        = {2003},
  periodEnd          = {2013},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on structured doctoral
    training and research integrity and developed
    collaborative methods.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {mandatory},
  periodStart        = {1999},
  periodEnd          = {2002},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    structured doctoral training and research integrity.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {supplement},
  description        = {Research focus: structured doctoral training and
    research integrity. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {activities},
  description        = {Chairs the graduate curriculum committee and
    coordinates the annual doctoral retreat. Contributes
    to peer review and open teaching materials.}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {supervision},
  description        = {Supports thesis committees, individual development
    plans and peer mentoring across all research areas.
    Regular progress reviews include research integrity
    and publication planning.}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {distinction},
  description        = {2024: Example University prize for doctoral
    education. 2021: consortium mentoring recognition for
    support of early-career researchers.}
}

\addEntry[cv]{cv-per5}{
  ref-person-id      = {per5},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Samira Hartmann: Microbial systems medicine.

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Combines microbial genetics with functional assays of
    host metabolic responses.},
  ref-institution-id = {ins3}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on microbial metabolic
    pathways and immune adaptation and developed
    collaborative methods.},
  ref-institution-id = {ins3}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    microbial metabolic pathways and immune adaptation.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {supplement},
  description        = {Research focus: microbial metabolic pathways and
    immune adaptation. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {activities},
  description        = {Coordinates the pathway-discovery workshop and joint
    protocol reviews across the consortium. Contributes
    to peer review and open teaching materials.}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {supervision},
  description        = {Supervises paired microbiology and immunology
    projects, including laboratory exchanges for doctoral
    researchers. Regular progress reviews include
    research integrity and publication planning.}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {distinction},
  description        = {2024: Example Foundation award for microbial systems
    research. 2021: consortium mentoring recognition for
    support of early-career researchers.}
}

\addEntry[cv]{cv-per6}{
  ref-person-id      = {per6},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Noah Lindberg: Spatial immunology.

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Links spatial profiling to microscopy and
    quantitative descriptions of immune-cell
    neighbourhoods.},
  ref-institution-id = {ins3}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on spatial immune niches
    and quantitative imaging and developed collaborative
    methods.},
  ref-institution-id = {ins3}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    spatial immune niches and quantitative imaging.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {supplement},
  description        = {Research focus: spatial immune niches and
    quantitative imaging. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {activities},
  description        = {Leads the imaging quality-control forum and teaches
    the annual spatial-analysis course. Contributes to
    peer review and open teaching materials.}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {supervision},
  description        = {Mentors doctoral researchers in image analysis, with
    shared supervision across experimental and
    computational groups. Regular progress reviews
    include research integrity and publication planning.}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {distinction},
  description        = {2024: Example Imaging Society early-career research
    prize. 2021: consortium mentoring recognition for
    support of early-career researchers.}
}

\addEntry[cv]{cv-per7}{
  ref-person-id      = {per7},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Alexis-Marie Winters-Scholz: Host--microbe interactions.

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Develops experimental models of diet-dependent
    microbial colonisation and mucosal responses.},
  ref-institution-id = {ins4}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on dietary perturbations
    and mucosal microbial communities and developed
    collaborative methods.},
  ref-institution-id = {ins4}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    dietary perturbations and mucosal microbial
    communities.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {supplement},
  description        = {Research focus: dietary perturbations and mucosal
    microbial communities. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {activities},
  description        = {Coordinates the experimental-models working group and
    a public seminar series on microbiome science.
    Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {supervision},
  description        = {Supervises doctoral projects in microbial ecology and
    supports exchange placements between partner
    laboratories. Regular progress reviews include
    research integrity and publication planning.}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {distinction},
  description        = {2024: Example University award for experimental
    microbiome research. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per8}{
  ref-person-id      = {per8},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Leonie Navarro: Metabolic systems biology.

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Integrates dietary interventions with metabolic
    profiling and predictive modelling.},
  ref-institution-id = {ins5}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on nutrient sensing and
    predictive metabolic models and developed
    collaborative methods.},
  ref-institution-id = {ins5}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    nutrient sensing and predictive metabolic models.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {supplement},
  description        = {Research focus: nutrient sensing and predictive
    metabolic models. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {activities},
  description        = {Organises the metabolic modelling summer school and
    contributes to graduate admissions panels.
    Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {supervision},
  description        = {Mentors doctoral researchers in model validation,
    interdisciplinary communication and career planning.
    Regular progress reviews include research integrity
    and publication planning.}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {distinction},
  description        = {2024: Example Society distinction for integrative
    metabolic research. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per9}{
  ref-person-id      = {per9},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Daniel Okafor: Translational systems medicine.

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Connects patient-derived measurements with biomarker
    validation and experimental tissue models.},
  ref-institution-id = {ins5}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on microbial biomarkers
    and clinical tissue responses and developed
    collaborative methods.},
  ref-institution-id = {ins5}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    microbial biomarkers and clinical tissue responses.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {supplement},
  description        = {Research focus: microbial biomarkers and clinical
    tissue responses. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {activities},
  description        = {Coordinates the translational data-analysis workshop
    and the clinical assay harmonisation group.
    Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {supervision},
  description        = {Supervises clinician scientists and laboratory
    researchers in joint translational thesis projects.
    Regular progress reviews include research integrity
    and publication planning.}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {distinction},
  description        = {2024: Westhaven Research Centre translational science
    award. 2021: consortium mentoring recognition for
    support of early-career researchers.}
}

\addEntry[cv]{cv-per10}{
  ref-person-id      = {per10},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Mira Sato: Cross-organ immunology.

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Coordinates tissue sampling and comparative analyses
    of inflammatory responses across organs.},
  ref-institution-id = {ins6}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on inflammatory circuits
    between intestine and liver and developed
    collaborative methods.},
  ref-institution-id = {ins6}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    inflammatory circuits between intestine and liver.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {supplement},
  description        = {Research focus: inflammatory circuits between
    intestine and liver. A visiting fellowship at the
    Example Centre for Interdisciplinary Research
    supported new collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {activities},
  description        = {Leads the clinical sample-coordination group and
    teaches a course on cross-organ immunology.
    Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {supervision},
  description        = {Mentors doctoral researchers in clinical cohort
    design, sample governance and mechanistic validation.
    Regular progress reviews include research integrity
    and publication planning.}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {distinction},
  description        = {2024: Example Clinical Research Society award for
    collaborative immunology. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per11}{
  ref-person-id      = {per11},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}


%% Robin Keller: Integrative systems medicine.

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {mandatory},
  periodStart        = {2018},
  periodEnd          = {},
  positionText       = {Professor of Systems Medicine},
  position           = {Current appointment},
  description        = {Combines patient-derived models with biomarker
    translation and stewardship of shared research data.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {mandatory},
  periodStart        = {2015},
  periodEnd          = {2017},
  positionText       = {Independent research group leader},
  position           = {Independent research},
  description        = {Established a research team on patient-derived models
    and biomarker translation and developed collaborative
    methods.},
  ref-institution-id = {ins1}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {mandatory},
  periodStart        = {2011},
  periodEnd          = {2014},
  positionText       = {Postdoctoral researcher},
  position           = {Postdoctoral training},
  description        = {Developed experimental and analytical approaches to
    patient-derived models and biomarker translation.},
  ref-institution-id = {ins2}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {supplement},
  description        = {Research focus: patient-derived models and biomarker
    translation. A visiting fellowship at the Example
    Centre for Interdisciplinary Research supported new
    collaborations and exchange of methods.}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {activities},
  description        = {Chairs the consortium reproducibility forum and
    coordinates workshops on reusable clinical research
    data. Contributes to peer review and open teaching
    materials.}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {supervision},
  description        = {Co-supervises doctoral researchers across clinical
    and computational projects, with individual
    career-development plans. Regular progress reviews
    include research integrity and publication planning.}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {distinction},
  description        = {2024: Example University award for reproducible
    translational medicine. 2021: consortium mentoring
    recognition for support of early-career researchers.}
}

\addEntry[cv]{cv-per12}{
  ref-person-id      = {per12},
  cv-type            = {other},
  description        = {Makes analysis protocols and training resources
    available for reuse. No commercial interests related
    to the proposed research. All career details and
    distinctions in this CV are fictional examples.}
}

% \iffalse
%</meta-cv>
%<*meta-tables>
% \fi




%    \end{macrocode}
% \iffalse
%</meta-tables>
%<*00>
% \fi
% \subsection{Title Page (Proposal specific)}
%    \begin{macrocode}
\pdfbookmark{Titlepage}{titlepage}
\begin{titlepage}
  \def\tmpLocalDB{meta}%
  \vspace*{4em}
  \begin{center}%
  	\large
	\crc\,\dfgCRCNumber\\
    \vspace*{1.5em}
    {\Large\bfseries \dfgCRCName}\\
    \dfgCRCNameAddon\\
	\vspace*{2em}
  	\crcLogo[height=2cm]\\
    \vspace*{2em}
    \theCRCCoordinatingAffiliation\\
    \dfgApplicantAffiliationsTF
      { }
      {\theCRCOtherApplicantAffiliations\\}
	\vspace*{2em}
    {\Large\bfseries Funding Proposal}\\[1em]
	for the \dfgFundingPeriodText\space Funding Period\\
	\dfgFundingYear{1}--%
	\dfgFundingYear{2}--%
	\dfgFundingYear{3}--%
	\dfgFundingYear{4}--%
	\dfgFundingYear{5}
    \dfgIfCVT{\par\textcolor{tableHeadingsFont}{Appendix: Research profiles}}
    \dfgIfFinalF{{\par\large\InfoTeX}}
  	% \iftoggle{crc@chapter}{%
  	%   \par\vspace*{5em}\par
  	%   \begin{crcTitleBox}
  	%       \centering\Huge%
  	%       {\color{rwthRed}%
  	%           \ttfamily%
  	%           content/\textbf{\dfgChapter}.tex}\\
  	%       \Large\dfgCompiled
  	%   \end{crcTitleBox}%
  	% }{}
  	\vfill
  	%
  	%  \crcLogo[height=1cm]
  	\hfill%
  	\affiliationLogo[height=1cm]
  \end{center}
  \clearpage
  \checkFile{content/00_titlepage-colophon}
\end{titlepage}
\begin{titlepage}
  % setting the default database for general information
  \def\tmpLocalDB{meta}
  \begin{center}
	Proposal for the \dfgFundingPeriodText\space Funding Period of\\
	\crc\,\dfgCRCNumber

	\enquote{\bfseries\dfgCRCName: \dfgCRCNameAddon}
  \end{center}
  funded since
  \begin{center}
  	\getEntry{crc}{fundedSince}
  \end{center}
  for
  \begin{center}
	\dfgFundingYear{1}--%
	\dfgFundingYear{2}--%
	\dfgFundingYear{3}--%
	\dfgFundingYear{4}--%
	\dfgFundingYear{5}
  \end{center}
  Coordinating university:
  \begin{center}
	\theCRCCoordinatingAffiliation
  \end{center}
  \dfgApplicantAffiliationsTF
    { }
    {
      Other applicant
      \dfgOtherApplicantAffiliationsTF{university}{universities}:
      \begin{center}
        \theCRCOtherApplicantAffiliations
      \end{center}
    }
  \Hrule[
  	thickness = 1.5pt,
  	above     = 2em,
  	below     = 2em]

  \begin{minipage}[t]{.49\linewidth}
  	\textbf{Spokesperson of\\ the \crc:}\\[1\baselineskip]
    \getPIsWithRole[raster columns=1]{spokesperson}
  \end{minipage}\hfill%
  \begin{minipage}[t]{.49\linewidth}
  	\textbf{Management or office of\\the \crc:}\\[1\baselineskip]
    \getPIsWithRole[raster columns=1]{manager}
  \end{minipage}
  \vfill
  \printSignaturesWithRole{spokesperson}{(Spokesperson~of~\crc)}
  \printSignaturesWithRole{rector}
    {(Rector,~chancellor,~or~president~of~
      \getEntry[affiliation]{\theAffiliationOfRoleID}{name})}
\end{titlepage}
\bgroup
\let\cleardoublepage\clearpage% to get the TOC on two pages (left/right)
\pdfbookmark{\contentsname}{Contents}
\tableofcontents
\dfgIfCVT{\KOMAoptions{open=left}}
\egroup
%    \end{macrocode}
% \iffalse
%</00>
%<*01>
% \fi
% \subsection{Content Files (Proposal specific)}
%    \begin{macrocode}
\newrefsection
\chapter{General information}
\printThumbIndex{1}
\section{Key data}
\subsection{Governing bodies of the \crc}
% \subsubsection{Spokesperson of the \thisCRC}
% \getPIsWithRole{spokesperson}

\subsubsection*{Steering Committee of the \thisCRC}

\getPIsWithRole{steering-committee-member}

For the third funding period, the steering committee includes representatives
of both research areas and the Integrated Research Training Group.  The
spokesperson and committee members are elected by the CRC general assembly in
accordance with the bylaws.  The composition is reviewed annually with regard
to scientific breadth, career stage, and equitable participation.

\subsection{Project leaders}
\printTable{ProjectLeaders}

\subsection{Participating institutions}
\printList{ParticipatingInstitutions}

\clearpage
\subsection{Project groups and projects}
\printTable{{Projects}{A}{Microbiota and metabolic pathways}}
\printTable{{Projects}{B}{Immunological circuits}}
\printTable{{Projects}{Q}{Central projects}}
N: New projects started in the \dfgFundingPeriodText\space funding period; %
E: Ending projects not continued in the \dfgFundingPeriodText\space funding
period; %
Research areas according to the German Research Foundation (2024--2028)%
\footnote{\raggedright\url{https://www.dfg.de/resource/blob/331950/fachsystematik-2024-2028-en.pdf}}:
\printList{ResearchAreasFromProjects}


% For the following sections we want to have them
% numbered until 'subsubsection'
\setcounter{secnumdepth}{4}

\clearpage
\section{Research profile of the \crc} %1.2
\begin{dfgSummaryBox}[title={Spotlights: Moving Forward}]
  \item Resolve causal mechanisms of communication between microbial
    communities, epithelial barriers, and tissue-resident immune cells.
  \item Combine spatial profiling, experimental perturbation, and predictive
    modelling across the participating projects.
  \item Translate shared methods into reproducible services, interoperable
    data, and structured training for researchers in early career phases.
\end{dfgSummaryBox}

%% \FloatBarrier % no images in references list.
\defbibheading{frame-references}[References]{\subsection*{#1}}
\printFrameBibliography[heading=frame-references]


\subsection{Summary of the research programme}%1.2.1

The CRC investigates how microbial and host-derived signals cross epithelial
barriers and influence organ function.  During the previous funding periods,
the consortium established shared cohorts, experimental models, imaging
workflows, and computational methods.  The new programme links these resources
in hypothesis-driven projects that test causality across molecular, cellular,
and tissue scales.

\subsection{Detailed presentation of the research programme}%1.2.2

Project area A examines microbial metabolites and barrier signalling, whereas
project area B focuses on immune circuits and tissue responses.  The central
projects provide imaging, analysis, training, coordination, and research-data
services.  Common samples, harmonised metadata, and reciprocal collaborations
connect the individual work programmes and enable validation across models and
participating institutions.

\subsection{Positioning of the \crc within its general research area}%1.2.3

The programme combines mechanistic microbiome research with systems immunology
and organ physiology.  Its distinguishing feature is the coordinated
validation of candidate signals from discovery cohorts through controlled
experimental systems to tissue-level readouts, supported by shared technology
and transparent data-management standards.

\subsection{National and international cooperation and networking} %1.2.4

The CRC maintains method-oriented collaborations with national infrastructure
networks and international partner laboratories.  Cooperation agreements
define sample and data transfer, authorship, quality assurance, and access to
specialised technologies.  Visiting-researcher and exchange formats are
coordinated through the Integrated Research Training Group.

\section{Research profile of the applicant
  \dfgApplicantAffiliationsTF{university}{universities}} %1.3
\subsection{Strategy and planning}%1.3.1

Example University has identified host--microbiome research as a strategic
priority and supports the CRC through permanent scientific positions, shared
technical platforms, research-data infrastructure, and central administration.
Annual reviews align institutional investments with the scientific milestones
of the consortium.

\subsection{Staff situation} % 1.3.2

The participating units contribute principal investigators, research staff,
technical personnel, data stewards, and administrative support.  Recruitment
planning prioritises timely appointments, transparent selection procedures,
career development, and continuity of essential technical expertise.

\subsection{Research infrastructure} % 1.3.3

The CRC has access to advanced microscopy, flow cytometry, sequencing,
gnotobiotic facilities, secure data storage, and high-performance computing.
Central projects coordinate access, training, maintenance, and quality control
so that methods and datasets remain comparable across all projects.

\section{Support structures} % 1.4
\subsection{Researchers in early career phases} % 1.4.1

Researchers in early career phases receive structured scientific and career
mentoring, transferable-skills training, annual progress reviews, and access to
methods courses and exchange opportunities organised by \getProject{Q02}.

\addEntry[person]{EarlyCareerResearcher}{
  ref-project-id= {A01},
  id              = {KM},
  lastname      = {Sample},
  firstname     = {Kimmi},
  financed-by   = {DFG},
  category      = {PhD},
  topic         = {Epithelial sensing of microbial metabolites},
  periodStart   = {2025-04},
  periodEnd     = {2029-06}
}
\addEntry[person]{EarlyCareerResearcher}{
  ref-project-id= {B01},
  id              = {KiM},
  lastname      = {Wunderlich},
  firstname     = {Kimmi},
  financed-by   = {DFG},
  category      = {MD},
  topic         = {Immune signatures during microbiome perturbation},
  periodStart   = {2025-04},
  periodEnd     = {2029-06}
}

%% \getEntry[EarlyCareerResearcher]{KM}{lastname}
\printTable{EarlyCareerResearchers}

\subsection{Promotion of equity and diversity} % 1.4.2

Recruitment, supervision, and committee appointments follow transparent
criteria and are monitored by career stage and gender.  Flexible working
arrangements, mentoring, accessibility measures, and targeted career support
are available through the central coordination project.

\addEntry[GenderEquality]{GenderEqualityStaff}{
  position                             = {PhD}, %PhD|PostDoc
  previous-objective-percentage-female = {40},
  status-quo-number-female             = {20},
  status-quo-percentage-female         = {14},
  future-objective-percentage-female   = {40}
}

\addEntry[GenderEquality]{GenderEqualityStaff}{
  position                             = {postDoc}, %PhD|PostDoc
  previous-objective-percentage-female = {22},
  status-quo-number-female             = {34},
  status-quo-percentage-female         = {44},
  future-objective-percentage-female   = {34}
}
% -----

\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                             = {postDoc}, %PhD|PostDoc
  previous-objective-percentage-female = {22},
  future-objective-percentage-female   = {34}
}
\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                             = {groupLeader}, %PhD|PostDoc
  previous-objective-percentage-female = {22},
  future-objective-percentage-female   = {34}
}


\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                             = {prof-W2}, %PhD|PostDoc
  previous-objective-percentage-female = {22},
  future-objective-percentage-female   = {34}
}

\addEntry[GenderEquality]{GenderEqualityProjectLeaders}{
  position                             = {prof-W3}, %PhD|PostDoc
  previous-objective-percentage-female = {22},
  future-objective-percentage-female   = {34}
}

\clearpage
\subsubsection*{A. Objectives for the participation of female researchers}
\printTable{GenderEqualityStaff}

\subsubsection*{B. Project leaders}
\printTable{GenderEqualityProjectLeaders}

\subsection{Knowledge transfer and science communication} % 1.4.3

The CRC communicates results through open research resources, public lectures,
school and patient-group activities, and dialogue formats with clinical and
societal stakeholders.  Transfer opportunities are assessed early, with clear
procedures for intellectual property, responsible communication, and reusable
research outputs.

\section{Risks in international cooperation} %1.5

International partnerships are reviewed for legal, ethical, export-control,
data-protection, and research-security risks.  Written agreements specify
permitted data and material transfers, access rights, publication principles,
and responsibilities.  The participating universities reassess collaborations
when partners, technologies, or regulatory conditions change.

\section{Considerations on aspects of ecological sustainability in project
  planning and implementation} %1.6

The CRC considers ecological sustainability when planning experiments,
procurement, travel, computing, sample storage, and shared infrastructure.
Projects consolidate measurement campaigns, share equipment and reference
materials, select proportionate data-retention and computing strategies, and
prefer lower-emission travel or remote participation where this is compatible
with the scientific objective.  The steering committee reviews these measures
alongside scientific feasibility, research quality, legal obligations, animal
welfare, and the responsible use of resources.


% ok, let’s go back to the default (from base.tex)
\setcounter{secnumdepth}{2}

\endrefsection
\resetboldnames

%    \end{macrocode}
% \iffalse
%</01>
%<*02>
% \fi
%    \begin{macrocode}
\chapter{Existing funds and requested funds} %2
\printThumbIndex{2}
\section{Existing funds} % 2.1
\subsection{Overview of existing funds for direct costs} %2.1.1

\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year        = 1,
  applicant   = 1000,
  participant = 2000,
  other-funds = 3000
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year        = 2,
  applicant   = 1000,
  participant = 2000,
  other-funds = 3000
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year        = 3,
  applicant   = 1000,
  participant = 2000,
  other-funds = 3000
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year        = 4,
  applicant   = 1000,
  participant = 2000,
  other-funds = 3000
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year        = 5,
  applicant   = 1000,
  participant = 2000,
  other-funds = 3000
}


% New-period values are declared once in the individual project files below.
% The class restores those later declarations from the preceding LaTeX run's
% auxiliary files into the overview database used here.
\printTable{ExistingFundsDirectCosts}


\subsection{Overview of existing staff} % 2.1.2
% Data are reused from project-level RequestedFundingStaff declarations with
% funding-status={existing}.  No separate overview database is required.
\printTable{OverviewExistingStaff}

\subsection{List of existing instrumentation} % 2.1.2
\addEntry[instrumentation]{existingInstrumentation}{
  ref-project-id = {A01},
  quantity       = {1},
  instrument     = {Confocal laser-scanning microscope},
  company        = {Example Instruments GmbH},
  year           = {2025},
  cost           = {250},
  financed-by    = {DFG}
}
\addEntry[instrumentation]{existingInstrumentation}{
  ref-project-id = {A01,B01},
  quantity       = {2},
  instrument     = {Anaerobic workstation},
  company        = {Laboratory Systems AG},
  year           = {2024},
  cost           = {80},
  financed-by    = {Institutional funds}
}

\printTable{ExistingInstrumentation}

\section{Previous and requested funds} %2.2
\subsection{Overview} % 2.2.1

\addEntry[funding]{PreviousRequestedFunding}{
  year            = 1,
  staff           = 1000,
  costs           = 2000,
  instrumentation = 3000,
  fellowships     = 4000,
  globalfunds     = 5000
}
\addEntry[funding]{PreviousRequestedFunding}{
  year            = 2,
  staff           = 1000,
  costs           = 2000,
  instrumentation = 3000,
  fellowships     = 4000,
  globalfunds     = 5000
}
\addEntry[funding]{PreviousRequestedFunding}{
  year            = 3,
  staff           = 1000,
  costs           = 2000,
  instrumentation = 3000,
  fellowships     = 4000,
  globalfunds     = 5000
}
\addEntry[funding]{PreviousRequestedFunding}{
  year            = 4,
  staff           = 1000,
  costs           = 2000,
  instrumentation = 3000,
  fellowships     = 4000,
  globalfunds     = 5000
}
\addEntry[funding]{PreviousRequestedFunding}{
  year            = 5,
  staff           = 1000,
  costs           = 2000,
  instrumentation = 3000,
  fellowships     = 4000,
  globalfunds     = 5000
}


\printTable{PreviousAndCurrentRequestedFunding}

\subsection{Overview of funds requested for staff} % 2.2.2
% data comes from all the 
% \addEntry[funding]{RequestedFunding}{
%    ...
%   category     = {....},
%   funding-type = {staff},
%    ...
% }
\printTable{OverviewOfFundsRequestedForStaff}

\subsection{Overview of funds requested for instrumentation} % 2.2.3

% data comes from all the 
% \addEntry[funding]{RequestedFunding}{
%    ...
%   funding-type = {instrumentation},
%    ...
% }
\printTable{OverviewFundsRequestedInstrumentation}


\section{Upkeep of laboratory animals} % 2.3
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id   = {A01},
  species          = {mouse},
  quantity         = {1212},
  weeks-kept       = {43},
  purchasing-costs = {23},
  requested-funds  = {100},
  existing-funds   = {232}
}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id   = {A01,A02},
  species          = {rat},
  quantity         = {2},
  weeks-kept       = {3},
  purchasing-costs = {23.54},
  requested-funds  = {1230},
  existing-funds   = {232}
}
\addEntry{UpkeepLaboratoryAnimals}{
  ref-project-id   = {B01},
  species          = {mouse-gnotobiotic},
  quantity         = {3},
  weeks-kept       = {43},
  purchasing-costs = {23},
  requested-funds  = {201},
  existing-funds   = {132}
}
\printTable{UpkeepLaboratoryAnimals}

%    \end{macrocode}
% \iffalse
%</02>
%<*03-project-a01>
% \fi
% \subsection{Complete continuing-project example}
% This file demonstrates the complete heading and command structure for a
% continuing research project (|project-status=C|).
%    \begin{macrocode}
\printProjectHead{A01}

\section{Summary}
\label{A01:summary}

Summarise the continuing project's central question, progress, planned work,
methods, and contribution to the Collaborative Research Centre.

\section{Project progress to date}
\label{A01:project-progress-to-date}

\subsection{Report and current state of research}%
\label{A01:report-and-current-state-of-research}

Report the work and results from the previous funding periods, relate them to
the current state of research, and explain how they motivate the new plan.

\FloatBarrier

\projectPublicationsHeading

%% Add all project-specific publication keys before printing the bibliography.
\projectNocite{FAIR2016}
\printProjectBibliography[heading=none]

\section{Project plan}
\label{A01:project-plan}

\begin{aims}
  \addAim{A} Define the underlying mechanism.
  \addAim{B} Validate the mechanism experimentally.
  \addAim{C} Integrate the findings across the CRC.
\end{aims}

Refer to one aim as \getAim{A}, or to several as \getAim{A,B,C}.

\begin{workpackages}
  \addWP{wp1}{
    name={Mechanistic analysis},
    description={Define the underlying mechanism},
    periodStart={1},
    periodEnd={8},
    style={default},
  }

  Describe the work, methods, milestones, risks, and expected results of
  \getWP{wp1}.

  \begin{workpackages}
    %% Sub-workpackages deliberately have no name key: their authored text is
    %% the visible list item, while description is used only in the Gantt chart.
    \addWP{wp1a}{
      description={Establish the experimental system},
      periodStart={1},
      periodEnd={4},
      style={alternative},
    }
    Establish and validate the experimental system.

    \addWP{wp1b}{
      description={Perform the mechanistic experiments},
      periodStart={3},
      periodEnd={8},
      style={important},
    }
    Perform the mechanistic experiments and define decision points.
  \end{workpackages}

  \addWP{wp2}{
    name={Experimental validation},
    description={Validate and integrate the mechanism},
    periodStart={7},
    periodEnd={16},
    style={striped},
  }

  Describe the validation strategy, expected results, and contingency plan of
  \getWP{wp2}.
\end{workpackages}

\printPlot{{Gantt}{A01}}

\FloatBarrier

\section{Relevance of sex, gender and/or diversity in the research
  project}
\label{A01:relevance-of-sex-gender-and-diversity}

Explain whether and how sex, gender, and diversity affect the research
questions, design, analysis, and interpretation.

\section{Role within the Collaborative Research
  Centre}
\label{A01:role-within-the-collaborative-research-centre}

Describe the project's contribution to the CRC and its principal
collaborations.

%% The default full-width arc layout shows nodes and area rules without edges.
\printPlot{{collaboration}{A01}}
%% To draw the connecting arcs, replace the call above with:
%% \printPlot[arcs=true,caption={Optional additional caption text.}]
%%   {{collaboration}{A01}}
%% Use [layout=heatmap] for the alternative heatmap layout.


\section{Differentiation from other funded
  projects}
\label{A01:differentiation-from-other-funded-projects}

Explain how this project differs from, and complements, other funded work of
the project leaders.

\section{Project funding}
\label{A01:project-funding}

\subsection{Previous funding}

Funding of this project within the Collaborative Research Centre started
in July 2019.  Preparatory work was funded by Example University's seed-fund
programme from January 2018 to June 2019 (reference number EU-EXAMPLE-01).

\subsection{Requested funding}

%% Without sum, the class calculates from salary@prof, percentage, and
%% quantity, using half the annual amount in year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A01},
  funding-type   = {staff},
  category       = {prof},
  percentage     = {100},
  quantity = {
    year1 = {2},
    year2 = {2},
    year3 = {2},
    year4 = {2},
    year5 = {2}
  }
}

%% With sum, these concrete yearly amounts override the central salary rate;
%% year1 and year5 below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A01},
  funding-type   = {staff},
  category       = {PhD},
  percentage     = {65},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {26500},
    year2 = {53000},
    year3 = {53000},
    year4 = {53000},
    year5 = {26500}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A01},
  funding-type       = {costs}, %staff, costs, ...
  category   = {Laboratory consumables},
  sum = {
  		year1      =  {2112},
  		year2      =  {67},
  		year3      =  {9843},
  		year4      =  {2375},
  		year5      =  {983}
  	}}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A01},
  funding-type       = {costs}, %staff, costs, ...
  category   = {Sequencing and data analysis},
  sum = {
  		year1      =  {1000},
  		year2      =  {2000},
  		year3      =  {3000},
  		year4      =  {4000},
  		year5      =  {5000}
  	}}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A01},
  funding-type       = {instrumentation}, %staff, costs, ...
  category           = {Live-cell imaging system},
  sum = {
  		year1      =  {1000},
  		year2      =  {2000},
  		year3      =  {3000},
  		year4      =  {4000},
  		year5      =  {5000}
  	}}

\printTable{{RequestedFunding}{A01}}





\subsubsection{Requested funding for staff for the new funding period}
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {A01},
  funding-status     = {existing},
  staff-type         = {research},
  ref-person-id      = {per1},
  field-of-research  = {Microbiology and systems medicine},
  commitment         = {8},
  category           = {prof},
  funding-source     = {State funds},
  description        = {Leads the experimental programme and supervises the
    research staff assigned to the project.}
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id    = {A01},
  funding-status    = {existing},
  staff-type        = {nonResearch},
  firstname         = {Alex},
  lastname          = {Example},
  academic-degree   = {M.Sc.},
  positionText      = {Technical assistant},
  field-of-research = {Laboratory management},
  ref-institution-id = {ins1},
  commitment        = {20},
  category          = {nonResearch},
  funding-source    = {Core support},
  description       = {Maintains shared laboratory workflows and coordinates
    sample logistics.}
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {A01},
  funding-status     = {requested},
  staff-type         = {research},
  firstname          = {Researcher},
  lastname           = {TBA},
  academic-degree    = {Dr. rer. nat.},
  positionText       = {Postdoctoral researcher},
  field-of-research  = {Host--microbiome interactions},
  ref-institution-id = {ins2},
  category           = {postDoc},
  description        = {Performs the planned mechanistic experiments and
    integrates molecular and clinical datasets.}
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id    = {A01},
  funding-status    = {requested},
  staff-type        = {nonResearch},
  firstname         = {Taylor},
  lastname          = {Demo},
  academic-degree   = {B.Sc.},
  positionText      = {Research assistant},
  field-of-research = {Biobanking and data curation},
  ref-institution-id = {ins2},
  category          = {assistant},
  description       = {Supports biobanking, quality control, and structured
    curation of the project datasets.}
}

\printTable{{RequestedFundingStaff}{A01}}

\subsubsection{Requested funding for direct costs for the new funding
  period}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id = {A01},
  ref-affiliation-id = {aff2},
  financed-by = {Partner University core support},
  sum = {
		year1      =  {1200},
		year2      =  {500},
		year3      =  {21100},
		year4      =  {5600},
		year5      =  {3400}
	}}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id = {A01},
  ref-affiliation-id = {aff1},
  financed-by = {Example University core support},
  sum = {
		year1      =  {11100},
		year2      =  {53800},
		year3      =  {21100},
		year4      =  {600},
		year5      =  {38300}
	}}


\printTable{{RequestedAndExistingFundingDirectCosts}{A01}}

\begin{FundingDirectCostsTable}[Text]
  Laboratory consumables and antibodies & EUR & 15000 \\
  Single-cell sequencing and spatial profiling & EUR & 12000 \\
  Research data storage and analysis & EUR & 3000 \\
\end{FundingDirectCostsTable}


\subsubsection{Requested funding for instrumentation for the new funding
  period}


\begin{FundingDirectCostsTable}[Text]
  Automated live-cell imaging system & EUR & 95000 \\
  Environmental control module & EUR & 18000 \\
  Analysis workstation and software & EUR & 7000 \\
\end{FundingDirectCostsTable}


\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-a01>
%<*03-project-a02>
% \fi
% \subsection{Complete new-project example}
% This file demonstrates the complete heading and command structure for a new
% research project (|project-status=N|).  Its scientific-background section is
% intentionally named differently from the progress section of a continuing
% project.
%    \begin{macrocode}
\printProjectHead{A02}

\section{Summary}
\label{A02:summary}

Summarise the new project's central hypothesis, methods, expected results, and
contribution to the Collaborative Research Centre.

\section{Research rationale}
\label{A02:research-rationale}

\subsection{Current state of research and preliminary work}
\label{A02:current-state-of-research-and-preliminary-work}

Describe the relevant state of research, preliminary work, open questions,
and the scientific rationale for the proposed project.

\FloatBarrier

\projectPublicationsHeading
\projectNocite{FAIR2016}
\printProjectBibliography[heading=none]

\section{Project plan}
\label{A02:project-plan}

\begin{aims}
  \addAim{1} Establish the experimental and analytical framework.
  \addAim{2} Test the central hypothesis and validate the findings.
\end{aims}

\begin{workpackages}
  \addWP{wp1}{
    name={Framework and pilot experiments},
    description={Establish the framework and complete pilot experiments},
    periodStart={1},
    periodEnd={7},
    style={default},
  }

  Describe the methods, milestones, expected results, and risks of
  \getWP{wp1} and its contribution to \getAim{1}.

  \addWP{wp2}{
    name={Hypothesis testing and validation},
    description={Test the hypothesis and validate the findings},
    periodStart={6},
    periodEnd={16},
    style={important},
  }

  Describe the validation strategy and contingency plan for \getWP{wp2} and
  \getAim{2}.
\end{workpackages}

\printPlot{{Gantt}{A02}}

\FloatBarrier

\section{Relevance of sex, gender and/or diversity in the research project}
\label{A02:relevance-of-sex-gender-and-diversity}

Explain whether and how sex, gender, and diversity affect the research
questions, design, analysis, and interpretation.

\section{Role within the Collaborative Research Centre}
\label{A02:role-within-the-collaborative-research-centre}

Describe the project's contribution to the CRC and its principal
collaborations.

\printPlot{{ProjectCollaboration}{A02}}

\section{Differentiation from other funded projects of the project leader(s)}
\label{A02:differentiation-from-other-funded-projects}

Explain how this new project differs from, and complements, other funded work
of the project leaders.

\section{Project funding}
\label{A02:project-funding}

\subsection{Previous funding}

State that this is a new CRC project and list related previous funding of the
project leaders where applicable.

\subsection{Requested funding}

%% Automatic staff-cost example: sum is intentionally omitted; the class
%% halves the calculated amounts in year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A02},
  funding-type   = {staff},
  category       = {postDoc},
  percentage     = {100},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  }
}

%% Explicit staff-cost example: sum overrides the central salary calculation;
%% the concrete year1 and year5 amounts below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A02},
  funding-type   = {staff},
  category       = {PhD},
  percentage     = {65},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {26500},
    year2 = {53000},
    year3 = {53000},
    year4 = {53000},
    year5 = {26500}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A02},
  funding-type   = {costs},
  category       = {Consumables},
  sum = {
    year1 = {2000},
    year2 = {2000},
    year3 = {2000},
    year4 = {2000},
    year5 = {2000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {A02},
  funding-type   = {instrumentation},
  category       = {Specialised instrument},
  sum = {
    year1 = {5000},
    year2 = {0},
    year3 = {0},
    year4 = {0},
    year5 = {0}
  }
}

\printTable{{RequestedFunding}{A02}}

\subsubsection{Requested funding for staff}

%% When no person database row is needed, all display data can be supplied
%% directly.  Leave academic-degree empty when it is unknown.
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {A02},
  funding-status     = {requested},
  staff-type         = {research},
  firstname          = {Researcher},
  lastname           = {TBA},
  academic-degree    = {},
  positionText       = {Postdoctoral researcher},
  field-of-research  = {Experimental systems medicine},
  ref-institution-id = {ins1},
  category           = {postDoc},
  description        = {Establishes the new experimental platform, performs
    the mechanistic studies, and analyses the resulting datasets.}
}

\printTable{{RequestedFundingStaff}{A02}}

Provide the scientific and organisational justification for every requested
staff position.

\subsubsection{Requested funding of direct costs}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {A02},
  ref-affiliation-id = {aff1},
  financed-by        = {State funds},
  sum = {
    year1 = {500},
    year2 = {500},
    year3 = {500},
    year4 = {500},
    year5 = {500}
  }
}

\printTable{{RequestedAndExistingFundingDirectCosts}{A02}}

\begin{FundingDirectCostsTable}[Text]
  Consumables for pilot experiments & EUR & 10000 \\
  External data analysis & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsubsection{Requested funding for instrumentation}

\begin{FundingDirectCostsTable}[Text]
  Specialised instrument including installation & EUR & 5000 \\
\end{FundingDirectCostsTable}

\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-a02>
%<*03-project-b01>
% \fi
% \subsection{Second continuing-project example}
% This compact but complete file demonstrates another continuing research
% project and keeps the funding-category examples used by the dummy proposal.
%    \begin{macrocode}
\printProjectHead{B01}

\section{Summary}
\label{B01:summary}

Summarise the continuing project and the work proposed for the new funding
period.

\section{Project progress to date}
\label{B01:project-progress-to-date}

\subsection{Report and current state of research}
\label{B01:report-and-current-state-of-research}

Report the previous work, published and unpublished results, and the current
state of research.

\FloatBarrier

\projectPublicationsHeading
\projectNocite{FAIR2016}
\printProjectBibliography[heading=none]

\section{Project plan}
\label{B01:project-plan}

\begin{aims}
  \addAim{1} Complete the mechanistic analysis.
  \addAim{2} Validate the findings with CRC partners.
\end{aims}

\begin{workpackages}
  \addWP{wp1}{
    name={Mechanistic analysis},
    description={Complete the mechanistic analysis},
    periodStart={1},
    periodEnd={10},
    style={default},
  }
  Describe \getWP{wp1}, including methods, milestones, and risks.

  \addWP{wp2}{
    name={Collaborative validation},
    description={Validate the findings with CRC partners},
    periodStart={8},
    periodEnd={16},
    style={alternative},
  }
  Describe \getWP{wp2} and its links to \getAim{2}.
\end{workpackages}

\printPlot{{Gantt}{B01}}

\FloatBarrier

\section{Relevance of sex, gender and/or diversity in the research project}
\label{B01:relevance-of-sex-gender-and-diversity}

Explain the relevance of sex, gender, and diversity, or justify why they do
not affect this project's research questions and methods.

\section{Role within the Collaborative Research Centre}
\label{B01:role-within-the-collaborative-research-centre}

Describe the role of the project and its reciprocal collaborations.

\printPlot{{ProjectCollaboration}{B01}}

\section{Differentiation from other funded projects}
\label{B01:differentiation-from-other-funded-projects}

Differentiate the project from other funded work of its project leaders.

\section{Project funding}
\label{B01:project-funding}

\subsection{Previous funding}

State when CRC funding began and list other relevant previous funding.

\subsection{Requested funding}

%% Automatic staff-cost example: sum is intentionally omitted; the class
%% halves the calculated amounts in year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {B01},
  funding-type   = {staff},
  category       = {groupLeader},
  percentage     = {100},
  quantity = {
    year1 = {2},
    year2 = {2},
    year3 = {2},
    year4 = {2},
    year5 = {2}
  }
}

%% Explicit staff-cost example: sum overrides the central salary calculation;
%% the concrete year1 and year5 amounts below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {B01},
  funding-type   = {staff},
  category       = {postDoc},
  percentage     = {100},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {45000},
    year2 = {90000},
    year3 = {90000},
    year4 = {90000},
    year5 = {45000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {B01},
  funding-type       = {globalfunds}, %staff, costs, ...
  category   = {Project-wide data stewardship},
  sum = {
    year1 = {1000},
    year2 = {2000},
    year3 = {3000},
    year4 = {4000},
    year5 = {5000}
  }
}

\printTable{{RequestedFunding}{B01}}

\subsubsection{Requested funding for staff for the new funding period}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {B01},
  funding-status     = {requested},
  staff-type         = {research},
  firstname          = {Researcher},
  lastname           = {TBA},
  academic-degree    = {},
  positionText       = {Research group leader},
  field-of-research  = {Translational microbiology},
  ref-institution-id = {ins2},
  category           = {groupLeader},
  description        = {Coordinates the experimental programme and the
    collaborative validation studies.}
}

\printTable{{RequestedFundingStaff}{B01}}

\subsubsection{Requested funding for direct costs for the new funding period}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {B01},
  ref-affiliation-id = {aff2},
  financed-by        = {Institutional funds},
  sum = {
    year1 = {1000},
    year2 = {1000},
    year3 = {1000},
    year4 = {1000},
    year5 = {1000}
  }
}

\printTable{{RequestedAndExistingFundingDirectCosts}{B01}}

\begin{FundingDirectCostsTable}[Text]
  Experimental consumables & EUR & 10000 \\
  Data-processing services & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsubsection{Requested funding for instrumentation for the new funding
  period}

\begin{FundingDirectCostsTable}[Text]
  No instrumentation requested & EUR & 0 \\
\end{FundingDirectCostsTable}

\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-b01>
%<*03-project-ending>
% \fi
% \subsection{Complete ending-project example}
% Ending projects use a deliberately shorter DFG structure: after the general
% information printed by \cs{printProjectHead}, they report project history,
% published results, and closing funding information.  They do not contain a
% new project plan or a request for another funding period.
%    \begin{macrocode}
\printProjectHead{A00}

\section{Project history}
\label{A00:project-history}

\subsection{Report}
\label{A00:report}

\begin{projectReport}
Describe the complete funding history, objectives, methods, results, and
contribution of the ending project.  Citations used only in the report are
printed automatically at the end of this environment.  This dummy citation
also demonstrates the exclusion of a result listed below
\autocite{FAIR2016}.
\end{projectReport}

\subsection{Published project results}
\label{A00:published-project-results}

%% Replace the example key with the project's results.  Use the literal value
%% none only when a category genuinely produced no result; leaving a value
%% empty keeps a visible drafting instruction.
\printProjectResults{
  quality-assured = {FAIR2016},
  other           = none,
  patents         = none
}

\section{Funding}
\label{A00:funding}

Funding of this project within the Collaborative Research Centre started in
April 2018.  The project will be completed by the end of the current funding
period.  Replace these dates and, where applicable, add previous funding under
another DFG programme and its reference number.

\subsection{Project staff in the ending funding period}
\label{A00:project-staff-in-the-ending-funding-period}

%% For an ending project, funding-status=requested is printed as
%% ``Staff funded with approved grant money'', matching the DFG form.
\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {A00},
  funding-status     = {existing},
  staff-type         = {research},
  ref-person-id      = {per4},
  commitment         = {8},
  funding-source     = {State funds},
  field-of-research  = {Molecular tissue regeneration},
  description        = {Led the project, supervised the experimental work,
    and integrated its results across the CRC throughout the ending funding
    period.}
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {A00},
  funding-status     = {requested},
  staff-type         = {research},
  firstname          = {Researcher},
  lastname           = {TBA},
  academic-degree    = {},
  positionText       = {Postdoctoral researcher},
  field-of-research  = {Regenerative cell biology},
  ref-institution-id = {ins2},
  category           = {postDoc},
  description        = {Completed the final validation experiments and data
    publication from April 2025 until the end of the current funding period.}
}

\printTable{{RequestedFundingStaff}{A00}}

\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-ending>
%<*03-project-q01>
% \fi
% \subsection{Complete continuing service-project example}
% Service projects use the continuing-project headings while the prose and work
% packages focus on services, resources, access rules, and collaborative use.
%    \begin{macrocode}

\printProjectHead{Q01}

\section{Summary}
\label{Q01:summary}

Summarise the service portfolio, its scientific purpose, its users, and the
developments planned for the new funding period.

\section{Project progress to date}
\label{Q01:project-progress-to-date}

\subsection{Report and current state of research}
\label{Q01:report-and-current-state-of-research}

Report completed and ongoing services, usage by CRC projects, technical
developments, quality assurance, and relevant service-project research.

\FloatBarrier

\projectPublicationsHeading
\projectNocite{FAIR2016}
\printProjectBibliography[heading=none]

\section{Project plan}
\label{Q01:project-plan}

\begin{aims}
  \addAim{1} Maintain and quality-assure the core service portfolio.
  \addAim{2} Extend the portfolio for new collaborative requirements.
\end{aims}

\begin{workpackages}
  \addWP{wp1}{
    name={Core service provision},
    description={Provide and quality-assure core services},
    periodStart={1},
    periodEnd={16},
    style={default},
  }
  Describe access, sample or data handover, turnaround, quality assurance,
  responsibilities, and capacity for \getWP{wp1}.

  \addWP{wp2}{
    name={Service development},
    description={Develop and validate new service modules},
    periodStart={3},
    periodEnd={14},
    style={alternative},
  }
  Describe development milestones and the projects participating in
  \getWP{wp2}.
\end{workpackages}

\printPlot{{Gantt}{Q01}}

\FloatBarrier

\section{Relevance of sex, gender and/or diversity in the research project}
\label{Q01:relevance-of-sex-gender-and-diversity}

Explain relevance for the service methods and the studies supported by them.

\section{Role within the Collaborative Research Centre}
\label{Q01:role-within-the-collaborative-research-centre}

Describe which projects use the services and how priorities, access, and
collaborations are coordinated.

\printPlot{{ProjectCollaboration}{Q01}}

\section{Differentiation from other funded projects}
\label{Q01:differentiation-from-other-funded-projects}

Differentiate the CRC service from existing institutional infrastructure and
other funded service activities.

\section{Project funding}
\label{Q01:project-funding}

\subsection{Previous funding}

State when the service project began and describe relevant previous funding.

\subsection{Requested funding}

%% Automatic staff-cost example: sum is intentionally omitted; the class
%% halves the calculated amounts in year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q01},
  funding-type   = {staff},
  category       = {nonResearch},
  percentage     = {65},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  }
}

%% Explicit staff-cost example: sum overrides the central salary calculation;
%% the concrete year1 and year5 amounts below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q01},
  funding-type   = {staff},
  category       = {assistant},
  percentage     = {50},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {9000},
    year2 = {18000},
    year3 = {18000},
    year4 = {18000},
    year5 = {9000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q01},
  funding-type       = {costs}, %staff, costs, ...
  category   = {Invitation},
  sum = {
    year1 = {1000},
    year2 = {2000},
    year3 = {3000},
    year4 = {4000},
    year5 = {5000}
  }
}

\printTable{{RequestedFunding}{Q01}}

\subsubsection{Requested funding for staff for the new funding period}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {Q01},
  funding-status     = {requested},
  staff-type         = {nonResearch},
  firstname          = {Service},
  lastname           = {Specialist},
  academic-degree    = {},
  positionText       = {Technical specialist},
  field-of-research  = {Core-facility services},
  ref-institution-id = {ins1},
  category           = {nonResearch},
  description        = {Operates the service platform, performs quality
    control, and supports participating projects.}
}

\printTable{{RequestedFundingStaff}{Q01}}

\subsubsection{Requested funding for direct costs for the new funding period}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {Q01},
  ref-affiliation-id = {aff1},
  financed-by        = {Core-facility funds},
  sum = {
    year1 = {1000},
    year2 = {1000},
    year3 = {1000},
    year4 = {1000},
    year5 = {1000}
  }
}

\printTable{{RequestedAndExistingFundingDirectCosts}{Q01}}

\begin{FundingDirectCostsTable}[Text]
  Service-specific consumables & EUR & 10000 \\
  Maintenance and quality assurance & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsubsection{Requested funding for instrumentation for the new funding
  period}

\begin{FundingDirectCostsTable}[Text]
  Service-platform upgrade & EUR & 5000 \\
\end{FundingDirectCostsTable}

\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-q01>
%<*03-project-q02>
% \fi
% \subsection{Complete integrated research training group example}
% The MGK/IRTG project type has its own required narrative and funding
% headings.  This file mirrors that structure instead of pretending it is a
% conventional research project.
%    \begin{macrocode}
\printProjectHead{Q02}

\section{Summary}
\label{Q02:summary}

Summarise the objectives, development, and added value of the Integrated
Research Training Group.

\section{Tabular report}
\label{Q02:tabular-report}

Provide the required tabular report of all researchers funded by the
Integrated Research Training Group to date.

\section{Qualification programme}
\label{Q02:qualification-programme}

Describe the qualification programme, workshops, courses, retreats, career
development measures, and other training activities.

\section{Management and supervision}
\label{Q02:management-and-supervision}

Describe management responsibilities, recruitment, supervision arrangements,
mentoring, conflict-resolution processes, and quality assurance.

\section{Environment of the Integrated Research Training Group}
\label{Q02:environment-of-the-integrated-research-training-group}

Describe the scientific, institutional, interdisciplinary, and international
training environment.

\section{Interim assessment and outlook}
\label{Q02:interim-assessment-and-outlook}

Assess progress during the current funding period and describe priorities and
measurable objectives for the next funding period.

\section{Project funding}
\label{Q02:project-funding}

\subsection{Previous funding}

The Integrated Research Training Group has been funded within the
Collaborative Research Centre since April 2018.  Replace this date and add any
relevant funding under another programme.

%% Declare all monetary rows before the existing-funds overview: that table
%% compares existing direct-cost resources with the requested direct costs.
%% Automatic staff-cost example: sum is intentionally omitted; the class
%% halves the calculated amounts in year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q02},
  funding-type   = {staff},
  category       = {PhD},
  percentage     = {65},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  }
}

%% Explicit staff-cost example: sum overrides the central salary calculation;
%% the concrete year1 and year5 amounts below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q02},
  funding-type   = {staff},
  category       = {nonResearch},
  percentage     = {50},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {15000},
    year2 = {30000},
    year3 = {30000},
    year4 = {30000},
    year5 = {15000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q02},
  funding-type   = {costs},
  category       = {Qualification programme},
  sum = {
    year1 = {2000},
    year2 = {2000},
    year3 = {2000},
    year4 = {2000},
    year5 = {2000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q02},
  funding-type   = {fellowships},
  category       = {Short-term fellowships},
  sum = {
    year1 = {1000},
    year2 = {1000},
    year3 = {1000},
    year4 = {1000},
    year5 = {1000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q02},
  funding-type   = {globalfunds},
  category       = {Training and networking},
  sum = {
    year1 = {3000},
    year2 = {3000},
    year3 = {3000},
    year4 = {3000},
    year5 = {3000}
  }
}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {Q02},
  ref-affiliation-id = {aff2},
  financed-by        = {Graduate-school funds},
  sum = {
    year1 = {1000},
    year2 = {1000},
    year3 = {1000},
    year4 = {1000},
    year5 = {1000}
  }
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {Q02},
  funding-status     = {existing},
  staff-type         = {nonResearch},
  firstname          = {Taylor},
  lastname           = {Trainer},
  academic-degree    = {},
  positionText       = {Training coordinator},
  field-of-research  = {Structured doctoral training},
  ref-institution-id = {ins2},
  commitment         = {20},
  funding-source     = {Partner University core funds},
  description        = {Coordinates recruitment, course administration,
    progress monitoring, mentoring, and quality assurance for the
    qualification programme.}
}

\subsection{Existing funds for the new funding period}

Describe the coordination, training, staff, and direct-cost resources made
available to the Integrated Research Training Group by the participating
institutions.

\subsubsection*{Existing staff}

\printTable{{RequestedFundingStaff}{Q02}}

\printTable{{RequestedAndExistingFundingDirectCosts}{Q02}}

\subsection{Requested funding}

\printTable{{RequestedFunding}{Q02}}

\subsection{Requested funding for staff}

\begin{FundingDirectCostsTable}[Text]
  Doctoral-researcher position: interdisciplinary research and participation
    in the complete qualification programme & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsection{Requested funding for direct costs}

\begin{FundingDirectCostsTable}[Text]
  Workshops and transferable-skills courses & EUR & 10000 \\
  Visiting researchers and networking & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsection{Requested funding for fellowships}

\begin{FundingDirectCostsTable}[Text]
  Short-term research fellowships: state the type of fellowship, average
    number of fellows, average duration, monthly allowance per person, and
    justification & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsection{Requested global funds}

\begin{FundingDirectCostsTable}[Text]
  Training and networking measures: explain the purpose, allocation rules,
    selection process, and administration & EUR & 15000 \\
\end{FundingDirectCostsTable}

\printProjectTail
%    \end{macrocode}
% \iffalse
%</03-project-q02>
%<*03-project-q03>
% \fi
% \subsection{Complete central administrative-project example}
% The central administrative project has a dedicated DFG structure.  It does
% not reuse the summary, research-progress, publication, project-plan, or
% instrumentation headings of a continuing research project.
%    \begin{macrocode}
\printProjectHead{Q03}

\section{Documentation of the central activities of the Collaborative
  Research Centre}
\label{Q03:documentation-of-central-activities}

Document governance and decision-making, scientific coordination, reporting,
internal communication, data stewardship, publication support, equal-
opportunity measures, early-career support, outreach, and the interfaces with
all applicant and participating institutions.  Distinguish CRC-specific tasks
from permanent institutional duties and state responsibilities, workflows,
results from the current period, and priorities for the new funding period.

\section{Project funding}
\label{Q03:project-funding}

%% The existing-funds overview includes the requested direct-cost total, so
%% all monetary records are declared before either table is printed.
%% Automatic staff-cost example: sum is intentionally omitted.  The class
%% applies the half-year factor to year1 and year5.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q03},
  funding-type   = {staff},
  category       = {nonResearch},
  percentage     = {100},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  }
}

%% Explicit staff-cost example: the stated sums override the salary settings;
%% year1 and year5 below already represent half-years.
\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q03},
  funding-type   = {staff},
  category       = {assistant},
  percentage     = {50},
  quantity = {
    year1 = {1},
    year2 = {1},
    year3 = {1},
    year4 = {1},
    year5 = {1}
  },
  sum = {
    year1 = {12500},
    year2 = {25000},
    year3 = {25000},
    year4 = {25000},
    year5 = {12500}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q03},
  funding-type   = {costs},
  category       = {Central coordination and communication},
  sum = {
    year1 = {2000},
    year2 = {2000},
    year3 = {2000},
    year4 = {2000},
    year5 = {2000}
  }
}

\addEntry[funding]{RequestedFunding}{
  ref-project-id = {Q03},
  funding-type   = {globalfunds},
  category       = {Central measures},
  sum = {
    year1 = {2000},
    year2 = {2000},
    year3 = {2000},
    year4 = {2000},
    year5 = {2000}
  }
}

\addEntry[staff]{RequestedFundingStaff}{
  ref-project-id     = {Q03},
  funding-status     = {existing},
  staff-type         = {nonResearch},
  ref-person-id      = {man1},
  field-of-research  = {Research management},
  commitment         = {20},
  funding-source     = {Partner University core funds},
  description        = {Coordinates governance, reporting, internal
    communication, central measures, and interfaces with applicant and
    participating institutions.}
}

\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {Q03},
  ref-affiliation-id = {aff1},
  financed-by        = {Central university funds},
  sum = {
    year1 = {1000},
    year2 = {1000},
    year3 = {1000},
    year4 = {1000},
    year5 = {1000}
  }
}

\subsection{Existing funds for the new funding period}

Describe the central staff, facilities, and direct-cost resources contributed
by the applicant and participating institutions.

\subsubsection*{Existing staff}

\printTable{{RequestedFundingStaff}{Q03}}

\printTable{{RequestedAndExistingFundingDirectCosts}{Q03}}

\subsection{Requested funding for the new funding period}

\printTable{{RequestedFunding}{Q03}}

\subsection{Requested funding for staff}

\begin{FundingDirectCostsTable}[Text]
  Scientific coordination: justify the category, percentage, period, and
    CRC-specific responsibilities & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsection{Requested funding for direct costs}

\begin{FundingDirectCostsTable}[Text]
  Governance meetings and scientific exchange & EUR & 10000 \\
  Communication and outreach & EUR & 5000 \\
\end{FundingDirectCostsTable}

\subsection{Requested global funds}

\begin{FundingDirectCostsTable}[Text]
  Central measures: explain the purpose, allocation rules, selection process,
    and administration & EUR & 10000 \\
\end{FundingDirectCostsTable}

\printProjectTail

%    \end{macrocode}
% \iffalse
%</03-project-q03>
%<*04>
% \fi
%    \begin{macrocode}
\chapter{Bylaws of the Collaborative Research Centre} %4
\printThumbIndex{4}
\cohead{Bylaws of the \crc}%
\cehead{Bylaws of the \crc}%

\begin{bylaws}
  \item Name, coordinating
    \dfgApplicantAffiliationsTF{university}{universities}, and purpose of the \crc
  \begin{bylaws}
	\item The \crc (CRC) \enquote{\dfgCRCName\space --\space\dfgCRCNameAddon}
      is a legally dependent institution of \theCRCaffiliation.

    \item The \crc conducts interrelated research on microbial signalling,
      epithelial barriers, immune regulation, and organ function.  It is
      divided into research project areas and central projects.

    \item The \crc promotes interaction with other research institutions,
      supports researchers in early career phases, and fosters responsible
      international cooperation, equity, and equal opportunity.
  \end{bylaws}

  \item Membership and governing bodies
  \begin{bylaws}
    \item Members are the project leaders and persons appointed to central
      scientific or administrative responsibilities by the general assembly.
    \item The governing bodies are the general assembly, the spokesperson, and
      the steering committee.  The general assembly elects the spokesperson
      and steering committee for the applicable funding period.
    \item The steering committee prepares strategic and budgetary decisions,
      monitors milestones, and reports to the general assembly at least once
      per year.
  \end{bylaws}

  \item Decisions and allocation of shared resources
  \begin{bylaws}
    \item Decisions are normally taken by simple majority of members present;
      changes to these bylaws require a two-thirds majority.
    \item Shared funds and infrastructure are allocated through documented,
      transparent procedures based on scientific need, feasibility, and equal
      access across participating projects.
    \item Members disclose conflicts of interest and do not participate in the
      corresponding deliberation or decision.
  \end{bylaws}

  \item Research integrity, equity, and conflict resolution
  \begin{bylaws}
    \item All members follow the applicable rules of good research practice,
      data protection, animal welfare, research ethics, and occupational safety.
    \item The CRC implements equal-opportunity and accessibility measures and
      monitors participation in recruitment, training, and governance.
    \item Concerns may be raised confidentially with the spokesperson, the CRC
      management, or the competent independent offices of the participating
      institutions.
  \end{bylaws}

  \item Research-data governance
  \begin{bylaws}
    \item Projects document data, code, samples, access rights, retention, and
      publication in project-specific data-management plans.
    \item Central data stewardship defines common metadata and quality
      standards, manages controlled access, and supports publication according
      to the FAIR principles and applicable legal requirements.
  \end{bylaws}
\end{bylaws}
%    \end{macrocode}
% \iffalse
%</04>
%<*05>
% \fi
%    \begin{macrocode}
\chapter{Declarations} %5
\printThumbIndex{5}
I/We hereby confirm the accuracy of the information contained in the proposal, including the research profiles.

The \emph{DFG Rules of Procedure for Dealing with Scientific Misconduct}
(\emph{known as VerfOwF})
apply to individuals with a high level of scientific/\-academic responsibility in connection with funding proposals submitted by universities. The applicant \dfgApplicantAffiliationsTF{university confirms}{universities confirm} that all individuals with a high level of scientific/\-academic responsibility in the project proposal submitted by the \dfgApplicantAffiliationsTF{university}{universities} (cf. programme guidelines, DFG form 50.06) recognise the \emph{DFG Rules of Procedure for Dealing with Scientific Misconduct} as legally binding by submitting a corresponding declaration of commitment.

In submitting this proposal, all project leaders undertake to comply with the
relevant discipline-specific research ethics guidelines, to determine whether
a statement from the responsible ethics committee is required and, where
necessary, to obtain it in good time before the start of funding.  They will
inform the DFG immediately if an ethics committee expresses substantive
concerns or issues a negative statement and will submit the statement if the
DFG requests it.

The DFG takes the protection of your personal data very seriously.
Please note the DFG’s data protection notice on research funding, which can be viewed and downloaded at
\url{www.dfg.de/privacy_policy}

Please forward this information to those individuals whose data will be processed by the DFG because they are mentioned in your proposal.

I/We have read the DFG’s data protection notice.

I/We consent to the processing and transfer of special categories of personal
data (including the data of all parties involved) for the purposes stated in the
Privacy Policy if, after careful consideration, I/we provide such data either
now or at a later date.\par
\vfill

\printSignaturesWithRole{spokesperson}{(Spokesperson~of~\crc)}
\printSignaturesWithRole{rector}
  {(Rector,~chancellor,~or~president~of~
    \getEntry[affiliation]{\theAffiliationOfRoleID}{name})}
%    \end{macrocode}
% \iffalse
%</05>
%<*99>
% \fi
% \subsection{Backmatter File}
% The final page suppresses running headers and page numbers and delegates the
% complete layout to the project-overview table defined by the class.
%    \begin{macrocode}
\pagestyle{empty}
\printTable{projectOverview}
%    \end{macrocode}
% \iffalse
%</99>
%<*test-project-collaboration>
% \fi
% \subsection{Project collaboration plot test}
% This focused test is deliberately independent of the proposal metadata.  It
% contains active, ending, and reference-only projects; duplicate and
% reverse-only declarations; and calls both supported collaboration layouts.
%    \begin{macrocode}
%% Compile from the generated local directory with:
%%   lualatex -interaction=nonstopmode -halt-on-error test-project-collaboration.tex
%%
%% This test is deliberately self-contained.  The image switch is initially
%% false so the fast project option prevents the proposal metadata from loading.
%% Immediately after \begin{document} the image switch is enabled so dummy
%% project entries are retained and the plots below exercise their focused-mode
%% dispatch without disabling the other fast-mode reductions.
\documentclass[
  fastcompile-project = true,
  fastcompile-project-show-images = false,
  english
]{dfg-crc}

\begin{document}

\ExplSyntaxOn
\bool_set_true:N \l_@@_class_fastcompile_project_show_images_bool
\ExplSyntaxOff

%% #1 is either empty or a complete project-area assignment; #2 is the
%% project id, #3 status (C/N/E), #4 collaborations, and #5 reference-only.
\NewDocumentCommand{\AddDummyProjectEntry}{m m m m m}{
  \addEntry{project}{
    id                 = {#2},
    #1
    number             = {#2},
    name               = {Dummy project #2},
    project-status     = {#3},
    project-type       = {research},
    consider-for-lists = {true},
    reference-only     = {#5},
    ref-person-id      = {},
    collaboration      = {#4},
    research-area      = {},
    legal-issues       = {
      L1  = {no},
      L1a = {},
      L2  = {no},
      L2a = {},
      L3  = {no},
      L4  = {no},
      L5  = {no},
      L5a = {},
      L6  = {no},
      L7  = {no},
      L7a = {}
    }
  }
}
%% Omitting the optional area leaves the project-area database column absent
%% until the first plot and therefore exercises both schema and ID fallbacks.
\NewDocumentCommand{\AddDummyProject}{o m m m m}{
  \IfNoValueTF{#1}
    { \AddDummyProjectEntry{}{#2}{#3}{#4}{#5} }
    { \AddDummyProjectEntry{project-area={#1},}{#2}{#3}{#4}{#5} }
}

%% Active project area A.  A11 repeats B06 deliberately to test that an
%% undirected relation declared twice is collapsed.
\AddDummyProject{A02}{C}{}{false}
\AddDummyProject{A03}{C}{}{false}
\AddDummyProject{A05}{C}{}{false}
\AddDummyProject{A09}{C}{}{false}
\AddDummyProject{A10}{C}{}{false}
\AddDummyProject{A11}{C}{B06}{false}
\AddDummyProject{A12}{N}{}{false}
\AddDummyProject{A13}{N}{}{false}

%% A04 is ending and A00 is reference-only.  Neither may occur in a plot.
\AddDummyProject{A04}{E}{}{false}
\AddDummyProject{A00}{C}{}{true}

%% Active project area B.  The A04 relation checks ending-project filtering.
\AddDummyProject{B01}{C}{}{false}
\AddDummyProject{B04}{C}{}{false}
\AddDummyProject{B05}{C}{}{false}
\AddDummyProject{B06}{C}
  {A00,A04,A11,A12,B01,B04,B05,B07,B10}
  {false}
\AddDummyProject{B07}{C}{}{false}
\AddDummyProject{B08}{C}{}{false}
\AddDummyProject{B09}{C}{}{false}
\AddDummyProject{B10}{N}{}{false}

%% Active project area Q.  Q02 declares B06 in the reverse direction only.
\AddDummyProject{Q01}{C}{}{false}
\AddDummyProject{Q02}{C}{B06}{false}
\AddDummyProject{Q03}{C}{}{false}
\AddDummyProject{Q04}{C}{}{false}

%% Focused image mode must retain Gantt rows created through the same data path
%% as ordinary project work packages.
\addEntry[gantt]{gantt-B06}{
  id = {wp1},
  name = {Dummy work package},
  description = {Dummy Gantt bar},
  periodStart = {1},
  periodEnd = {4},
  style = {default}
}

\printPlot{{Gantt}{B06}}

%% The first plot is deliberately called before any project-area key has been
%% entered.  It exercises the missing-column and ID-prefix fallbacks.
\printPlot[layout=heatmap,caption={Many collaborations are shown here.}]
  {{collaboration}{B06}}

\clearpage

%% Explicit project areas need not match the project-ID prefix.  The longer
%% service-area label exercises dynamic label measurement, while the options
%% exercise explicit color mappings for otherwise unknown areas.
\AddDummyProject[C]{X01}{C}{B06}{false}
\AddDummyProject[Shared services]{Y01}{N}{}{false}
\ExplSyntaxOn
\@@_project_count_build:
\prop_get:NnN \g_@@_project_count_area_prop { C } \l_tmpa_tl
\int_compare:nNnF { \l_tmpa_tl } = { 1 }
  { \PackageError{test}{Expected~one~project~in~dynamic~area~C}{} }
\prop_get:NnN \g_@@_project_count_area_prop { SHARED~SERVICES } \l_tmpa_tl
\int_compare:nNnF { \l_tmpa_tl } = { 1 }
  { \PackageError{test}{Expected~one~project~in~dynamic~Shared~services~area}{} }
\ExplSyntaxOff
\printPlot[
  layout=heatmap,
  area-colors={C=cyan!70!black,Shared services=orange!80!black}
]{{collaboration}{B07}}

\clearpage

%% Select the low arc layout with arcs explicitly. Every displayed arc reaches the
%% same vertical peak, IDs should sit inside the boxes, and each area rule should
%% span its boxes; additional caption text uses the leading options.
\printPlot[
  layout=arc,
  arcs=true,
  area-palette={orange!80!black,violet!75!black,teal!70!black},
  caption={Dummy metadata; A04 and A00 are intentionally omitted.}
]{{collaboration}{B06}}

\clearpage

%% The same full-width node strip can be shown without connecting arcs.
\printPlot[arcs=false]{{collaboration}{B06}}

\clearpage

%% Turning the image switch off again must restore the fast-mode plot skip.
\ExplSyntaxOn
\bool_set_false:N \l_@@_class_fastcompile_project_show_images_bool
\ExplSyntaxOff
\printPlot{{ProjectCollaboration}{B06}}

\end{document}
%    \end{macrocode}
% \iffalse
%</test-project-collaboration>
%<*test-reference-lookups>
% \fi
% \subsection{Reference-path lookup regression test}
% Exercise the public command against real databases, including fan-out,
% shared destinations, arbitrary database names, missing data and fast mode.
% The tag hook records the originating row and protected value of every result.
%    \begin{macrocode}
\documentclass[english,final=true]{dfg-crc}
\ExplSyntaxOn
\tl_new:N \g_@@_get_test_seen_tl
\int_new:N \g_@@_get_test_count_int
\NewDocumentCommand{\CheckGet}{m m +m}
{
  \tl_gclear:N \g_@@_get_test_seen_tl
  \par\noindent #1:~#3\par
  \str_if_eq:eeF {\tl_to_str:V \g_@@_get_test_seen_tl}{\tl_to_str:n {#2}}
    {\PackageError{get-test}{Failed~#1:~\tl_to_str:V \g_@@_get_test_seen_tl}
      {Expected~\tl_to_str:n {#2}}}
  \int_gincr:N \g_@@_get_test_count_int
  \typeout{GET~TEST~PASS:~#1}
}
% A custom keyset verifies that traversal does not hard-code the four
% built-in relation types or require the source database to match its keyset.
\keys_define:nn {get-test}
{
  id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{id}{#1},
  name .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{name}{#1},
  code .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{code}{#1},
  ref-person-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-person-id}{#1},
  ref-other-unit-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-other-unit-id}{#1},
  ref-absent-db-id .code:n = \DTLnewdbentry{\l_@@_database_name_tl}{ref-absent-db-id}{#1},
}
\ExplSyntaxOff
\begin{document}
\DTLcleardb{person}
\DTLcleardb{institution}
\DTLcleardb{affiliation}
\DTLcleardb{project}
\addEntry{affiliation}{id={a1},name={University One},country={Germany}}
\addEntry{affiliation}{id={a2},name={University Two},country={France}}
\addEntry{institution}{id={i1},name={\textbf{Alpha Institute}},ref-affiliation-id={a1}}
\addEntry{institution}{id={i2},name={Beta Institute},ref-affiliation-id={a1}}
\addEntry{institution}{id={i3},name={Gamma Institute},ref-affiliation-id={a2}}
\addEntry{person}{id={p1},lastname={Example},ref-institution-id={i1},ref-project-id={P1}}
\addEntry{person}{id={p2},lastname={Other},ref-institution-id={i2,i3,i1,i2}}
\addEntry{person}{id={empty},lastname={Empty},ref-institution-id={}}
\addEntry{person}{id={broken},ref-institution-id={unknown,i3}}
\addEntry{project}{id={P1},name={Project One},ref-person-id={p1,p2}}
\addEntry[get-test]{lookup-source}{id={r1},code={alternate},ref-person-id={p1,p2},ref-other-unit-id={u1}}
\addEntry[get-test]{other-unit}{id={u1},name={Custom Unit},ref-person-id={p1}}
\addEntry[get-test]{lookup-source}{id={r2},ref-absent-db-id={nowhere}}

\ExplSyntaxOn
\RenewDocumentCommand{\dfgShowTag}{m m m o}
{
  \tl_gput_right:Nn \g_@@_get_test_seen_tl {[#4/#1/#2]=#3;}
  #3
}
\ExplSyntaxOff
\CheckGet{direct}{[person/p1/lastname]=Example;}{\get[person]{p1}{lastname}}
\CheckGet{one-hop}{[institution/i1/name]=\textbf{Alpha Institute};}
  {\get[person]{p1}{institution}{name}}
\CheckGet{explicit-key}{[institution/i1/name]=\textbf{Alpha Institute};}
  {\get[person]{p1}{ref-institution-id}{name}}
\CheckGet{two-hops}{[affiliation/a1/name]=University One;}
  {\get[person]{p1}{institution}{affiliation}{name}}
\CheckGet{explicit-chain}{[affiliation/a1/country]=Germany;}
  {\get[person]{p1}{ref-institution-id}{ref-affiliation-id}{country}}
\CheckGet{institution-root}{[affiliation/a1/name]=University One;}
  {\get[institution]{i2}{affiliation}{name}}
\CheckGet{project-reference}{[project/P1/name]=Project One;}
  {\get[person]{p1}{project}{name}}
\CheckGet{person-reference}{[person/p1/lastname]=Example;[person/p2/lastname]=Other;}
  {\get[project]{P1}{person}{lastname}}
\CheckGet{multiple-ids}{[institution/i2/name]=Beta Institute;[institution/i3/name]=Gamma Institute;[institution/i1/name]=\textbf{Alpha Institute};}
  {\get[person]{p2}{institution}{name}}
\CheckGet{shared-affiliation}{[affiliation/a1/name]=University One;[affiliation/a2/name]=University Two;}
  {\get[person]{p2}{institution}{affiliation}{name}}
\CheckGet{three-hops}{[affiliation/a1/name]=University One;[affiliation/a2/name]=University Two;}
  {\get[project]{P1}{person}{institution}{affiliation}{name}}
\CheckGet{named-source}{[person/p1/lastname]=Example;[person/p2/lastname]=Other;}
  {\get[lookup-source]{r1}{person}{lastname}}
\CheckGet{custom-target}{[other-unit/u1/name]=Custom Unit;}
  {\get[lookup-source]{r1}{other-unit}{name}}
\CheckGet{custom-explicit}{[person/p1/lastname]=Example;}
  {\get[lookup-source]{r1}{ref-other-unit-id}{ref-person-id}{lastname}}
\CheckGet{alternative-id}{[person/p1/lastname]=Example;[person/p2/lastname]=Other;}
  {\get[lookup-source]{alternate}{person}[code]{lastname}}
\def\tmpLocalDB{person}
\CheckGet{default-database}{[institution/i1/name]=\textbf{Alpha Institute};}
  {\get{p1}{institution}{name}}
\CheckGet{raw-reference}{[person/p1/ref-institution-id]=i1;}
  {\get[person]{p1}{ref-institution-id}}
\CheckGet{following-group}{[person/p1/lastname]=Example;}
  {\get[person]{p1}{lastname}{\textbf{Following prose.}}}
\CheckGet{field-reference-cycle}{[person/p1/lastname]=Example;[person/p2/lastname]=Other;}
  {\get[person]{p1}{project}{person}{lastname}}
\CheckGet{starred}{}{
  \get*[person]{p1}{\TestLastname=lastname}
  \ifdefstring{\TestLastname}{Example}{}{\PackageError{get-test}{Starred lookup failed}{}}
}
\CheckGet{empty-reference}{}{\get[person]{empty}{institution}{name}}
\CheckGet{missing-root}{}{\get[person]{missing}{institution}{name}}
\CheckGet{missing-leaf}{}{\get[person]{p1}{institution}{absent-field}}
\CheckGet{missing-relation}{}{\get[institution]{i1}{person}{lastname}}
\CheckGet{missing-target-db}{}{\get[lookup-source]{r2}{ref-absent-db-id}{name}}
\CheckGet{missing-source-db}{}{\get[absent-db]{r1}{person}{lastname}}
\CheckGet{broken-branch}{[institution/i3/name]=Gamma Institute;}
  {\get[person]{broken}{institution}{name}}
\CheckGet{after-missing-reset}{[affiliation/a1/name]=University One;}
  {\get[person]{p1}{institution}{affiliation}{name}}
\begingroup
\ExplSyntaxOn
\bool_set_true:N \l_@@_class_fastcompile_project_bool
\RenewDocumentCommand{\dfgFastReference}{m}
  {\tl_gput_right:Ne \g_@@_get_test_seen_tl {fast:#1;}}
\RenewDocumentCommand{\dfgShowTag}{m m m o}
{
  \tl_gput_right:Ne \g_@@_get_test_seen_tl
    {tag:\IfNoValueTF{#4}{}{#4}/#1/#2;}
  #3
}
\ExplSyntaxOff
\CheckGet{fast-chain}{tag:person/p1/institution/affiliation/name;fast:p1;}
  {\get[person]{p1}{institution}{affiliation}{name}}
\addEntry[get-test]{skipped-source}{id={skip},ref-other-unit-id={u1}}
\CheckGet{fast-skipped-custom}
  {tag:skipped-source/skip/other-unit/person/lastname;fast:skip;}
  {\get[skipped-source]{skip}{other-unit}{person}{lastname}}
\CheckGet{fast-skipped-scalar}{tag:skipped-source/skip/name;fast:skip;}
  {\get[skipped-source]{skip}{name}{\textbf{Following prose.}}}
\CheckGet{fast-star}{}{
  \def\TestLastname{stale}
  \get*[person]{p1}{\TestLastname=lastname}
  \ifdefempty{\TestLastname}{}{\PackageError{get-test}{Fast starred lookup failed}{}}
}
\endgroup
\CheckGet{after-fast-reset}{[person/p1/lastname]=Example;}{\get[person]{p1}{lastname}}
\ExplSyntaxOn
\int_compare:nNnF {\g_@@_get_test_count_int} = {33}
  {\PackageError{get-test}{Not~all~33~cases~ran}{}}
\ExplSyntaxOff
\typeout{REFERENCE LOOKUP TEST PASS: 33 cases}
\end{document}
%    \end{macrocode}
% \iffalse
%</test-reference-lookups>
%<*test-command-options>
% \fi
% \subsection{Public-command option regression tests}
% Small probe renderers check the public dispatchers without depending on a
% particular table or plot. Database-aware lists retain their real lookup and
% filtering; only their final cells are replaced with assertions.
%    \begin{macrocode}
% The customization file is loaded during class initialization. Probe both
% interfaces there, then verify that later class setup preserves the values.
\AddToHook{file/dfg-customization.tex/before}{%
  \let\DefaultDateBeforeCustomization\dfgDate
  \renewcommand{\dfgLocation}{Direct early location\xspace}%
  \renewcommand{\dfgDate}{Direct early date\xspace}%
  \renewcommand{\dfgTitle}{Direct early title\xspace}%
  \renewcommand{\InfoTeX}{Direct early compiler}%
  \changeSettings{
    dfgLocation={Early location}, dfgDate={Early date},
    dfgTitle={Early title}, InfoTeX={Early compiler}}
}
\documentclass[english,final=true]{dfg-crc}
\ExplSyntaxOn
\int_new:N \g_@@_document_settings_test_count_int
\NewDocumentCommand{\CheckDocumentSetting}{m m m}
{
  \tl_set:No \l_tmpa_tl {#2}
  \tl_if_eq:NnF \l_tmpa_tl {#3}
    {\PackageError{settings-test}{Failed~#1}{Unexpected~document~text.}}
  \int_gincr:N \g_@@_document_settings_test_count_int
}
\ExplSyntaxOff
% Resolve the default date's fast-mode conditional, preserving its spacing
% command. Other checks below deliberately retain deferred metadata lookups.
\ExplSyntaxOn
\group_begin:
\cs_set_eq:NN \xspace \scan_stop:
\cs_set:Npe \ExpandedDefaultDateBeforeCustomization
  {\DefaultDateBeforeCustomization}
\CheckDocumentSetting{generic-date}
  {\ExpandedDefaultDateBeforeCustomization}{<date>\xspace}
\group_end:
\ExplSyntaxOff
\CheckDocumentSetting{early-location}{\dfgLocation}{Early location\xspace}
\CheckDocumentSetting{early-date}{\dfgDate}{Early date\xspace}
\CheckDocumentSetting{early-title}{\dfgTitle}{Early title\xspace}
\CheckDocumentSetting{early-compiler}{\InfoTeX}{Early compiler}
\begingroup
\changeSettings{
  dfgLocation={Runtime location}, dfgDate={Runtime date},
  dfgTitle={\get[meta]{crc}{name}}, InfoTeX={Runtime compiler}}
\CheckDocumentSetting{runtime-location}{\dfgLocation}{Runtime location\xspace}
\CheckDocumentSetting{runtime-date}{\dfgDate}{Runtime date\xspace}
\CheckDocumentSetting{deferred-title}{\dfgTitle}{\get[meta]{crc}{name}\xspace}
\CheckDocumentSetting{runtime-compiler}{\InfoTeX}{Runtime compiler}
\renewcommand{\dfgLocation}{Direct location\xspace}
\renewcommand{\dfgDate}{Direct date\xspace}
\renewcommand{\dfgTitle}{Direct title\xspace}
\renewcommand{\InfoTeX}{Direct compiler}
\CheckDocumentSetting{direct-location}{\dfgLocation}{Direct location\xspace}
\CheckDocumentSetting{direct-date}{\dfgDate}{Direct date\xspace}
\CheckDocumentSetting{direct-title}{\dfgTitle}{Direct title\xspace}
\CheckDocumentSetting{direct-compiler}{\InfoTeX}{Direct compiler}
\endgroup
\CheckDocumentSetting{local-settings-scope}{\dfgDate}{Early date\xspace}
\ExplSyntaxOn
\int_compare:nNnF {\g_@@_document_settings_test_count_int} = {14}
  {\PackageError{settings-test}{Not~all~14~cases~ran}{}}
\typeout{DOCUMENT~SETTINGS~TEST~PASS:~14~cases}

% Exercise the public customization getter through real key assignments.
% All rates below are synthetic, group-local test inputs, not proposal defaults.
\int_new:N \g_@@_get_value_test_count_int
\cs_new_protected:Npn \@@_test_custom_value:nn #1#2
  {
    \tl_set:Ne \l_tmpa_tl {\getValue{#1}}
    \str_if_eq:VnF \l_tmpa_tl {#2}
      {\PackageError{settings-test}{Unexpected~getValue~result~for~#1}{}}
    \int_gincr:N \g_@@_get_value_test_count_int
  }
\@@_test_custom_value:nn {journalTitle}{journaltitle}
\group_begin:
  \changeSettings{journalTitle=shortjournal}
  \@@_test_custom_value:nn {journalTitle}{shortjournal}
\group_end:
\@@_test_custom_value:nn {journalTitle}{journaltitle}
\clist_map_inline:nn
  {font,fontspec,sansfont,sansfontspec,crcLogoPath,affiliationLogoPath,PIcontactStyle,collaborationAreaColors,thumbindex@font,doiAPIMail,biblatexstyleCV,biblatexstyleFeatureCV,biblatexstyleProposal,biblatexstyleFeatureProposal,color@reference@boldAuthor,color@reference@PI,color@reference@WP,color@reference@Aim,color@gantt@frame,color@gantt@default,color@gantt@alternative,color@gantt@crosshatch,color@gantt@important,color@gantt@stripe-one,color@gantt@stripe-two,color@table@headingsBG,color@table@headingsBGalt,color@table@headingsFont,color@table@rows,color@table@lines,color@table@outerLines,color@table@noValue,color@table@firstColumn,color@table@link,color@table@contFootHead,color@table@caption,color@thumbindex@bg,color@thumbindex@font,color@tags@font,color@tags@line,color@font@alternative,color@item@i}
  {
    \group_begin:
    \changeSettings{#1={Getter~probe}}
    \@@_test_custom_value:nn {#1}{Getter~probe}
    \changeSettings{#1={Second~probe}}
    \@@_test_custom_value:nn {#1}{Second~probe}
    \group_end:
  }
\clist_map_inline:nn
  {projectPIOncePerSection,PIReferenceFirstName,projectsTableInstitutionAbbreviations,categoryAbbreviations,thumbindex,emphasizeAuthors,emphasizeEntries}
  {
    \group_begin:
    \changeSettings{#1={false}}
    \@@_test_custom_value:nn {#1}{false}
    \changeSettings{#1={true}}
    \@@_test_custom_value:nn {#1}{true}
    \group_end:
  }
\clist_map_inline:nn
  {salary@prof,salary@groupLeader,salary@postDoc,salary@medDoc,salary@PhD,salary@research,salary@nonResearch,salary@student,salary@assistant,animalHousing@mouse,animalHousing@mouseGnotobiotic,animalHousing@rat}
  {
    \group_begin:
    \changeSettings{#1={17.25}}
    \@@_test_custom_value:nn {#1}{17.25}
    \changeSettings{#1={23.5}}
    \@@_test_custom_value:nn {#1}{23.5}
    \group_end:
  }
\clist_map_inline:nn
  {thumbindex@pattern}
  {
    \group_begin:
    \changeSettings{#1={17}}
    \@@_test_custom_value:nn {#1}{17}
    \changeSettings{#1={23}}
    \@@_test_custom_value:nn {#1}{23}
    \group_end:
  }
\clist_map_inline:nn
  {thumbindex@width}
  {
    \group_begin:
    \changeSettings{#1={17pt}}
    \@@_test_custom_value:nn {#1}{17.0pt}
    \changeSettings{#1={23pt}}
    \@@_test_custom_value:nn {#1}{23.0pt}
    \group_end:
  }

\group_begin:
\cs_set:Npn \xspace {}
\changeSettings{dfgLocation=Here,dfgDate=Today,dfgTitle=Title,InfoTeX=Compiler,
  collaborationAreaPalette={red,blue},thumbindex@topmargin=17pt,
  thumbindex@bottommargin=23pt,thumbindex@orientation=inwards,
  animalHousing@mouse=0.85,salary@postDoc=90000}
\@@_test_custom_value:nn {dfgLocation}{Here}
\@@_test_custom_value:nn {dfgDate}{Today}
\@@_test_custom_value:nn {dfgTitle}{Title}
\@@_test_custom_value:nn {InfoTeX}{Compiler}
\@@_test_custom_value:nn {collaborationAreaPalette}{red,blue}
\changeSettings{collaborationAreaPalette={}}
\@@_test_custom_value:nn {collaborationAreaPalette}{red,blue}
\@@_test_custom_value:nn {thumbindex@topmargin}{17.0pt}
\@@_test_custom_value:nn {thumbindex@bottommargin}{23.0pt}
\@@_test_custom_value:nn {thumbindex@orientation}{inwards}
\changeSettings{thumbindex@topmargin=auto,thumbindex@bottommargin=auto,
  thumbindex@orientation=outwards}
\@@_test_custom_value:nn {thumbindex@topmargin}{auto}
\@@_test_custom_value:nn {thumbindex@bottommargin}{auto}
\@@_test_custom_value:nn {thumbindex@orientation}{outwards}
\@@_test_custom_value:nn {~animalHousing@mouse~}{0.85}
\fp_compare:nNnF {2 * \getValue{animalHousing@mouse}} = {1.7}
  {\PackageError{settings-test}{getValue~failed~in~arithmetic}{}}
\group_begin:
\changeSettings{animalHousing@mouse=1.25}
\@@_test_custom_value:nn {animalHousing@mouse}{1.25}
\group_end:
\@@_test_custom_value:nn {animalHousing@mouse}{0.85}
\changeSettings{biblatexstyle=shared,biblatexstyleFeature=shared-feature}
\@@_test_custom_value:nn {biblatexstyleCV}{shared}
\@@_test_custom_value:nn {biblatexstyleProposal}{shared}
\changeSettings{biblatexstyleCV=cv-style,biblatexstyleProposal=proposal-style,
  biblatexstyleFeatureCV=cv-feature,biblatexstyleFeatureProposal=proposal-feature}
\bool_set_false:N \l_@@_class_cv_bool
\@@_test_custom_value:nn {biblatexstyle}{proposal-style}
\@@_test_custom_value:nn {biblatexstyleFeature}{proposal-feature}
\bool_set_true:N \l_@@_class_cv_bool
\@@_test_custom_value:nn {biblatexstyle}{cv-style}
\@@_test_custom_value:nn {biblatexstyleFeature}{cv-feature}
\group_end:
% Relative CV spacing follows the line spacing at use, including in getters.
\group_begin:
  \skip_set:Nn \baselineskip {10pt}
  \changeSettings{cvTableAfterSkip={-.5\baselineskip}}
  \@@_test_custom_value:nn {cvTableAfterSkip}{-5.0pt}
  \skip_set:Nn \baselineskip {20pt}
  \@@_test_custom_value:nn {cvTableAfterSkip}{-10.0pt}
  \group_begin:
    \changeSettings{cvTableAfterSkip=0pt}
    \@@_test_custom_value:nn {cvTableAfterSkip}{0.0pt}
  \group_end:
  \@@_test_custom_value:nn {cvTableAfterSkip}{-10.0pt}
\group_end:
\typeout{CUSTOMIZATION~GETTER~TEST~PASS:~\int_use:N\g_@@_get_value_test_count_int~checks}


\tl_new:N \g_@@_options_test_result_tl
\tl_new:N \l_@@_options_test_mode_tl
\tl_new:N \l_@@_options_test_caption_tl
\dim_new:N \l_@@_options_test_width_dim
\int_new:N \g_@@_options_test_count_int
\keys_define:nn {dfg-options-test}
{
  mode .tl_set:N = \l_@@_options_test_mode_tl,
  caption .tl_set:N = \l_@@_options_test_caption_tl,
}
\cs_new_protected:Npn \@@_options_test_probe:nnn #1#2#3
{
  \tl_set:Nn \l_@@_options_test_mode_tl {empty}
  \tl_clear:N \l_@@_options_test_caption_tl
  \keys_set:nn {dfg-options-test} {#2}
  \tl_gput_right:Ne \g_@@_options_test_result_tl
    {#1|\l_@@_options_test_mode_tl|\l_@@_options_test_caption_tl|#3}
}
\NewDocumentCommand{\OptionProbeList}{O{mode=default}}
  {\@@_options_test_probe:nnn {list}{#1}{}}
\NewDocumentCommand{\OptionProbePlot}{O{mode=default}}
  {\@@_options_test_probe:nnn {plot}{#1}{}}
\NewDocumentCommand{\OptionProbeTable}{O{mode=default}}
{
  \int_compare:nNnF {\value{rowNumber}} = {0}
    {\PackageError{options-test}{Table~row~counter~was~not~reset}{}}
  \@@_options_test_probe:nnn {table}{#1}{}
}
\NewDocumentCommand{\OptionArgumentsList}{O{mode=default} m m}
  {\@@_options_test_probe:nnn {list}{#1}{#2/#3}}
\NewDocumentCommand{\OptionArgumentsPlot}{O{mode=default} m m}
  {\@@_options_test_probe:nnn {plot}{#1}{#2/#3}}
\NewDocumentCommand{\OptionArgumentsTable}{O{mode=default} m m}
  {\@@_options_test_probe:nnn {table}{#1}{#2/#3}}
\NewDocumentCommand{\CheckOptions}{m m +m}
{
  \tl_gclear:N \g_@@_options_test_result_tl
  #3
  \str_if_eq:eeF {\g_@@_options_test_result_tl} {#2}
  {
    \PackageError{options-test}{Failed~#1:~\g_@@_options_test_result_tl}
      {Expected~#2.}
  }
  \int_gincr:N \g_@@_options_test_count_int
  \typeout{OPTIONS~TEST~PASS:~#1}
}
% Keep the real database lookup and option parsing; inspect the resulting
% institution ID and boolean settings at the final formatting boundary.
\cs_set_protected:Npn \_@@_one_institution:n #1
{
  \tl_gput_right:Ne \g_@@_options_test_result_tl
  {
    #1|
    \bool_if:NTF \l_@@_institution_abbreviation_bool {1}{0}
    \bool_if:NTF \l_@@_narrow_bool {1}{0}
    \bool_if:NTF \l_@@_noaddr_bool {1}{0}
    \bool_if:NTF \l_@@_nozip_bool {1}{0}
    \bool_if:NTF \l_@@_noloc_bool {1}{0}
  }
}
% Keep the real PI filtering and raster, but use a minimal box to measure
% the available column width independently of the card's text/padding.
\cs_set_protected:Npn \__getperson_one:n #1
{
  \begin{tcolorbox}[blankest]
    \dim_compare:nNnT
      {\dim_abs:n{\linewidth-\l_@@_options_test_width_dim}} > {.1pt}
      {\PackageError{options-test}{PI~raster~column~width~is~wrong}{}}
    \tl_gput_right:Ne \g_@@_options_test_result_tl
      {#1\bool_if:NT \l_@@_pi_academicdegree_below_bool {|below}}
    PI~#1
  \end{tcolorbox}
}
\NewDocumentCommand{\CheckPIOptions}{m m m +m}
{
  \dim_set:Nn \l_@@_options_test_width_dim
    {(\linewidth-12pt*\int_eval:n{#2-1})/#2}
  \CheckOptions{#1}{#3}{#4}
}
\ExplSyntaxOff

\begin{document}
\begingroup
\changeSettings{animalHousing@mouse=0.85,salary@postDoc=90000}
Test-only mouse housing: \num{\getValue{animalHousing@mouse}}\,EUR per week.\par
Test-only postdoctoral salary: \num{\getValue{salary@postDoc}}\,EUR per year.\par
\endgroup

\section*{Command option regression checks}
\CheckOptions{list-omitted}{list|default||}{\printList{OptionProbe}}
\CheckOptions{list-empty}{list|empty||}{\printList[]{OptionProbe}}
\CheckOptions{list-grouped}{list|default||}{\printList{{OptionProbe}}}
\CheckOptions{list-leading}{list|leading||}{\printList[mode=leading]{OptionProbe}}
\CheckOptions{list-legacy}{list|legacy||}{\printList{OptionProbe}[mode=legacy]}
\CheckOptions{list-precedence}{list|leading||}
  {\printList[mode=leading]{{OptionProbe}}[mode=legacy]}
\CheckOptions{list-arguments}{list|leading|left,right|A01/two words}
  {\printList[mode=leading,caption={left,right}]{{OptionArguments}{A01}{two words}}}
\CheckOptions{plot-omitted}{plot|default||}{\printPlot{OptionProbe}}
\CheckOptions{plot-empty}{plot|empty||}{\printPlot[]{OptionProbe}}
\CheckOptions{plot-grouped}{plot|default||}{\printPlot{{OptionProbe}}}
\CheckOptions{plot-arguments}{plot|leading|left,right|A01/two words}
  {\printPlot[mode=leading,caption={left,right}]{{OptionArguments}{A01}{two words}}}
\CheckOptions{plot-embedded-legacy}{plot|legacy||A01/second}
  {\printPlot{{OptionArguments}[mode=legacy]{A01}{second}}}
\setcounter{rowNumber}{99}
\CheckOptions{table-omitted-and-counter}{table|default||}{\printTable{OptionProbe}}
\CheckOptions{table-empty}{table|empty||}{\printTable[]{OptionProbe}}
\CheckOptions{table-grouped}{table|default||}{\printTable{{OptionProbe}}}
\CheckOptions{table-arguments}{table|leading|left,right|A01/two words}
  {\printTable[mode=leading,caption={left,right}]{{OptionArguments}{A01}{two words}}}

\DTLcleardb{person}
\addEntry{person}{id={default-person},lastname={Default},role={PI},
  period={1,2,3},ref-institution-id={default-institute}}
\DTLnewdb{option-people}
\DTLnewrow{option-people}
\DTLnewdbentry{option-people}{id}{other-person}
\DTLnewdbentry{option-people}{lastname}{Other}
\DTLnewdbentry{option-people}{role}{PI,spokesperson}
\DTLnewdbentry{option-people}{period}{1,2,3}
\DTLnewdbentry{option-people}{ref-institution-id}{other-institute}

\CheckOptions{institutions-default}{default-institute|00000}
  {\printList{{Institutions}{default-person}}}
\CheckOptions{institutions-flags}{other-institute|11111}
  {\printList[database=option-people,abbreviation,narrow,noaddress,nozip,nolocation]
    {{Institutions}{other-person}}}
\CheckOptions{institutions-legacy-database}{other-institute|11000}
  {\InstitutionsList[option-people]{other-person}[abbreviation,narrow]}
\CheckOptions{institutions-precedence}{other-institute|01000}
  {\InstitutionsList[database=option-people,abbreviation=false,narrow]
    {other-person}[abbreviation]}
\CheckOptions{institutions-dispatch-precedence}{other-institute|01000}
  {\printList[database=option-people,abbreviation=false,narrow]
    {{Institutions}{other-person}}[abbreviation]}
\CheckOptions{institutions-empty}{default-institute|00000}
  {\InstitutionsList[]{default-person}}
\CheckOptions{institutions-reset}{default-institute|00000}
  {\InstitutionsList{default-person}}

\CheckPIOptions{pi-default}{3}{default-person}{\getPIsWithRole{PI}}
\CheckPIOptions{pi-leading}{2}{other-person}
  {\getPIsWithRole[database=option-people,raster columns=2]{spokesperson}}
\CheckPIOptions{pi-legacy}{1}{other-person}
  {\getPIsWithRole[option-people]{PI}[raster columns=1]}
\CheckPIOptions{pi-precedence}{2}{other-person}
  {\getPIsWithRole[database=option-people,raster columns=2]{PI}[raster columns=1]}
\CheckPIOptions{pi-degree-below}{3}{default-person|below}
  {\getPIsWithRole[academicdegree-below]{PI}}
\CheckPIOptions{pi-degree-legacy}{1}{other-person|below}
  {\getPIsWithRole[option-people]{PI}[academicdegree-below,raster columns=1]}
\CheckPIOptions{pi-degree-precedence}{3}{default-person}
  {\getPIsWithRole[academicdegree-below=false]{PI}[academicdegree-below]}
\CheckPIOptions{pi-degree-reset}{3}{default-person}{\getPIsWithRole{PI}}
\CheckPIOptions{pi-empty}{3}{default-person}{\getPIsWithRole[]{PI}}
\CheckPIOptions{pi-reset}{3}{default-person}{\getPIsWithRole{PI}}
\CheckPIOptions{pi-role-filter}{3}{}{\getPIsWithRole{spokesperson}}

\ExplSyntaxOn
\int_compare:nNnF {\g_@@_options_test_count_int} = {34}
  {\PackageError{options-test}{Not~all~34~cases~ran}{}}
\ExplSyntaxOff
\typeout{COMMAND OPTIONS TEST PASS: 34 cases}

% Render real metadata lookups to check punctuation and option defaults.
\clearpage
\section*{Project PI prose lists}
\addEntry{person}{id={pi-test-a},firstname={Alice},lastname={Able},academicdegree={Dr.}}
\addEntry{person}{id={pi-test-b},firstname={Bob},lastname={Baker},academicdegree={Dr.}}
\addEntry{person}{id={pi-test-c},firstname={Carol},lastname={Clark},academicdegree={Dr.}}
\addEntry{person}{id={pi-test-d},firstname={Dan},lastname={Dover},academicdegree={Dr.}}
\addEntry{project}{id={PI0},ref-person-id={}}
\addEntry{project}{id={PI1},ref-person-id={pi-test-a}}
\addEntry{project}{id={PI2},ref-person-id={pi-test-a,pi-test-b}}
\addEntry{project}{id={PI3},ref-person-id={pi-test-a,pi-test-b,pi-test-c}}
\addEntry{project}{id={PI4},ref-person-id={pi-test-a,pi-test-b,pi-test-c,pi-test-d}}
Zero: [\getPIofProject*{PI0}].\par
One: \getPIofProject*{PI1}.\par
Two: \getPIofProject*{PI2}.\par
Three: \getPIofProject*{PI3}.\par
Four: \getPIofProject*{PI4}.\par
Properties: \getPIofProject*[lastname]{PI3}.\par
Final separator: \getPIofProject*{PI3}[\space und \space].\par
Legacy: \getPIofProject[firstname,lastname]{PI3}[; ].\par
Reset: \getPIofProject{PI2}.\par
Empty properties: [\getPIofProject*[]{PI1}].\par
Following group: \getPIofProject*{PI1}{ followed}.\par
\begingroup
\ExplSyntaxOn
\bool_set_true:N \l_@@_class_fastcompile_project_bool
\ExplSyntaxOff
Fast: \getPIofProject*{PI3}.\par
\endgroup

% Use the same destination helper as the PI table. Keep targets on a separate
% page so a PDF check can distinguish working links from fallback destinations.
\clearpage
\section*{PI table link targets}
\ExplSyntaxOn
\clist_map_inline:nn {pi-test-a,pi-test-b,pi-test-c,pi-test-d}
  {\@@_pi_target:n {#1} PI~target~#1\par}
\ExplSyntaxOff

% Exercise real project heads/tails in normal and both fast-publication modes.
% An ending administrative project keeps the fixture's heading self-contained.
\clearpage
\begingroup
\addEntry{project}{id={A90},number={A90},name={Project setup scope test},
  project-type={admin},project-status={E},ref-person-id={}}
\addEntry{project}{id={A91},number={A91},name={Continuing setup scope test},
  project-type={admin},project-status={C},ref-person-id={}}
\addEntry{project}{id={A92},number={A92},name={Legacy ending scope test},
  project-type={admin},project-status={E},ref-person-id={}}
\DTLnewdb{project-scope-test}
\ExplSyntaxOn
\int_new:N \l_@@_project_setup_test_group_int
\tl_new:N \l_@@_project_setup_test_error_tl
\cs_set:Npn \ProjectSetupMarker {outside}
\cs_set:Npn \ProjectSetupExpectedTitle {shortjournal}
\changeSettings{journalTitle=journaltitle,animalHousing@mouse=0.85,
  emphasizeAuthors=false,emphasizeEntries=true}
% This fixture switches between normal and fast modes within one document.
\bool_gset_true:N \g_@@_fast_project_started_bool
\cs_new_eq:NN \@@_project_setup_test_original_head:n \@@_print_project_head:n
\cs_set_protected:Npn \@@_print_project_head:n #1
{
  \str_if_eq:eeF {\getValue{journalTitle}} {\ProjectSetupExpectedTitle}
    {\PackageError{project-setup-test}{Settings~were~not~applied~before~the~head}{}}
  \@@_project_setup_test_original_head:n {#1}
}
\cs_new_protected:Npn \@@_project_setup_test_restored:
{
  \str_if_eq:eeF {\getValue{journalTitle}} {journaltitle}
    {\PackageError{project-setup-test}{Journal~setting~escaped~the~project}{}}
  \fp_compare:nNnF {\getValue{animalHousing@mouse}} = {0.85}
    {\PackageError{project-setup-test}{Funding~rate~escaped~the~project}{}}
  \str_if_eq:eeF {\ProjectSetupMarker} {outside}
    {\PackageError{project-setup-test}{Setup~code~escaped~the~project}{}}
  \str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {false/true}
    {\PackageError{project-setup-test}{Project~emphasis~escaped~its~scope}{}}
  \int_compare:nNnF {\currentgrouplevel} = {\l_@@_project_setup_test_group_int}
    {\PackageError{project-setup-test}{Project~scope~left~an~unbalanced~group}{}}
  \int_compare:nNnF {\value{refsection}} = {0}
    {\PackageError{project-setup-test}{Project~refsection~was~not~closed}{}}
}
\cs_new_protected:Npn \@@_project_setup_test:nnn #1#2#3
{
  \group_begin:
  \bool_set_false:N \l_@@_class_fastcompile_project_bool
  \bool_set_true:N \l_@@_class_fastcompile_project_show_publications_bool
  \str_case:nn {#1}
  {
    {fast-publications}
      {\bool_set_true:N \l_@@_class_fastcompile_project_bool}
    {fast-text}
      {\bool_set_true:N \l_@@_class_fastcompile_project_bool
       \bool_set_false:N \l_@@_class_fastcompile_project_show_publications_bool}
    {fast-text-legacy-tail}
      {\bool_set_true:N \l_@@_class_fastcompile_project_bool
       \bool_set_false:N \l_@@_class_fastcompile_project_show_publications_bool}
  }
  \int_set:Nn \l_@@_project_setup_test_group_int {\currentgrouplevel}
  \resetThumbIndex
  \printProject[
    \changeSettings{journalTitle=shortjournal,animalHousing@mouse=1.25}
    \def\ProjectSetupMarker{inside}
  ]{{Head}{#2}}
  \str_if_eq:eeF {\getValue{journalTitle}} {shortjournal}
    {\PackageError{project-setup-test}{Journal~setting~did~not~reach~the~body}{}}
  \fp_compare:nNnF {\getValue{animalHousing@mouse}} = {1.25}
    {\PackageError{project-setup-test}{Funding~rate~did~not~reach~the~body}{}}
  \str_if_eq:eeF {\ProjectSetupMarker} {inside}
    {\PackageError{project-setup-test}{Setup~code~did~not~reach~the~body}{}}
  \str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {true/false}
    {\PackageError{project-setup-test}{Ending~project~defaults~were~not~applied}{}}
  \bool_if:NF \l_@@_class_fastcompile_project_bool
    {\addEntry[person]{project-scope-test}{id={#1},lastname={Survives}}}
  Project~setup~case:~#1.\par
  #3
  \@@_project_setup_test_restored:
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \int_compare:nNnF {\l_thumb_index_int} = {1}
      {\PackageError{project-setup-test}{Thumb-index~progress~was~lost}{}}
  }
  \bool_if:NF \l_@@_class_fastcompile_project_bool
  {
    \DTLgetvalueforkey{\ProjectSetupStoredValue}{lastname}{project-scope-test}{id}{#1}
    \str_if_eq:eeF {\ProjectSetupStoredValue} {Survives}
      {\PackageError{project-setup-test}{Project~database~entry~was~lost}{}}
  }
  \typeout{PROJECT~SETUP~TEST~PASS:~#1}
  \group_end:
}
\@@_project_setup_test:nnn {normal} {A90} {\printProject{{Tail}}}
\@@_project_setup_test:nnn {normal-legacy-tail} {A92} {\printProjectTail}
\@@_project_setup_test:nnn {fast-publications} {A90} {\printProject{{Tail}}}
\@@_project_setup_test:nnn {fast-text} {A90} {\printProject{{Tail}}}
\@@_project_setup_test:nnn {fast-text-legacy-tail} {A90} {\printProjectTail}

\bool_set_true:N \l_@@_class_fastcompile_project_bool
\bool_set_false:N \l_@@_class_fastcompile_project_show_publications_bool
\cs_set:Npn \ProjectSetupExpectedTitle {journaltitle}
\int_set:Nn \l_@@_project_setup_test_group_int {\currentgrouplevel}
\printProject[]{{Head}{A90}}
\changeSettings{journalTitle=shortjournal}
\printProject{{Tail}}
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~empty-setup}
\printProject{{Head}{A90}}
\str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {true/false}
  {\PackageError{project-setup-test}{Unadorned~ending~head~missed~its~defaults}{}}
\printProject{{Tail}}
\@@_project_setup_test_restored:
\printProjectHead{A90}
\str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {true/false}
  {\PackageError{project-setup-test}{Legacy~ending~head~missed~its~defaults}{}}
\printProjectTail
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~ending-defaults}
\printProject{{Head}{A91}}
\str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {false/true}
  {\PackageError{project-setup-test}{Continuing~head~changed~global~emphasis}{}}
\printProject{{Tail}}
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~continuing-defaults}
\printProject[
  \changeSettings{emphasizeAuthors=false,emphasizeEntries=true}
]{{Head}{A90}}
\str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {false/true}
  {\PackageError{project-setup-test}{Explicit~ending~override~did~not~win}{}}
\printProject{{Tail}}
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~ending-override}
\printProjectHead[
  \changeSettings{emphasizeAuthors=true,emphasizeEntries=false}
]{A91}
\str_if_eq:eeF {\getValue{emphasizeAuthors}/\getValue{emphasizeEntries}} {true/false}
  {\PackageError{project-setup-test}{Legacy~head~setup~was~not~applied}{}}
\printProjectTail
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~legacy-head-setup}

% Invalid calls must report the error without executing setup or opening groups.
\cs_new_protected:Npn \@@_project_setup_test_error:nn #1#2
{
  \tl_clear:N \l_@@_project_setup_test_error_tl
  \group_begin:
  \cs_set_protected:Npn \PackageError ##1##2##3
    {\tl_gset:Nn \l_@@_project_setup_test_error_tl {##2}}
  #2
  \group_end:
  \tl_if_empty:NT \l_@@_project_setup_test_error_tl
    {\PackageError{project-setup-test}{Missing~diagnostic~for~#1}{}}
  \@@_project_setup_test_restored:
  \typeout{PROJECT~SETUP~TEST~PASS:~#1}
}
\@@_project_setup_test_error:nn {invalid-head}
  {\printProject[\def\ProjectSetupMarker{unexpected}]{{Head}{}}}
\@@_project_setup_test_error:nn {invalid-part}
  {\printProject[\def\ProjectSetupMarker{unexpected}]{{Other}{A90}}}
\@@_project_setup_test_error:nn {setup-on-tail}
  {\printProject[\def\ProjectSetupMarker{unexpected}]{{Tail}}}
\printProject[]{{Head}{A90}}
\tl_clear:N \l_@@_project_setup_test_error_tl
\cs_set_eq:NN \ProjectSetupSavedPackageError \PackageError
\cs_set_protected:Npn \PackageError #1#2#3
  {\tl_set:Nn \l_@@_project_setup_test_error_tl {#2}}
\printProject[\def\ProjectSetupMarker{unexpected}]{{Head}{A90}}
\cs_set_eq:NN \PackageError \ProjectSetupSavedPackageError
\tl_if_empty:NT \l_@@_project_setup_test_error_tl
  {\PackageError{project-setup-test}{Missing~nested-project~diagnostic}{}}
\str_if_eq:eeF {\ProjectSetupMarker} {outside}
  {\PackageError{project-setup-test}{Nested~project~setup~was~executed}{}}
\printProject{{Tail}}
\@@_project_setup_test_restored:
\typeout{PROJECT~SETUP~TEST~PASS:~nested-head}
\ExplSyntaxOff
\endgroup
\end{document}
%    \end{macrocode}
% \iffalse
%</test-command-options>
%<*test-participating-institutions>
% \fi
% \subsection{Participating-institution layout regression test}
% Assert the width and complete, ordered content of the rendered institution
% groups. Shared PI institutions must appear once, inactive/non-PI institutions
% must be absent, and options must not leak into the next list.
%    \begin{macrocode}
\documentclass[english,final=true]{dfg-crc}

\ExplSyntaxOn
\seq_new:N \g_@@_institutions_test_seen_seq
\dim_new:N \l_@@_institutions_test_width_dim
\NewDocumentCommand{\TestInstitutionName}{m}
{
  \dim_compare:nNnT
    {\dim_abs:n {\linewidth-\l_@@_institutions_test_width_dim}} > {.1pt}
  {
    \PackageError{institutions-test}
      {Wrong~column~width~for~#1:~\the\linewidth}
      {The~list~did~not~honour~its~column~count~or~column~gap.}
  }
  \seq_gput_right:Nn \g_@@_institutions_test_seen_seq {#1}
  Institute~#1
}
\AddToHook{env/multicols/before}
{
  \dim_compare:nNnT {\lastskip} < {\medskipamount}
    {\PackageError{institutions-test}{Missing~space~above~columns}{}}
}
\NewDocumentCommand{\TestInstitutionList}{m m m m +m}
{
  \clearpage
  \section*{#1}
  \seq_gclear:N \g_@@_institutions_test_seen_seq
  \dim_set:Nn \l_@@_institutions_test_width_dim
    {(\linewidth-\dim_eval:n{#3}*\int_eval:n{#2-1})/#2}
  #5
  \tl_set:Ne \l_tmpa_tl
    {\seq_use:Nn \g_@@_institutions_test_seen_seq {,}}
  \tl_if_eq:NnF \l_tmpa_tl {#4}
  {
    \PackageError{institutions-test}
      {Unexpected~institutions~in~#1:~\l_tmpa_tl}
      {Check~filtering,~duplicate~removal,~sorting,~and~option~scoping.}
  }
  \typeout{INSTITUTIONS~TEST~PASS:~#1}
}
\ExplSyntaxOff

\newcommand{\TestInstitution}[2]{%
  \addEntry{institution}{
    id={#1},name={\TestInstitutionName{#1}},ref-affiliation-id={#2}
  }%
}

\begin{document}
\DTLcleardb{affiliation}
\DTLcleardb{institution}
\DTLcleardb{person}

\addEntry{affiliation}{id={z},name={Zeta University},location={Zeta City}}
\addEntry{affiliation}{id={a},name={Alpha University},location={Alpha City}}
\addEntry{affiliation}{id={b},name={Beta University},location={Beta City}}
\addEntry{affiliation}{id={unused},name={Unused University},location={Unused City}}
\TestInstitution{Z1}{z}
\TestInstitution{Z2}{z}
\TestInstitution{Z3}{z}
\TestInstitution{Z4}{z}
\TestInstitution{Z5}{z}
\TestInstitution{Z6}{z}
\TestInstitution{A1}{a}
\TestInstitution{B1}{b}
\TestInstitution{INACTIVE}{unused}
\TestInstitution{NONPI}{unused}
\addEntry{person}{
  id={active},role={PI},period={1,2,3},
  ref-institution-id={Z1,Z2,Z3,Z4,Z5,Z6,A1,B1,Z1}
}
\addEntry{person}{
  id={shared},role={PI},period={1,2,3},ref-institution-id={Z1,A1}
}
\addEntry{person}{
  id={inactive},role={PI},period={1},ref-institution-id={INACTIVE}
}
\addEntry{person}{
  id={manager},role={manager},period={1,2,3},ref-institution-id={NONPI}
}

\TestInstitutionList{flow-two}{2}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList[columns=2]{ParticipatingInstitutions}}
\TestInstitutionList{flow-three-alpha}{3}{16pt}{A1,B1,Z1,Z2,Z3,Z4,Z5,Z6}
  {\printList[columns=3,column sep=16pt,order=alpha]{ParticipatingInstitutions}}
\TestInstitutionList{raster-two}{2}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList[raster columns=2]{ParticipatingInstitutions}}
\TestInstitutionList{raster-three}{3}{16pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList[raster columns=3,raster column skip=16pt]{ParticipatingInstitutions}}
\TestInstitutionList{legacy-alpha}{2}{12pt}{A1,B1,Z1,Z2,Z3,Z4,Z5,Z6}
  {\printList[columns=2]{{ParticipatingInstitutions}}[alpha]}
\TestInstitutionList{leading-order-wins}{2}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList[columns=2,order=count]{{ParticipatingInstitutions}}[alpha]}
\TestInstitutionList{default-reset}{1}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList{ParticipatingInstitutions}}
\TestInstitutionList{flow-after-text}{2}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {Introductory text.\printList[columns=2]{ParticipatingInstitutions}}
\TestInstitutionList{flow-one}{1}{12pt}{Z1,Z2,Z3,Z4,Z5,Z6,A1,B1}
  {\printList[columns=1]{ParticipatingInstitutions}}
\DTLcleardb{person}
\TestInstitutionList{empty-list}{2}{12pt}{}
  {\printList[columns=2]{ParticipatingInstitutions}}

\end{document}
%    \end{macrocode}
% \iffalse
%</test-participating-institutions>
%<*test-workpackage-references>
% \fi
% \subsection{Nested work-package reference test}
% This focused test creates repeated child-counter values under three parent
% work packages.  It catches both loss of later references during sorting and
% ranges that incorrectly cross a parent boundary.
%    \begin{macrocode}
%% Compile from the generated local directory with:
%%   latexmk -lualatex -g -halt-on-error test-workpackage-references.tex
\documentclass[
  fastcompile-project = true,
  fastcompile-project-show-images = false,
  english
]{dfg-crc}

\begin{document}

\ExplSyntaxOn
\tl_set:Nn \l__tmp_current_project_tl {WPTEST}
\ExplSyntaxOff

\begin{workpackages}
  \addWP{wp1}{name={Parent one}}
  Parent one.
  \begin{workpackages}
    \addWP{wp1a}{} Child 1a.
    \addWP{wp1b}{} Child 1b.
    \addWP{wp1c}{} Child 1c.
    \addWP{wp1d}{} Child 1d.
  \end{workpackages}

  \addWP{wp2}{name={Parent two}}
  Parent two.
  \begin{workpackages}
    \addWP{wp2a}{} Child 2a.
    \addWP{wp2b}{} Child 2b.
  \end{workpackages}

  \addWP{wp3}{name={Parent three}}
  Parent three.
  \begin{workpackages}
    \addWP{wp3a}{} Child 3a.
    \addWP{wp3b}{} Child 3b.
    \addWP{wp3c}{} Child 3c.
  \end{workpackages}
\end{workpackages}

\noindent Range result:
\getWP{wp1b,wp1c,wp1d,wp2b,wp3c}.

\noindent Unordered result:
\getWP{wp2b,wp3c,wp1d}.


\noindent Mixed result:
\getWP{wp1a,wp1b,wp2,wp3a,wp3b}.

\noindent Reversed mixed:
\getWP{wp3b,wp2,wp1a,wp3a,wp1b}.

\noindent Parent and children:
\getWP{wp1,wp1a,wp1b,wp1c,wp2,wp2a,wp2b,wp3}.

\noindent Parent range:
\getWP{wp1,wp2,wp3}.

\end{document}
%    \end{macrocode}
% \iffalse
%</test-workpackage-references>
%<*test-workpackage-metadata>
% \fi
% \subsection{Work-package metadata compatibility test}
% This fixture checks stored raw fields, precedence, explicit empty values,
% deferred expansion and mixed old/new declarations in three compilation modes.
% Rendered headings, nested references and late-bound chart labels are also
% checked by the test target.
%    \begin{macrocode}
%% Run make test-workpackage-metadata for normal, focused/image and focused/text.
\providecommand*\WPTestMode{normal}
\ExplSyntaxOn
\str_if_eq:eeT {\WPTestMode}{normal}
  {\PassOptionsToClass{final=true}{dfg-crc}}
\str_if_eq:eeF {\WPTestMode}{normal}
  {\PassOptionsToClass{fastcompile-project=true}{dfg-crc}}
\str_if_eq:eeT {\WPTestMode}{images}
  {\PassOptionsToClass{fastcompile-project-show-images=true}{dfg-crc}}
\str_if_eq:eeT {\WPTestMode}{text}
  {\PassOptionsToClass{fastcompile-project-show-images=false}{dfg-crc}}
\ExplSyntaxOff
\documentclass[english]{dfg-crc}
\newcommand*\WPTitleToken{Deferred heading}
\newcommand*\WPLabelToken{Original deferred label}
\ExplSyntaxOn
\int_new:N \g_wp_test_checks_int
\tl_new:N \l_wp_test_value_tl
\NewDocumentCommand \WPCheck {m m m}
  {
    \str_if_eq:eeF {\WPTestMode}{text}
      {
        \DTLgetvalueforkey{\l_wp_test_value_tl}{#2}{gantt-WPTEST}{id}{#1}
        \tl_if_eq:NnF \l_wp_test_value_tl {#3}
          {\PackageError{wp-test}{Wrong~#2~for~#1}{Expected~unexpanded~#3.}}
        \int_gincr:N \g_wp_test_checks_int
      }
  }
\NewDocumentCommand \WPCheckEmpty {m m}
  {
    \str_if_eq:eeF {\WPTestMode}{text}
      {
        \DTLgetvalueforkey{\l_wp_test_value_tl}{#2}{gantt-WPTEST}{id}{#1}
        \DTLifnullorempty{\l_wp_test_value_tl}{}
          {\PackageError{wp-test}{Unexpected~#2~for~#1}{Expected~empty~or~absent.}}
        \int_gincr:N \g_wp_test_checks_int
      }
  }
\ExplSyntaxOff
\begin{document}
\ExplSyntaxOn
\tl_set:Nn \l__tmp_current_project_tl {WPTEST}
\ExplSyntaxOff
\begin{workpackages}
  \addWP{legacy}{name={LEGACY HEADING},description={Shared label},
    periodStart=1,periodEnd=6,style=alternative}
  Legacy declaration.
  \WPCheck{legacy}{name}{LEGACY HEADING}
  \WPCheck{legacy}{description}{Shared label}
  \WPCheck{legacy}{periodStart}{1}\WPCheck{legacy}{periodEnd}{6}
  \WPCheck{legacy}{style}{alternative}
  \addWP{grouped}{title={GROUPED HEADING},gantt={label={Shared label},
    start=1,end=6,style=alternative}}
  Grouped declaration.
  \WPCheck{grouped}{name}{GROUPED HEADING}
  \WPCheck{grouped}{description}{Shared label}
  \WPCheck{grouped}{periodStart}{1}\WPCheck{grouped}{periodEnd}{6}
  \WPCheck{grouped}{style}{alternative}
  \addWP{new-first}{title={NEW FIRST HEADING},
    gantt={label={Preferred label A},start=2,end=5,style=important},
    name={STALE HEADING A},description={STALE LABEL A},
    periodStart=1,periodEnd=16,style=bad}
  New keys precede their legacy counterparts.
  \WPCheck{new-first}{name}{NEW FIRST HEADING}
  \WPCheck{new-first}{description}{Preferred label A}
  \WPCheck{new-first}{periodStart}{2}\WPCheck{new-first}{periodEnd}{5}
  \WPCheck{new-first}{style}{important}
  \addWP{old-first}{name={STALE HEADING B},description={STALE LABEL B},
    periodStart=1,periodEnd=16,style=bad,title={OLD FIRST HEADING},
    gantt={label={Preferred label B},start=4,end=9,style=striped}}
  Legacy keys precede their replacements.
  \WPCheck{old-first}{name}{OLD FIRST HEADING}
  \WPCheck{old-first}{description}{Preferred label B}
  \WPCheck{old-first}{periodStart}{4}\WPCheck{old-first}{periodEnd}{9}
  \WPCheck{old-first}{style}{striped}
  \addWP{fallback}{title={TITLE FALLBACK HEADING},gantt={start=3,end=8}}
  Omitted label uses the title.
  \WPCheck{fallback}{name}{TITLE FALLBACK HEADING}
  \WPCheck{fallback}{description}{TITLE FALLBACK HEADING}
  \WPCheck{fallback}{style}{default}
  \addWP{empty-label}{title={EMPTY LABEL HEADING},
    gantt={label={},start=2,end=7},description={STALE EMPTY LABEL},
    style=alternative}
  An explicitly empty label wins; the legacy style is retained.
  \WPCheckEmpty{empty-label}{description}
  \WPCheck{empty-label}{style}{alternative}
  \addWP{legacy-missing}{name={LEGACY MISSING LABEL},periodStart=1,periodEnd=5}
  An old declaration does not acquire a title fallback.
  \WPCheckEmpty{legacy-missing}{description}
  \WPCheckEmpty{legacy-missing}{style}
  \addWP{legacy-empty}{name={LEGACY EMPTY LABEL},description={},
    periodStart=1,periodEnd=5,style={}}
  An old empty label stays empty.
  \WPCheckEmpty{legacy-empty}{description}
  \WPCheck{legacy-empty}{style}{default}
  \addWP{partial}{title={PARTIAL MIGRATION HEADING},
    description={Legacy short label},periodStart=4,periodEnd=8,style=crosshatch}
  A legacy description takes precedence over the title fallback.
  \WPCheck{partial}{description}{Legacy short label}
  \WPCheck{partial}{periodStart}{4}\WPCheck{partial}{periodEnd}{8}
  \WPCheck{partial}{style}{crosshatch}
  \addWP{empty-title}{name={STALE EMPTY TITLE},title={},
    gantt={label={},start=5,end=5}}
  Empty title overrides the legacy name. Equal endpoints omit the chart row.
  \WPCheckEmpty{empty-title}{name}\WPCheckEmpty{empty-title}{description}
  \WPCheck{empty-title}{periodStart}{5}\WPCheck{empty-title}{periodEnd}{5}
  \addWP{repeated}{title={STALE REPEATED TITLE},title={REPEATED HEADING},
    gantt={label={STALE REPEATED LABEL},start=1,end=4},
    gantt={label={Repeated label},start=3,style={}}}
  Repeated new assignments use the last value and keep other fields.
  \WPCheck{repeated}{name}{REPEATED HEADING}
  \WPCheck{repeated}{description}{Repeated label}
  \WPCheck{repeated}{periodStart}{3}\WPCheck{repeated}{periodEnd}{4}
  \WPCheck{repeated}{style}{default}
  \addWP{tokens}{title={\WPTitleToken},
    gantt={label={\WPLabelToken},start=6,end=12}}
  Formatting commands and labels are stored without expansion.
  \WPCheck{tokens}{name}{\WPTitleToken}
  \WPCheck{tokens}{description}{\WPLabelToken}
  \begin{workpackages}
    \addWP{child}{title={HIDDEN CHILD TITLE},
      gantt={label={Nested chart label},start=8,end=10}}
    Nested body starts here.
    \WPCheck{child}{name}{HIDDEN CHILD TITLE}
    \WPCheck{child}{description}{Nested chart label}
  \end{workpackages}
\end{workpackages}
\renewcommand*\WPLabelToken{UPDATED DEFERRED LABEL}
\noindent Nested reference: \getWP{tokens,child}.
\ExplSyntaxOn
\str_if_eq:eeTF {\WPTestMode}{text}
  {
    \DTLifdbexists{gantt-WPTEST}
      {\PackageError{wp-test}{Focused~text~mode~created~a~Gantt~database}{}}{}
  }
  {
    \int_compare:nNnF {\g_wp_test_checks_int}>{40}
      {\PackageError{wp-test}{Too~few~metadata~checks}{}}
    % Direct low-level callers retain the old schema and validation.
    \addEntry[gantt]{WPDirect}{id=direct,name={Direct~title},
      description={Direct~label},periodStart=1,periodEnd=4,style=default}
    \DTLgetvalueforkey{\l_wp_test_value_tl}{description}{WPDirect}{id}{direct}
    \tl_if_eq:NnF \l_wp_test_value_tl {Direct~label}
      {\PackageError{wp-test}{Direct~Gantt~declaration~changed}{}}
    \int_gincr:N \g_wp_test_checks_int
    \clearpage
    \dfgGanttEnvironment{WPTEST}
  }
\typeout{WP~METADATA~TEST~PASS:~\WPTestMode,~\int_use:N\g_wp_test_checks_int~stored-field~checks}
\ExplSyntaxOff
\end{document}
%    \end{macrocode}
% \iffalse
%</test-workpackage-metadata>
%<*test-existing-funds-direct-costs>
% \fi
% \subsection{Existing direct-cost overview test}
% This focused two-pass test prints section 2.1.1 before declaring the
% project-level rows.  On the following run, the auxiliary-file mirror must
% restore those rows early enough for the table and the assertions.
%    \begin{macrocode}
%% Compile from the generated local directory with:
%%   latexmk -lualatex -g -halt-on-error test-existing-funds-direct-costs.tex
\documentclass[english,final=true]{dfg-crc}

\providecommand{\dfgDirectCostsAuxReady}{0}

%% Ending-period values remain explicit because they describe the preceding
%% funding period rather than the project requests below.
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year=1, applicant=4300, participant=1200, other-funds=500
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year=2, applicant=0, participant=0, other-funds=0
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year=3, applicant=0, participant=0, other-funds=0
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year=4, applicant=0, participant=0, other-funds=0
}
\addEntry[funding]{PreviousExistingFundsDirectCosts}{
  year=5, applicant=0, participant=0, other-funds=0
}

\begin{document}

\section*{Overview of existing funds for direct costs}

%% The second and later passes must see the rows restored from the auxiliary
%% file before the live project declarations below are encountered.
\ifnum\dfgDirectCostsAuxReady=1\relax
  \ExplSyntaxOn
  \cs_set_eq:NN
    \@@_direct_costs_test_show_saved:nnN
    \@@_show_calculated_number:nnN
  \cs_set_protected:Npn
    \@@_show_calculated_number:nnN #1#2#3 { }
  \cs_new_protected:Npn \@@_direct_costs_test_expect:nnn #1#2#3
  {
    \getSumRequestedFundingDirectCosts
      [RequestedAndExistingFundingDirectCostsOverview]{#1}{#2}
    \DTLconverttodecimal {\SumRequestedFundingDirectCosts} \l_tmpa_tl
    \fp_compare:nNnF {\l_tmpa_tl} = {#3}
    {
      \PackageError{direct-costs-test}
        {Expected~#1/#2~sum~#3,~got~\SumRequestedFundingDirectCosts}
        {The~section~2.1.1~overview~classification~is~incorrect.}
    }
  }
  \@@_direct_costs_test_expect:nnn {1}{applicant}{5000}
  \@@_direct_costs_test_expect:nnn {1}{participant}{2100}
  \@@_direct_costs_test_expect:nnn {1}{other-funds}{300}
  \@@_direct_costs_test_expect:nnn {1}{all}{7400}
  \@@_direct_costs_test_expect:nnn {all}{applicant}{25000}
  \@@_direct_costs_test_expect:nnn {all}{participant}{10500}
  \@@_direct_costs_test_expect:nnn {all}{other-funds}{1500}
  \@@_direct_costs_test_expect:nnn {all}{all}{37000}
  \cs_set_eq:NN
    \@@_show_calculated_number:nnN
    \@@_direct_costs_test_show_saved:nnN
  \iow_term:n
    {DIRECT~COSTS~TEST~PASS:~auxiliary~restore,~classification,~and~totals}
  \ExplSyntaxOff
\fi

\printTable{ExistingFundsDirectCosts}

%% These rows intentionally occur after the overview.  aff1 is the applicant
%% affiliation in the generated metadata; aff2 is a participating affiliation.
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {A01},
  ref-affiliation-id = {aff1},
  financed-by        = {Applicant university core support},
  sum = {
    year1 = {5000}, year2 = {5000}, year3 = {5000},
    year4 = {5000}, year5 = {5000}
  }
}
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {B01},
  ref-affiliation-id = {aff2},
  financed-by        = {Participating university core support},
  sum = {
    year1 = {2100}, year2 = {2100}, year3 = {2100},
    year4 = {2100}, year5 = {2100}
  }
}
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id     = {Q01},
  ref-affiliation-id = {other-funds},
  financed-by        = {External grant},
  sum = {
    year1 = {300}, year2 = {300}, year3 = {300},
    year4 = {300}, year5 = {300}
  }
}

%% Project fast mode must update existing-funds totals as well as the rows.
%% Keep this local so the normal-mode auxiliary overview remains unchanged.
\ExplSyntaxOn
\group_begin:
\cs_set_protected:Npn \@@_direct_costs_fast_expect:nnn #1#2#3
{
  \@@_funding_sum_set:Nnnnn \l_tmpa_tl
    {RequestedAndExistingFundingDirectCosts}{#1}{__ALL__}{#2}
  \fp_compare:nNnF {\l_tmpa_tl} = {#3}
  {
    \PackageError{direct-costs-test}
      {Expected~#1/#2~sum~#3,~got~\l_tmpa_tl}
      {Existing~direct-cost~totals~must~match~the~project~rows.}
  }
}
%% Normal-mode rows above must still be counted exactly once.
\@@_direct_costs_fast_expect:nnn {A01}{sum-year1}{5000}
\bool_set_true:N \l_@@_class_fastcompile_project_bool
\bool_set_true:N \l_@@_class_fastcompile_project_show_funding_tables_bool
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id={FASTTEST}, ref-affiliation-id={aff1}, financed-by={Test},
  sum={year1=1000,year2=1000,year3=1000,year4=1000,year5=1000}
}
\clist_map_inline:nn {sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}
  { \@@_direct_costs_fast_expect:nnn {FASTTEST}{#1}{1000} }
\@@_direct_costs_fast_expect:nnn {FASTTEST}
  {sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}{5000}
%% A second entry adds to the same project without affecting other projects.
\addEntry[funding]{RequestedAndExistingFundingDirectCosts}{
  ref-project-id={FASTTEST}, ref-affiliation-id={aff1}, financed-by={Test},
  sum={year1=200,year2=200,year3=200,year4=200,year5=200}
}
\@@_direct_costs_fast_expect:nnn {FASTTEST}{sum-year1}{1200}
\@@_direct_costs_fast_expect:nnn {FASTTEST}
  {sum-year1,sum-year2,sum-year3,sum-year4,sum-year5}{6000}
\@@_direct_costs_fast_expect:nnn {A01}{sum-year1}{5000}
\iow_term:n {FAST~DIRECT~COSTS~TEST~PASS:~yearly~and~combined~totals}
\group_end:
\ExplSyntaxOff

\makeatletter
\protected@write\@auxout{}{%
  \string\gdef\string\dfgDirectCostsAuxReady{1}}
\makeatother

\end{document}
%    \end{macrocode}
% \iffalse
%</test-existing-funds-direct-costs>
%<*cv>
% \fi
% Starting now a template CV file.
%    \begin{macrocode}
\documentclass[english,cv]{dfg-crc}
\begin{document}
\input{content/00_titlepage}
\dfgCVsection
% %% \dfgCV{MM}
\end{document}
%    \end{macrocode}
% \iffalse
%</cv>
%</file>
% \fi
% \printindex
%\endinput
