根据列表行数更改 tcolorbox 列表选项

根据列表行数更改 tcolorbox 列表选项

考虑以下生成列表的代码:

% ---------------------------------------------------------------------------- %
% Preamble
\documentclass[12pt]{article}
% ---------------------------------------------------------------------------- %
% Packages
\usepackage{calc}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{multicol}
\usepackage{printlen}
\usepackage[most]{tcolorbox}
% ---------------------------------------------------------------------------- %
% Length
\newlength{\evenlength}
\setlength{\evenlength}{0pt}
\newlength{\oddlength}
\setlength{\oddlength}{10pt}
% ---------------------------------------------------------------------------- %
% Listing
\newtcblisting{lstbox}[4][\normalsize]{
    code = {},
    enhanced,
    listing only,
    top = 0pt,
    %%%%%%
    % I want bottom to be equal to:
    % - \evenlength if the listing has an even number of lines
    % - \oddlength if the listing has an even number of lines
    bottom = 0pt,
    %%%%%%
    left = 0pt,
    right = 0pt,
    arc = 0pt,
    outer arc = 0pt,
    boxsep = 0pt,
    titlerule = 0pt,
    colback = red,
    colframe = black,
    boxrule = 2pt,
    title = {\centering{\fontfamily{cmtt}\selectfont#2\strut}},
    listing options = {
        language = C++,
        framesep = 0pt,
        rulesep = 0pt,
        aboveskip = 0pt,
        belowskip = 0pt,
        backgroundcolor = \color{lightgray},
        basicstyle = \fontfamily{cmtt}\selectfont#1,
        #3,
    },
    #4,
}
% ---------------------------------------------------------------------------- %
% Document
\pagestyle{empty}
\begin{document}
\begin{lstbox}[\small]{title}{}{}
1
2
\end{lstbox}
\begin{lstbox}[\small]{title}{}{}
1
2
3
\end{lstbox}
\begin{lstbox}[\small]{title}{}{}
1
2
3
4
\end{lstbox}
\end{document}
% ---------------------------------------------------------------------------- %

有没有办法让tcolorbox bottom选项等于

  • \evenlength当列表有偶数行时
  • \oddlength当列表有奇数行时

答案1

在您的选项列表中\newtcblisting,添加以下内容

process code = {%
    \tcbset{ bottom = \ifodd\lst@lineno \oddlength \else \evenlength \fi }%
}

并将该命令包装在\makeatletter/中\makeatother

中的代码process code将在 中使用的钩子中执行\end{lstbox}。此时,列表代码中的行数已经知道( 的最后一个值\lst@lineno),但底部尚未打印,因此bottom仍可以更改选项。

输出

在此处输入图片描述

相关内容