# Get last value from \tikzsetnextfilename

I regularly use the pattern

\begin{figure}
\centering
\tikzsetnextfilename{<SOME-NAME>}
\begin{tikzpicture}
\subimport{.}{figures/<SOME-NAME>.tex}
\end{tikzpicture}
\label{fig:<SOME-NAME>}
\end{figure}


It so happens, that I forget to change the label fig:<SOME-NAME> when copy-pasting this code around. That's why I wondered, if there is the possibility to retrieve the value set with \tikzsetnextfilename so that

\label{fig:<SOME-NAME>}


could be changed to

\label{fig:\tikzgetnextfilename}


For a different use-case I would also like to get the value of \tikzsetexternalprefix for the import command.

EDIT: I extended my use-case in the sense that I would like to also use the variable to import the correct file.

EDIT2: I ended up using

\providecommand{\tikzfile}{}

...

\begin{figure}
\renewcommand{\tikzfile}{<SOME-NAME>}
\tikzsetnextfilename{\tikzfile}
\centering
\begin{tikzpicture}
\subimport{.}{figures/\tikzfile.tex}
\end{tikzpicture}%
\caption{This is the figure with name \tikzfile.}%
\label{fig:\tikzfile}%
\end{figure}


The macro \tikzsetnextfilename is very simple, it is defined as

\gdef\tikzexternal@nextfile{#1}


meaning that the filename will be stored in the (global) macro \tikzexternal@nextfile. You can use this macro for your labels, however it contains an @ symbol (indicating that it is an internal macro) which means you can only use it in your own code if you switch off the special meaning of @ temporarily with the \makeatletter and \makeatother macros. This is very inconvenient for the current use case, therefore it is easier to change the original definition in order to create two macros, the original \tikzexternal@nextfile with the @ symbol and another custom macro without the @ symbol that can be used in \label.

MWE, based on the TikZ manual:

\documentclass{article}
% main document, called main.tex
\usepackage{tikz}

\usetikzlibrary{external}
\makeatletter
\def\tikzsetnextfilename#1{\gdef\tikzexternal@nextfile{#1}\gdef\mytikznext{#1}}
\makeatother
\tikzexternalize[prefix=tikzext/] % activate
\begin{document}
\begin{figure}
\centering
\tikzsetnextfilename{trees}
\begin{tikzpicture}
\node {root}
child {node {left}}
child {node {right}
child {node {child}}
child {node {child}}
};
\end{tikzpicture}
\caption{A tree}
\label{fig:\mytikznext}
\end{figure}

\begin{figure}
\centering
\tikzsetnextfilename{gridlines}
\begin{tikzpicture}
\draw[help lines] (0,0) grid (5,5);
\end{tikzpicture}
\caption{A grid}
\label{fig:\mytikznext}
\end{figure}

\centering See Figure \ref{fig:trees} and \ref{fig:gridlines}.
\end{document}


Result:
