# How to have center title in listings when you have subcaption (workaournd conflict between listing caption and subcaption class)?

I want to use listings package (\usepackage{listings}) to show a matlab code in a paper (using elsarticle class) but the title is not aligned in center below the code. This happened after I added xleftmargin=3.5cm and xrightmargin=3.5cm to add margin from left and right. If I remove these two options, title appears at the center of page! How can I have both margin and center title with listings?

I used \centering and \begin{center}...\end{center} but they didn't work.

UPDATE: I found out that \usepackage{subcaption} is the problem. without it title will be centered. But I need subcaption!

my code:

\documentclass[3p,times]{elsarticle}

\usepackage{ecrc}
\volume{00}
\firstpage{1}
\journalname{Best Journal Ever}
\runauth{S. Gerami}
\jid{}
\jnltitlelogo{Best Journal Ever}
\usepackage{amssymb}
\usepackage[figuresright]{rotating}
\usepackage[ruled,vlined]{algorithm2e}

%%FOR MATH
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{amsfonts}

%%I NEED THESE PACKAGED FOR FIGURES AND SUBCAPTIONs
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}

%%FOR CODES
\usepackage{listings}
\usepackage{color}

%%FOR TABLES
\usepackage{array}
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

\usepackage{lipsum}
\begin{document}

\begin{frontmatter}
\title{title of my paper}

\address[bahonar]{Faculty of Mathematics and Computer Science, Best University, Somewhere, The One Country}

\begin{abstract}
abstract text....
\end{abstract}

\end{frontmatter}

\section{First section}
\lipsum{}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

\lstset{ %
backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
basicstyle=\footnotesize,        % the size of the fonts that are used for the code
breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
breaklines=true,                 % sets automatic line breaking
captionpos=b,                    % sets the caption-position to bottom
deletekeywords={...},            % if you want to delete keywords from the given language
extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
frame=single,                    % adds a frame around the code
keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue},       % keyword style
language=Octave,                 % the language of the code
morekeywords={*,...},            % if you want to add more keywords to the set
numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt,                   % how far the line-numbers are from the code
numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false,          % underline spaces within strings only
showtabs=false,                  % show tabs within strings adding particular underscores
stepnumber=1,                    % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{mymauve},     % string literal style
tabsize=2,                       % sets default tabsize to 2 spaces
%  title=Script 1: A program in Matlab to estimate the total area under sin(x),                   % show the filename of files included with \lstinputlisting; also try caption instead of title
xleftmargin=3.5cm,
xrightmargin=3.5cm
}

\begin{lstlisting}[title={Script 1: A program in Matlab to estimate the total area under $\sin(x)$}]
a=0;
b=pi/2;
h=max(feval(@func,linspace(a,b,n)));
x=a+(b-a)*rand(n,1);
y=h*rand(n,1);
N=0;
f=sin(x);
for j=1:n
if y(j)<=f(j)
N=N+1;
end
end
ans=N/n*h*(b-a)
\end{lstlisting}
%*****************
\lipsum{}

\end{document}


output:

UPDATE2: I tested method proposed in following link and not worked: Center caption in listing

but then I saw this answer and edited to this:

\begin{figure}[thp]
\begin{center}
\begin{lstlisting}[numbers=left]
My Code
Another line
\end{lstlisting}
\end{center}
\caption{my caption or title}
\end{figure}


result:

It's good but the gap between box and caption is too much. I need to reduce it for good result.

UPDATE3: This link has the best answer to removing gap for just one figure.

\begin{figure}[!ht]
\centering
\includegraphics[width=0.5\textwidth]{image}
\vspace{-1em}
\caption{\textcolor{gray}{\footnotesize \textit{ImageCaption}}}
\vspace{-1.5em}
\end{figure}

• I get it centered. Anyway, you'd probably better use \begin{lstlisting}[title={Script 1: A program in Matlab to estimate the total area under $\sin(x)$}] instead of putting it inside the \lstset. – karlkoeller Sep 23 '13 at 19:35
• @karlkoeller I did what you said and got the same result! How you centered it? did you have margin and center title? – sajjadG Sep 23 '13 at 19:39
• I've just used your code. Please post a complete compilable example that reproduces your issue. – karlkoeller Sep 23 '13 at 19:53
• To reduce the gap, move the \caption command inside the center environment and add \vspace*{-\baselineskip} just before \caption. – Andrew Swann Sep 24 '13 at 11:15
• Did you read section 6.7 of the caption manual? – Martin Schröder Sep 25 '13 at 19:19

