code: def finalize(doc):
      
      if doc.plot_found:
          pgfplots_inline = pf.MetaInlines(pf.RawInline(
              r'''%
  \makeatletter
  \@ifpackageloaded{pgfplots}{}{\usepackage{pgfplots}}
  \makeatother
  \usepgfplotslibrary{groupplots}
  ''', format='tex'))
          try:
              doc.metadata['header-includes'].append(pgfplots_inline)
          except KeyError:
              doc.metadata['header-includes'] = pf.MetaList(pgfplots_inline)
  
      if doc.caption_found:
          caption_inline = pf.MetaInlines(pf.RawInline(
              r'''%
  \makeatletter
  \@ifpackageloaded{caption}{}{\usepackage{caption}}
  \@ifpackageloaded{cleveref}{}{\usepackage{cleveref}}
  \@ifundefined{codelisting}{%
      \DeclareCaptionType{codelisting}[Code Listing][List of Code Listings]
      \crefname{codelisting}{code listing}{code listings}
      \Crefname{codelisting}{Code Listing}{Code Listings}
      \captionsetup[codelisting]{position=bottom}
  }{}
  \makeatother
  ''', format='tex'))
          try:
              doc.metadata['header-includes'].append(caption_inline)
          except KeyError:
              doc.metadata['header-includes'] = pf.MetaList(caption_inline)
docs: Adds the pgfplots and caption packages to the header-includes if needed.