Search code examples
latex

Create new variable each time an environment in LaTeX is called


I've created an example environment for my maths notes. It takes the title of the example as the input and draws some lines with tikz. However, to do so, it requires the length of the title.

This is relatively easy to do when the environment is only called once by using \newlength{\lengthname} followed by \settowidth{\lengthname}{[length]}. However, as soon as it is called more than once, a different length must be defined. My (admittedly poor) work-around has been to pass the name of a different length, #2, every time I use my example environment.

How can I create a unique \newlength{\unique} each time I use my environment, or, is there some better way of achieving my goal?

\newenvironment{example}[2] % Example Environment
    {\refstepcounter{example}
    \newlength{#2}
    \settowidth{#2}{\small \textbf{Example \thesection.\theexample} --- #1}
    \bigskip\begin{tikzpicture}
        \draw (-0.5\columnwidth,-0.2)--(-0.5\columnwidth,0)--(0.5\columnwidth,0)--(0.5\columnwidth,-0.2);
        \fill[white] (-0.5#2-5pt,-1pt) rectangle (0.5#2+5pt,1pt);
        \tikzlabel{0}{-0.4}{\text{\small \textbf{Example \thesection.\theexample} --- #1}}
    \end{tikzpicture}}
    %
    {\begin{tikzpicture}
        \draw (-0.5\columnwidth,0.2) -- (-0.5\columnwidth,0) -- (0.5\columnwidth,0) -- (0.5\columnwidth,0.2);
    \end{tikzpicture}}

Many thanks.


Solution

  • My suggestion would be to use tcolorbox instead of drawing the frame yourself, but if you must use tikz, simply use a white background for your title.

    Please note that your code would produce a lot of overfull box warnings. You have to consider the indention and drawing a frame of column won't fit because you need an additional two times the half the width of the tikz lines. I simply reduced the width to .49\columnwidth, but you could also take into account the width of the line in your calculation.

    Also pay attention to the spacing around the ---. If you don't prevent the macro before from swallowing the space, it won't be centred.

    \documentclass{article}
    
    \usepackage{tikz}
    \newcounter{example}
    
    
    \newenvironment{example}[1]{%
      \refstepcounter{example}%
      \bigskip
      \noindent%
      \begin{tikzpicture}
        \draw (-0.49\columnwidth,-0.2)--(-0.49\columnwidth,0)--(0.49\columnwidth,0)--(0.49\columnwidth,-0.2);
        \node[fill=white,font=\small\bfseries] at (0,-1pt) {Example \thesection.\theexample{} --- #1};
      \end{tikzpicture}%
      \par%
    }{%
      \par%
      \noindent%
      \begin{tikzpicture}
        \draw (-0.49\columnwidth,0.2) -- (-0.49\columnwidth,0) -- (0.49\columnwidth,0) -- (0.49\columnwidth,0.2);
      \end{tikzpicture}%
      \par%
    }
    
    
    \begin{document}
    
    
    \begin{example}{test}
    content...
    \end{example}
    
    
    \end{document}
    

    enter image description here