# \tikzsetnextfilename externalize with filename as variable

I want to externalize my pictures with the external tikzlibrary. The problem is that there are pictures created inside \newcommand and i have to automatically set the filename tor the externalization.

Currently I got this to work:

\documentclass[10pt]{beamer}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=TikZfigures-]

\newcommand{\Test}[1]{
\tikzsetnextfilename{#1}
\begin{tikzpicture}
\path (0,0) node (n) {#1};
\end{tikzpicture}
}

\begin{document}
\Test{Works}
\Test{Works}
\Test{Does not work}
\end{document}


When it tries to create the file "TikZfigures-Does not work.tex" the externalization doesn't do it right and crashes. How can I avoid this problem?

I found a similar problem in this question: TIKZ Externalize with filename and path variable

I found the answer myself after being pointed to this similar question with an excellent answer by Marijn:

How to replace characters from jobname?

My adapted code looks like this:

\documentclass[10pt]{beamer}
\usepackage{xstring}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzexternalize[prefix=TikZfigures-]

\newcommand{\Test}[1]{
\def\fn{#1}
\StrSubstitute{\fn}{ }{_}[\fn]
\tikzsetnextfilename{\fn}
\begin{tikzpicture}
\path (0,0) node (n) {#1};
\end{tikzpicture}
}

\begin{document}
\Test{Works}
\Test{Works}
\Test{Does still work}
\end{document}


Using xstring to replace the spaces with underscores makes the filename possible to be used by externalize. If you have any other symbols that can't be in the filename, just replace them, too.

A problem still exists if you try

\begin{document}
\Test{the same}
\Test{the\textunderscore same}
\end{document}


Because it results in the same filename. Each command on its own works, but not together.