Skip to content

Supporting file are cleanup to soon when using multiformat #8373

Open

Description

@Sciemon

Bug description

An mwe can be found in the github repo
https://github.com/Sciemon/issue_figures_folder

Somehow latex assumes the figures are in a 'mediabag' folder that does not exist.

Steps to reproduce

It is only possible to render (with quarto render ...) the file 'model_requirements.qmd' if 'docx: default' is deleted from the yaml.

Expected behavior

if 'docx: default' is deleted, the pdf is rendered

Actual behavior

Otherwise latex throws the following error:

ERROR:
compilation failed- error
Unable to load picture or PDF file 'model_requirements_files/mediabag/figs/SVS_droop.pdf'.

}
l.373 ...ements_files/mediabag/figs/SVS_droop.pdf}###

Your environment

  • IDE: VSCode 1.85.2
  • OS: Windows 10

Quarto check output

Quarto 1.4.545
[>] Checking versions of quarto binary dependencies...
Pandoc version 3.1.11: OK
Dart Sass version 1.69.5: OK
Deno version 1.37.2: OK
[>] Checking versions of quarto dependencies......OK
[>] Checking Quarto installation......OK
Version: 1.4.545
Path: C:\Program Files\Quarto\bin
CodePage: 1252

[>] Checking tools....................OK
TinyTeX: v2024.01
Chromium: (not installed)

[>] Checking LaTeX....................OK
Using: TinyTex
Path: C:\Users\seberlein\AppData\Roaming\TinyTeX\bin\windows
Version: 2023

[>] Checking basic markdown render....OK

[>] Checking Python 3 installation....OK
Version: 3.11.7
Path: C:/Users/seberlein/AppData/Local/Programs/Python/Python311/python.exe
Jupyter: 5.7.1
Kernels: python3

(-) Checking Jupyter engine render....Traceback (most recent call last):
File "C:\Program Files\Quarto\share\jupyter\jupyter.py", line 21, in
from notebook import notebook_execute, RestartKernel
File "C:\Program Files\Quarto\share\jupyter\notebook.py", line 14, in
from yaml import safe_load
ModuleNotFoundError: No module named 'yaml'
[>] Checking Jupyter engine render....OK

