1

I want to redefine the ampersand-charakter to expand to a macro, I defined. Basically it is/should be something like

&={\hspace*{30pt}Ampersand has been redefined\hfill}

The final use is

\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[german]{babel}
\usepackage{environ}
\usepackage{etoolbox}
\usepackage{xparse}

\newcommand{encap}[1]{ { % make definitions of \ns local / limit scope
\DeclareDocumentCommand{\ns}{s O{0 pt}}{%
    \ifx\tempi\undefined%
        \newlength{\tempi}%
    \fi%
    \setlength{\tempi}{##2}%
    \divide\tempi by 2%
    \ifx##1\BooleanTrue \hskip 0pt plus 1fill minus 1fill \hspace*{\tempi}-\hspace*{\tempi}%
        \hskip 0pt plus 1fill minus 1fill%
    \else% 
        \hskip 0pt plus 2fill minus 2fill \hspace*{##2}%
    \fi%
}%\ns

%Pseudocode:
&=\ns

\makebox[\textwidth]{#1}
}} % encap

\begin{document}
\encap{this\ns equals& this}
\ns % out of scope
& % should be restored
\end{document}

BTW.: The \ns command works exactly as intended

18
  • 1
    Why don't you make a complete example? And did you really thought throught the consequences if you make & is active and it no longer can be used in a tabular? May 27, 2016 at 15:01
  • @UlrikeFischer I thought this through (at least I think). Inside of \encap there can't be used the tabular-environment, but this is absolutely okay. May 27, 2016 at 15:11
  • So you want that & does \ns only inside the argument to \encap?
    – egreg
    May 27, 2016 at 15:16
  • 1
    You could use expl3 and do a \tl_replace_all:Nnn \l_tmpa_tl { & } { \ns }.
    – Manuel
    May 27, 2016 at 15:27
  • 1
    @MaestroGlanz It won't break.
    – Manuel
    May 27, 2016 at 15:38

1 Answer 1

2

It's not clear what is the intended usage of \ns; however, here's an implementation.

I fixed the most obvious weaknesses in your code.

\documentclass[12pt,a4paper]{article}

\usepackage{xparse}

\newlength{\tempi}

% define active & to be normal &
\begingroup\lccode`~=`&
\lowercase{\endgroup\let~}&
% make & active
\catcode`&=\active

\newcommand{\encap}[1]{\begingroup\let&\ns#1\endgroup}

\NewDocumentCommand{\ns}{s O{0 pt}}{%
  \unskip
  \setlength{\tempi}{\dimexpr#2/2}%
  \IfBooleanTF{#1}
    {%
     \hspace{0pt plus 1fill minus 1fill}%
     \hspace*{\tempi}-\hspace*{\tempi}%
     \hspace{0pt plus 1fill minus 1fill}%
    }
    {%
     \hspace{0pt plus 2fill minus 2fill}\hspace*{#2}%
    }%
  \ignorespaces
}

\begin{document}

\noindent
\makebox[\textwidth]{\encap{this \ns equals & this}}

\noindent
\makebox[\textwidth]{\encap{this \ns* equals &* this}}

\noindent
\makebox[\textwidth]{\encap{this \ns*[10pt] equals &*[10pt] this}}

\begin{tabular}{cc}
 text & text \\
 a & b
\end{tabular}

\end{document}

enter image description here

1
  • That's ecactly what it should do. May 27, 2016 at 15:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .