How can I hide the source code that overflows a listing's frame?
Here is a version using the viewport
option that package adjustbox
provides for its box commands. The code had to be rearranged a bit such that the frame around the listings is added by \adjustbox
and the captions by \captionof
. Otherwise you would get a missing right side of the frame.
Everything was wrapped into a new environment codebox
which takes the box width as its first and the listing's caption as its second parameter. It's basically just a sketch of the idea; a better interface for more customization could be added by providing a key-value option list for the environment.
Full example code:
\documentclass[a4paper,export]{report}
\usepackage{xcolor}
\usepackage{lipsum}
\usepackage{listings}
\usepackage{caption}
\usepackage{adjustbox}
\lstset{
%numbers=left,numberstyle=\tiny, stepnumber=1, numbersep=5pt,
breaklines=true,
breakatwhitespace=false,
tabsize=2,
basicstyle=\footnotesize,%\ttfamily,
% frame=single,
% rulecolor=\color{gray}
}
\newenvironment{codebox}[2]{%
\begin{minipage}[t]{#1}%
\vspace*{-0.5\baselineskip}
\captionof{lstlisting}{#2}\par
\vspace*{-0.7\baselineskip}
\begin{adjustbox}{
cfbox=gray,
clip=true,
viewport={\fboxrule+\fboxsep} {-\depth} {\linewidth-\fboxrule-\fboxsep} {\height}
}%
\hbadness=100
\hfuzz=\maxdimen
}{%
\end{adjustbox}%
\end{minipage}%
}
\begin{document}
\lipsum[1]
\noindent
\begin{codebox}{0.48\textwidth}{Code 1}
\begin{lstlisting}[breaklines=false]
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetSpecialtiesResponse xmlns="http://tempuri.org/">
<GetSpecialtiesResult xmlns:a="http://schemas.datacontract.org/2004/07/WsAgenda.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Specialty>
<a:code>cardiology</a:code>
<a:name>Cardiologie</a:name>
</a:Specialty>
<a:Specialty>
<a:code>neurology</a:code>
<a:name>Neurologie</a:name>
</a:Specialty>
<a:Specialty>
<a:code>urology</a:code>
<a:name>Urologie</a:name>
</a:Specialty>
<a:Specialty>
<a:code>physiotherapy</a:code>
<a:name>Physiotherapie</a:name>
</a:Specialty>
</GetSpecialtiesResult>
</GetSpecialtiesResponse>
</s:Body>
</s:Envelope>
\end{lstlisting}
\end{codebox}
\hfill
\begin{codebox}{.48\textwidth}{Code 2}
\begin{lstlisting}[breaklines=true]
{"Specialties": [
{
"id": "cardiology",
"description": "Cardiologie"
},
{
"id": "neurology",
"description": "Neurologie"
},
{
"id": "urology",
"description": "Urologie"
},
{
"id": "physiotherapy",
"description": "Physiotherapie"
}
]}
\end{lstlisting}
\end{codebox}
\medskip
\lipsum[2]
\end{document}
outputs