Нельзя использовать макрос внутри скобок или для обрезки

Aug 17 2020

Я пытаюсь определить необязательные параметры фигуры по умолчанию с помощью пользовательской команды, но я не могу использовать их внутри [ ]. Следующий пример генерирует исключение , когда я заменю trim=0 0 0 0с trim=\trim.

\usepackage[demo]{graphicx}

\newcommand{\trim}{0 0 0 0}

\begin{document}
    
    \begin{figure}[htbp]
        \centering
        \includegraphics[width=\linewidth,trim=0 0 0 0,clip]{Figure}
        \caption{blablabla.}
    \end{figure}
        
\end{document}

Кроме того, моя цель - определить команду, например, заменить ею все предложение width=\linewidth,trim=0 0 0 0,clipвнутри [ ].

Ответы

6 UlrichDiez Aug 17 2020 at 17:02

ИЗМЕНИТЬ 20 АВГУСТА 2020 ГОДА

Еще раз я (Ульрих Диец) поставил себя в затруднительное положение:

При написании того, что ниже, я (Ульрих Диез) не думал о том, что квадратные скобки [и - в ]отличие от фигурных скобок - не относятся к коду категории 1 и 2, а являются обычными символами с кодом категории 12, и поэтому квадратные скобки может встречаться в макро-аргументах. Менее сложный и намного короче, чем код ниже:

\documentclass{article}

\usepackage[demo]{graphicx}