Effectively, there is some incopatibility between caption and listings when you use xleftmargin and xrightmargin...

Without changing any commands from one or the other package, one thing that comes to mind is to insert the listing inside a centered minipage.

So, remove the lines

  xleftmargin=3.5cm,
xrightmargin=3.5cm


from inside the \lstset

\begin{center}
\begin{minipage}{.5\textwidth}
\begin{lstlisting}[title={Script 1: A program in Matlab to estimate the total area under $\sin(x)$}]
a=0;
b=pi/2;
h=max(feval(@func,linspace(a,b,n)));
x=a+(b-a)*rand(n,1);
y=h*rand(n,1);
N=0;
f=sin(x);
for j=1:n
if y(j)<=f(j)
N=N+1;
end
end
ans=N/n*h*(b-a)
\end{lstlisting}
\end{minipage}
\end{center}


Thus, the following MWE

\documentclass[3p,times]{elsarticle}

%%I NEED THESE PACKAGED FOR FIGURES AND SUBCAPTIONs
\usepackage{graphicx}
%\usepackage{caption}  % no need because it is loaded by subcaption.
\usepackage{subcaption}

%%FOR CODES
\usepackage{listings}
\usepackage{color}

\usepackage{lipsum}
\begin{document}

\begin{frontmatter}
\title{title of my paper}

\begin{abstract}
abstract text....
\end{abstract}

\end{frontmatter}

\section{First section}
\lipsum{}
\definecolor{mygreen}{rgb}{0,0.6,0}
\definecolor{mygray}{rgb}{0.5,0.5,0.5}
\definecolor{mymauve}{rgb}{0.58,0,0.82}

\lstset{ %
backgroundcolor=\color{white},   % choose the background color; you must add \usepackage{color} or \usepackage{xcolor}
basicstyle=\footnotesize,        % the size of the fonts that are used for the code
breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
breaklines=true,                 % sets automatic line breaking
captionpos=b,                    % sets the caption-position to bottom
deletekeywords={...},            % if you want to delete keywords from the given language
extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
frame=single,                    % adds a frame around the code
keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue},       % keyword style
language=Octave,                 % the language of the code
morekeywords={*,...},            % if you want to add more keywords to the set
numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt,                   % how far the line-numbers are from the code
numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false,          % underline spaces within strings only
showtabs=false,                  % show tabs within strings adding particular underscores
stepnumber=1,                    % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{mymauve},     % string literal style
tabsize=2,                       % sets default tabsize to 2 spaces
}
\begin{center}
\begin{minipage}{.5\textwidth}
\begin{lstlisting}[title={Script 1: A program in Matlab to estimate the total area under $\sin(x)$}]
a=0;
b=pi/2;
h=max(feval(@func,linspace(a,b,n)));
x=a+(b-a)*rand(n,1);
y=h*rand(n,1);
N=0;
f=sin(x);
for j=1:n
if y(j)<=f(j)
N=N+1;
end
end
ans=N/n*h*(b-a)
\end{lstlisting}
\end{minipage}
\end{center}
\lipsum{}

\end{document}


yields

Just some remarks:

1. I've removed some code from your MWE since I didn't know where to get the package ecrc.
2. the package caption doesn't need to be loaded since it is already loaded by the package subcaption.
3. I don't know if you are using title instead of caption for a specific reason. If the reason is to get rid of the word "Listing" inside the caption you can do the following:

a. put the following line in the preamble:

\renewcommand{\lstlistingname}{Script}


b. replace

\begin{lstlisting}[title={Script 1: A program in Matlab to estimate the total area under $\sin(x)$}]


with

\begin{lstlisting}[caption={A program in Matlab to estimate the total area under $\sin(x)$}]

• The ecrc package must be called to make the CRC functionality available. It's in the Elsevier template. You used \documentclass[3p,times]{elsarticle} and ecrc is in it! Your answer is very good. As you can see I have a workaround with figure for this issue. Your remarks is so much teaching. Thank you. – sajjadG Sep 24 '13 at 13:52
• @sajjadG Remember that inserting the listing inside a figure causes the listing to float. Also, you will have it listed in the List of Figures. If you want this behavior, then use your workaround, otherwise, I'd suggest you to use the code in my answer. – karlkoeller Sep 24 '13 at 14:01