Activity

  1. added
    bug
    on Jan 21, 2024
  2. added this to the v1.5 milestone on Jan 21, 2024
  3. self-assigned this
    on Jan 22, 2024
  4. added
    docx
    latex
    on Jan 24, 2024
  5. removed
    latex
    docx
    on Mar 5, 2024
  6. cderv commented on Mar 5, 2024

    @cderv
    Member

    Some context about the issue.

    This is similar to this one

    but happens with mediabag supporting files and with output file name conflict.

    Overall issue is order of cleanup for supporting files

    I am putting back what I shared there at #6705 (comment) by adapting to this use case.

    • Cleanup code is in renderCleanup()

      // if we aren't keeping the markdown or text and we are instructed to
      // clean supporting files then do it
      if (
      !format.execute[kKeepMd] &&
      !format.render[kKeepTex] &&
      !format.render[kKeepTyp] &&
      supporting
      ) {

      we are cleanup supporting file in some situations and this happens with docx format.

    • We cleanup the whole directory and not just the file associated to the format

      // ammend supporting with mediabag if it exists
      // (we can always delete the mediabag because it is generated by filters)
      const mediabagDir = join(dirname(input), filesDirMediabagDir(input));
      if (existsSync(mediabagDir)) {
      supporting.push(mediabagDir);
      }

    • When rendering to --to all we pass through this 3 times, and not in the order I though.

      • Last format is called first. So docx cleanup will happen before PDF rendering.
      • Meaning that when PDF rendering happens, the shared resources is already deleted.

      onPostProcess: async (renderedFormats: RenderedFormat[]) => {
      let completion = renderCompletions.pop();
      while (completion) {
      renderedFiles.push(await completion.complete(renderedFormats));
      completion = renderCompletions.pop();
      }
      renderedFiles.reverse();
      },

    • If docx is called first, the cleaning step happens last. So PDF rendering can work ok.

    Try just putting docx first as a workaround

    diff --git a/model_requirements.qmd b/model_requirements.qmd
    index 522edb4..3f12bf1 100644
    --- a/model_requirements.qmd
    +++ b/model_requirements.qmd
    @@ -8,6 +8,7 @@ toc: true
     number-sections: true
     highlight-style: pygments
     format:
    +  docx: default
       pdf:
         geometry:
           - top=30mm
    @@ -17,7 +18,6 @@ format:
         html-math-method: katex
         default-image-extension: svg
         css: style.css
    -  docx: default
     ---

    Setting keep-md: true in the YAML as global, or just under docx format will also prevent the cleaning before PDF Rendering and should avoid the issue

    This is a topic we can deal with

    It will happen with any combination of formats mixing

    • Format that needs cleaning always (like docx)
    • And other that may or may not (like HTML and embed-resources) or PDF that needs supporting file for tex rendering.

    This would probably be the better options. @cscheid do you agree ?

  7. changed the title [-]pdf rendering works only if docx format is not specified[/-] [+]Supporting file are cleanup to soon when using multiformat[/+] on Mar 5, 2024
  8. modified the milestones: v1.5, Future on Jun 18, 2024
  9. cderv commented on Sep 11, 2024

    @cderv
    Member

    New use case I found:

    ---
    title: About 
    format: 
      typst: default
      typst+toc:
        toc: true
    ---
    
    # Header
    
    Content
    
    
    
    ❯ quarto render index.qmd
    pandoc
      to: typst
      output-file: index.typ
      standalone: true
      default-image-extension: svg
      wrap: none
      citeproc: false
    
    metadata
      title: About
    
    pandoc
      to: typst
      output-file: index.typ
      standalone: true
      default-image-extension: svg
      wrap: none
      citeproc: false
      toc: true
    
    metadata
      title: About
    
    [typst]: Compiling index.typ to index.pdf...DONE
    
    [typst]: Compiling index.typ to index.pdf...error: input file not found (searched at C:\Users\chris\Documents\DEV_OTHER\00-TESTS\test-quarto\index.typ)
    ERROR: Error
        at Object.complete (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/output-typst.ts:80:13)
        at eventLoopTick (ext:core/01_core.js:153:7)
        at async file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/render.ts:282:23
        at async withTimingAsync (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/core/timing.ts:50:20)
        at async Object.complete (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/render.ts:277:7)
        at async Object.onPostProcess (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/render-files.ts:720:28)
        at async renderFileInternal (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/render-files.ts:689:3)
        at async renderFiles (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/render-files.ts:325:9)
        at async renderProject (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/project.ts:441:23)
        at async Command.actionHandler (file:///C:/Users/chris/Documents/DEV_R/quarto-cli/src/command/render/cmd.ts:248:26)
    

    Adding keep-typ solves it

    format: 
      typst: default
      typst+toc:
        toc: true
        keep-typ: true
    

    So it is not possibly to use the variant format with Typst right now because of our rendering and cleaning process.

  10. cderv commented on Oct 1, 2024

    @cderv
    Member

    #10883 is another report involving docx cleaning before LaTeX rendering happens.

    ---
    title: "Quazz"
    format:
      pdf: default
      docx: default
    ---
    
    # Quazz
    
    This is a sumbol of a pie chart in SVG:
    
    ![Symbolic pie chart](./piechart.svg)
    
    That is it.
    

    With this svg to reproduce: piechart.svg

    Doing reverse order solves it

    format:
      docx: default
      pdf: default
  11. modified the milestones: Future, v1.6 on Oct 1, 2024
  12. modified the milestones: v1.6, v1.7 on Oct 31, 2024
  13. added
    files
    on Oct 31, 2024
  14. modified the milestones: v1.7, Future on Apr 7, 2025
  15. andrewheiss commented on May 11, 2026

    @andrewheiss

    Hi! Running into this again. I normally address this with the +variant trick and keeping the intermediate markdown file (following this #8373 (comment)), and it works:

    ---
    title: About 
    
    # This is necessary to keep intermediate files/folders hanging around when
    # rendering to the same output format (like two different PDFs)
    # https://github.com/quarto-dev/quarto-cli/issues/8373#issuecomment-1979245883
    keep-md: true
    
    format: 
      pdf: default
      pdf+toc:
        output-file: "testing-toc.pdf"
        toc: true
    ---
    
    # Header
    
    Content

    ↑ this creates two different PDFs with different names, one with a TOC and one without, as expected

    But with typst, it doesn't work (as noted here #8373 (comment))

    This with keep-md…

    ---
    title: About 
    keep-md: true
    format: 
      typst: default
      typst+toc:
        output-file: "testing-toc.pdf"
        toc: true
    ---
    
    # Header
    
    Content

    … causes this error:

    ERROR: NotFound: No such file or directory (os error 2): readfile 'testing.typ'
    Path: testing.typ
    

    Using keep-typ instead does allow both formats to render, but they're identical—in this case both PDFs have a TOC:

    ---
    title: About 
    keep-typ: true
    format: 
      typst: default
      typst+toc:
        output-file: "testing-toc.pdf"
        toc: true
    ---
    
    # Header
    
    Content

    Is there a different way to render two different typst formats like this?

  16. mcanouil commented on May 13, 2026

    @mcanouil
    Collaborator

    The error moved to the new Skylighting post-processor but the underlying ordering is the same as described before.

    Trace on issue.qmd with format: { typst: default, typst+toc: { toc: true } }:

    1. Both pandoc passes write to the same issue.typ (shared intermediate, no modifier-aware suffix).
    2. Completions drain "Last In, First Out", so typst+toc completes first: compiles issue.pdf, then safeRemoveSync(issue.typ).
    3. typst completion then runs its generic post-processors, which now try to read the already-removed issue.typ.

    Disambiguating output-file per format key when modifiers are present would also be needed to make the variant useful, in addition to the broader cleanup-ordering fix tracked in #6518.

    Relevant codes:

    • onRender: async (
      _format: string,
      executedFile: ExecutedFile,
      quiet: boolean,
      ) => {
      renderCompletions.push(await renderPandoc(executedFile, quiet));
      },
      onPostProcess: async (renderedFormats: RenderedFormat[]) => {
      let completion = renderCompletions.pop();
      while (completion) {
      renderedFiles.push(await completion.complete(renderedFormats));
      completion = renderCompletions.pop();
      }
      renderedFiles.reverse();
    • // run generic postprocessors
      const postProcessSupporting: string[] = [];
      const postProcessResources: string[] = [];
      if (pandocResult.postprocessors) {
      for (const postprocessor of pandocResult.postprocessors) {
      const result = await postprocessor(outputFile);
      if (result && result.supporting) {
      postProcessSupporting.push(...result.supporting);
      }
      if (result && result.resources) {
      postProcessResources.push(...result.resources);
      }
      }
      }
      let finalOutput: string;
      let selfContained: boolean;
      await withTimingAsync("postprocess-selfcontained", async () => {
      // ensure flags
      const flags = context.options.flags || {};
      // determine whether this is self-contained output
      finalOutput = recipe.output;
      // note that we intentionally call isSelfContainedOutput twice
      // the first needs to happen before recipe completion
      // because ingestion of self-contained output needs
      // to happen before recipe completion (which cleans up some files)
      selfContained = isSelfContainedOutput(
      flags,
      format,
      finalOutput,
      );
      if (selfContained && isHtmlFileOutput(format.pandoc)) {
      await pandocIngestSelfContainedContent(
      outputFile,
      format.pandoc[kResourcePath],
      );
      }
      // call complete handler (might e.g. run latexmk to complete the render)
      finalOutput = (await recipe.complete(pandocOptions)) || recipe.output;
    • // which we will then compile to a pdf and rename to .typ)
      const [inputDir, inputStem] = dirAndStem(input);
      const output = inputStem + ".typ";
    • // keep typ if requested
      if (!format.render[kKeepTyp]) {
      safeRemoveSync(typstInput);
      }
    • function skylightingPostProcessor(brandBgColor?: string) {
      // Match the entire #let Skylighting(...) = { ... } function.
      // The signature is stable and generated by Skylighting's Typst backend.
      const skylightingFnRe =
      /(#let Skylighting\(fill: none, number: false, start: 1, sourcelines\) = \{[\s\S]*?\n\})/;
      return async (output: string) => {
      const content = Deno.readTextFileSync(output);
      const match = skylightingFnRe.exec(content);
      if (!match) {
      // No Skylighting function found — document may not have code blocks,
      // or upstream changed the function signature. Nothing to patch.
      return;
      }
      let fn = match[1];
      // Fix block() call: add width, inset, radius
      fn = fn.replace(
      "block(fill: bgcolor, blocks)",
      "block(fill: bgcolor, width: 100%, inset: 8pt, radius: 2pt, blocks)",
      );
      // Override bgcolor with brand monospace-block background-color
      if (brandBgColor) {
      fn = fn.replace(
      /let bgcolor = rgb\("[^"]*"\)/,
      `let bgcolor = rgb("${brandBgColor}")`,
      );
      }
      if (fn !== match[1]) {
      Deno.writeTextFileSync(output, content.replace(match[1], fn));
      }
      };
    • if (!format.pandoc[kOutputFile]) {
      const [_dir, stem] = dirAndStem(file);
      format.pandoc[kOutputFile] = `${stem}.${format.render[kOutputExt]}`;
      }
    • function breakFormatString(
      formatStr: string,
      strict = true,
      ): FormatDescriptor | undefined {
      const firstEl = formatStr.split(/[+-]/)[0];
      if (isBuiltInFormat(firstEl)) {
      // Grab anything that could be a variant
      const variantMatches = formatStr.matchAll(/[\+\-]\S*?(?=\-|\+|$)/g);
      const variantCommands: string[] = [];
      for (const match of variantMatches) {
      variantCommands.push(match[0]);
      }
      // Group the items into variants and modifiers
      // variants are valid markdown variants
      // modifiers are gmail style `+` syntax to allow the same base format
      // to be used with varying options (e.g. pdf+draft, pdf+final)
      const variants: string[] = [];
      const modifiers: string[] = [];
      variantCommands.forEach((cmd) => {
      if (kPandocExtensions.includes(cmd)) {
      variants.push(cmd);
      } else {
      modifiers.push(cmd);
      }
      });
      return {
      baseFormat: firstEl,
      variants,
      modifiers,
      formatWithVariants: `${firstEl}${variants.join("")}`,
      };
      } else {
      if (strict) {
      return undefined;
      } else {
      return {
      baseFormat: formatStr,
      variants: [],
      modifiers: [],
      formatWithVariants: formatStr,
      };
      }
      }
      }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugfiles

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions