![在 tcolorbox 中断线](https://linux22.com/image/340823/%E5%9C%A8%20tcolorbox%20%E4%B8%AD%E6%96%AD%E7%BA%BF.png)
我正在 TeXstudio 中创建一本书,并且有以下代码:
\newtcblisting[auto counter,number within=chapter]{sourcecode}[2][]{sharp corners, breakable,
fonttitle=\bfseries, colframe=gray, listing only,
listing options={basicstyle=\ttfamily,language=php, showstringspaces=false, breakatwhitespace=true, breaklines=true, tabsize=4},
title=Code Snippet \thetcbcounter: #2, #1}
我设法使用 breakable 选项来跨页分页,但尝试使用 breaklines=true 来分行却不起作用,因为它似乎不是 tcolorbox 的有效选项。
以下代码本身可以起到换行的作用:
\lstset{
breaklines=true,
postbreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\color{red}\hookrightarrow\space}}
}
但这样一来,我的颜色框样式就丢失了。我怎样才能将这两种样式合并为一种?我不一定需要漂亮的红色箭头,但最好在虚线上留一点缩进。
完整的代码片段可能看起来像这样:
\documentclass{book}
\usepackage{hyperref}
\usepackage[table]{xcolor}
\usepackage{listings}
\usepackage[most]{tcolorbox}
\usepackage{inconsolata}
\usepackage{graphicx}
\tcbuselibrary{breakable}
\newtcblisting[auto counter,number within=chapter]{sourcecode}[2][]{sharp corners, breakable,
fonttitle=\bfseries, colframe=gray, listing only,
listing options={basicstyle=\ttfamily,language=php, showstringspaces=false, breakatwhitespace=true, breaklines=true, tabsize=4},
title=Code Snippet \thetcbcounter: #2, #1}
\begin{document}
\begin{sourcecode}{}
<?php
function abc($file_name){
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$file_name.'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
}
\end{sourcecode}
\end{document}
编译后如下所示:
我怎样才能打破这一长行并使其缩进,以便它在框内流动并在代码中正确排列?
答案1
该选择 breakatwhitespace=true
只允许在空白处换行,而您的行代码不包含空格,只需删除您的选择即可breakatwhitespace=true
代码
\documentclass{book}
\usepackage{hyperref}
\usepackage[table]{xcolor}
\usepackage{listings}
\usepackage[most]{tcolorbox}
\usepackage{inconsolata}
\usepackage{graphicx}
\tcbuselibrary{breakable}
\newtcblisting[auto counter,number within=chapter]{sourcecode}[2][]{sharp corners, breakable,
fonttitle=\bfseries, colframe=gray, listing only,
listing options={basicstyle=\ttfamily,language=php, showstringspaces=false,
breaklines=true, postbreak={\raisebox{0ex}[0ex][0ex]{\ensuremath{\color{red}\hookrightarrow\space}}}, tabsize=4
},
title=Code Snippet \thetcbcounter: #2, #1}
\begin{document}
\begin{sourcecode}{}
<?php
function abc($file_name){
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$file_name.'"');
header('Cache-Control: max-age=0');
$writer->save('php://output');
}
\end{sourcecode}
\end{document}