Skip to content

Feature Contribution: better automatic naming for tikz externalization #1421

@JSlote

Description

@JSlote

Hi TikZ community, in my recent papers I've been heavily using tikz externalize because there are tons of quantum circuit figures. I have encountered a general useability problem with the tikz externalize package though, and wanted to offer the solution that I've been using which seems to work quite well.

Problem: while using tikz-externalize, the automatic naming feature is unstable; it labels graphics by their order in the file, so if you are shuffling figures around they always get recompiled simply because the names get swapped--even if the contents of the figures stay the same. On the other hand, one can manually name each graphic but that can be quite exhausting.

Solution: give the figures a name derived from a hash of the code defining the figure. This has the dual advantages of (a) not requiring any manual intervention and (b) allows the cached version to continue to be reused even after reordering figures in the source.

Usage:

\autoname{
  \begin{tikzpicture}
  % drawing code here
  \end{tikzpicture}
}

Code:

\ExplSyntaxOn
% One scratch tl for the diagram code, one for the hash
\tl_new:N  \l__autotikz_code_tl
\tl_new:N  \l__autotikz_hash_tl

% \AutoTikz{ <code> }
\NewDocumentCommand \autoname { m }
 {
   % 1. Store the raw argument *verbatim* (no expansion)
   \tl_set:Nn \l__autotikz_code_tl { #1 }

   % 2. Compute MD5 on a *detokenized* snapshot (one expansion only)
   \tl_set:Nx \l__autotikz_hash_tl
     { \pdfmdfivesum { \detokenize \expandafter { \l__autotikz_code_tl } } }

   % 3. Tell TikZ to use that hash as the filename
   \tikzsetnextfilename { tikz-\l__autotikz_hash_tl }

   % 4. Finally typeset the diagram
   #1
 }
\ExplSyntaxOff

I would be very happy to contribute an (improved) version of the above as a naming option to tikz. Please let me know if and how I should do this. For example, I would guess the above actual implementation is quite amateurish and would be happy to make it better before sending a PR.

Thanks for such a wonderful software package.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions