l3regex - 逐行分割

l3regex - 逐行分割

我想逐行分析环境的内容,但是以下简约的测试代码因“打印”而失败false

\documentclass{article}

\ExplSyntaxOn

\NewDocumentEnvironment{linebyline}{b}{
    \seq_new:N \l_temp_seq
    \regex_split:nnNTF { \n } { #1 } \l_tmpa_seq
        { true }
        { false }
}{}

\ExplSyntaxOff

\begin{document}

\begin{linebyline}
% Comment
    Line 1
    Line 2
% Comment
    Line 3
\end{linebyline}

\end{document}

答案1

这是一个使用命令而不是环境的解决方案,这不是我的需要,并使用正则表达式代替seq_set_split:Nnnseq_set_split_keep_spaces:Nnn


欢迎对 split-seq 解决方案提出任何建议。


\documentclass{article}

\ExplSyntaxOn

\NewDocumentCommand{\linebyline}{+v}{
    \seq_new:N \l_temp_seq
    \regex_split:nnN {\^^M} {#1} \l_tmpa_seq 
    \seq_use:Nn \l_tmpa_seq { :: }
}{}

\ExplSyntaxOff


\begin{document}

\linebyline{
% Comment
    Line 1
    Line 2
% Comment
    Line 3
}

\end{document}

此代码输出:

::% Comment::Line 1::Line 2::% Comment::Line 3::

答案2

我不太确定您在寻找什么,但是\obeylines在环境中,可以使用令牌循环来搜索行尾并在行::之间放置(如您的示例所示)。

\documentclass{article}
\usepackage{tokcycle}
{\obeylines
\gdef\mycr{
}}
\def\myenvname{linebyline}
\newenvironment{\myenvname}{\obeylines\catcode`\%=12 \tokencycle
  {\addcytoks{##1}}
  {\processtoks{##1}}
  {%
  \expandafter\ifx\mycr##1\addcytoks{::}\else
    \ifx\end##1
      \tcpop\z\tcpushgroup\z%
      \ifx\z\myenvname
        \tcpush{\noexpand\endtokcycraw##1}%
      \else\addcytoks{##1}\fi
    \else\addcytoks{##1}\fi
  \fi}
 {\addcytoks{##1}}}{}
\begin{document}
\begin{linebyline}
% Comment
    Line 1
    Line 2
% Comment
    Line 3
\end{linebyline}

Back to
normal
text.

\begin{linebyline}
% Comment
    Line 1 \today
    Line 2\begin{itemize} \item xxx\end{itemize}
% Comment
    Line 3
\end{linebyline}

Back to % absolutely
normal
text.
\end{document}

在此处输入图片描述

如果有人希望解析的内容不是被执行,但被去标记化,并且收集每行的行内容,可以这样做:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{tokcycle}
{\obeylines
\gdef\mycr{
}}
\def\myenvname{linebyline}
\newenvironment{\myenvname}{\obeylines\catcode`\%=12 \tokencycle
  {\addcytoks{\string##1}}
  {\addcytoks{\{}\processtoks{##1}\addcytoks{\}}}
  {%
  \expandafter\ifx\mycr##1
    \mbox{}\\Input line: ``\the\cytoks''% <-CURRENT INPUT LINE
    \cytoks{}%
  \else
    \ifx\end##1
      \tcpop\z\tcpushgroup\z%
      \ifx\z\myenvname
        \tcpush{\noexpand\endtokcycraw##1}%
      \else\addcytoks{\detokenize{##1}}\fi
    \else\addcytoks{\detokenize{##1}}\fi
  \fi}
  {\addcytoks{##1}}}{}
\begin{document}
\begin{linebyline}
% Comment
    Line 1
    Line 2
% Comment
    Line 3
\end{linebyline}

Back to
normal
text.

\begin{linebyline}
% Comment
    Line 1 \today
    Line 2\begin{itemize} \item xxx\end{itemize}
% Comment
    Line 3
\end{linebyline}

Back to % absolutely
normal
text.
\end{document}

在此处输入图片描述

相关内容