\newcommand\exchange[2]{#2#1}
\newcommand{\trim}{0 0 0 0}

\begin{document}
    
    \begin{figure}[htbp]
        \centering
        \expandafter\exchange\expandafter{\trim}{%
           \includegraphics[width=\linewidth,trim=%
        },clip]{/path/to/graphics/file.jpg}%%%%%
        % Why two captions?
        \caption{Testing of the Y-axis.}%%%%%
        \caption{blablabla.}%%%%%
    \end{figure}
        
\end{document}

Последовательность

\expandafter\exchange\expandafter{\trim}{%
   \includegraphics[width=\linewidth,trim=%
},clip]{/path/to/graphics/file.jpg}%%%%%

вызывает следующее:

В \expandafter-цепочку приводит к расширению \trim:

\exchange{0 0 0 0}{%
   \includegraphics[width=\linewidth,trim=%
},clip]{/path/to/graphics/file.jpg}%%%%%

Увеличение \exchangeурожайности:

\includegraphics[width=\linewidth,trim=%
0 0 0 0,clip]{/path/to/graphics/file.jpg}%%%%%

КОНЕЦ РЕДАКТИРОВАНИЯ 20 АВГУСТА 2020 Г.



Если определение \trim-команды может меняться от рисунка к рисунку, то вы можете, например, использовать \romannumeral0-расширение- и-технику-обмена-аргументами - суть \romannumeral0-расширения такова:

  • TeX расширяет расширяемые токены, собирая токены, принадлежащие « количеству» -количеству, которое должно быть представлено римскими цифрами.
  • Если первый токен, который TeX находит при сборе « числа» -количества, является цифрой, например, 0то процесс сбора токенов, принадлежащих « числу» -количеству, превращается в процесс сбора дополнительных цифр или чего-то еще, что не является цифра и, следовательно, завершает процесс сбора. Расширяемые жетоны расширяются при сборе цифр. Пробел-маркер, завершающий последовательность цифр, завершает процесс сбора дополнительных цифр и незаметно отбрасывается.
  • Если полученное число не является положительным, TeX молча проглатывает жетоны, образующие « число» -количество, не передавая никаких жетонов взамен.

Это означает, что \romannumeralего можно использовать для обмана TeX, заставляя его выполнять множество операций по расширению и обмену аргументами, если в конечном итоге будет найдено неположительное число.

\documentclass{article}

\usepackage[demo]{graphicx}

\newcommand\exchange[2]{#2#1}
\newcommand{\trim}{0 0 0 0}

\begin{document}
    
    \begin{figure}[htbp]
        \centering
        \expandafter\includegraphics\expandafter[%
          \romannumeral0%
          \expandafter\exchange
          \expandafter{\trim}{ width=\linewidth,trim=},clip%
        ]{/path/to/graphics/file.jpg}%%%%%
        % Why two captions?
        \caption{Testing of the Y-axis.}%%%%%
        \caption{blablabla.}%%%%%
    \end{figure}
        
\end{document}

Последовательность

\expandafter\includegraphics\expandafter[%
  \romannumeral0%
  \expandafter\exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

вызывает следующее:

Процесс получения расширения (верхнего уровня) для \expandafterзапускает процесс доставки расширения верхнего уровня следующего, но одного токена и завершается, когда завершается процесс получения расширения верхнего уровня следующего, но одного токена. . Таким образом:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggers the process of obtaining the top-level-
% expansion of the next but one token:
\includegraphics\expandafter[%
  \romannumeral0%
  \expandafter\exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Предполагаемый токен, исходящий из первого \expandafter, также является \expandafterследующим:

% Process of obtaining the top-level-expansion of the first \expandafter in 
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggers the process of obtaining the top-level-
% expansion of the next but one token:
[%
  \romannumeral0%
  \expandafter\exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Следующие , но один маркер исходящими из второго \expandafterявляется \romannumeral, таким образом:

% Process of obtaining the top-level-expansion of the first \expandafter in 
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in 
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering tokens of a <number>-
  %   quantity in progress:
  0%
  \expandafter\exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

TeX находит цифру 0, таким образом, подпроцесс\romannumeral сбора токенов « числа» -количества превращается в процесс сбора дополнительных цифр или чего-то, что завершает последовательность цифр:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
  %   <number>-quantity in progress; digit "0" found so far:
  \expandafter\exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

При поиске большего количества токенов / цифр, принадлежащих количеству « число», TeX обнаруживает третий \expandafter:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
  %   <number>-quantity in progress; digit "0" found so far:
  %     Process of obtaining the top-level-expansion of the third \expandafter
  %     in progress, this process triggers the process of obtaining the top-
  %     level-expansion of the next but one token:
  \exchange
  \expandafter{\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Следующий , но один маркер исходящий от третьего \expandafterявляется \expandafter, таким образом:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
  %   <number>-quantity in progress; digit "0" found so far:
  %     Process of obtaining the top-level-expansion of the third \expandafter
  %     in progress, this process triggerd the process of obtaining the top-
  %     level-expansion of the fourth \expandafter:
  \exchange
  %   Process of obtaining the top-level-expansion of the fourth \expandafter
  %   in progress, this process triggers the process of obtaining the top-
  %   level-expansion of the next but one token:
  {\trim}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Следующий, предпоследний токен, исходящий из четвертого, \expandafterэто \trim, таким образом, процесс получения расширения верхнего уровня четвертого \expandafterзавершается, когда процесс получения расширения верхнего уровня \trimзавершается:

% Process of obtaining the top-level-expansion of the first \expandafter in 
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a 
  %   <number>-quantity in progress, digit "0" found so far:
  %     Process of obtaining the top-level-expansion of the third \expandafter
  %     in progress, this process triggerd the process of obtaining the top-
  %     level-expansion of the fourth \expandafter:
  \exchange
  %  Process of obtaining the top-level-expansion of the fourth \expandafter
  %  terminated.
  {0 0 0 0}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Когда процесс получения расширения верхнего уровня четвертого \expandafterзавершается, процесс получения расширения верхнего уровня третьего также \expandafterзавершается:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
   %  <number>-quantity in progress, digit "0" found so far:
  %     Process of obtaining the top-level-expansion of the third \expandafter
  %     terminated.
  \exchange
  {0 0 0 0}{ width=\linewidth,trim=},clip%
]{/path/to/graphics/file.jpg}%%%%%

Когда процесс получения третьего раскрытия верхнего уровня \expandafterзавершается, \romannumeral-расширение продолжается, что дает расширение \exchange:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
  %   <number>-quantity in progress; digit "0" found so far:
  <space-token>width=\linewidth,trim=0 0 0 0,clip%
]{/path/to/graphics/file.jpg}%%%%%

TeX находит пробел. Этот пробел завершает подпроцесс сбора большего количества цифр « числа» -количества и молча отбрасывается.

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral in progress;
  %   Sub-process of \romannumeral-expansion for gathering more digits of a
  %   <number>-quantity terminated; number "0" found.
  width=\linewidth,trim=0 0 0 0,clip%
]{/path/to/graphics/file.jpg}%%%%%

Как TeX нашел ⟨number⟩ -quantity, значение которого 0, в то время как 0это не имеет положительное значение, процесс получения верхнего уровня расширения \romannumeralоканчивается на молча глотание маркеры , образующие этой ⟨number⟩ -quantity без TeX доставки любой лексемы возвращение.

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of \romannumeral:
[%
  % Process of obtaining the top-level-expansion of \romannumeral terminated.
  width=\linewidth,trim=0 0 0 0,clip%
]{/path/to/graphics/file.jpg}%%%%%

Когда процесс получения расширения верхнего уровня \romannumeralзавершается, процесс получения расширения верхнего уровня второго также \expandafterзавершается:

% Process of obtaining the top-level-expansion of the first \expandafter in
% progress, this process triggerd the process of obtaining the top-level-
% expansion of the second \expandafter:
\includegraphics
% Process of obtaining the top-level-expansion of the second \expandafter
% terminated.
[%
  width=\linewidth,trim=0 0 0 0,clip%
]{/path/to/graphics/file.jpg}%%%%%

Когда процесс получения расширения верхнего уровня второго \expandafterзавершается, завершается и процесс получения расширения первого уровня \expandafter:

% Process of obtaining the top-level-expansion of the first \expandafter
% terminated.
\includegraphics
[%
  width=\linewidth,trim=0 0 0 0,clip%
]{/path/to/graphics/file.jpg}%%%%%