0

I just got the following code.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{geometry}
\usepackage{blindtext}
\usepackage{enumerate}
\geometry{paper=a4paper, left=24mm, right=23mm, top=20mm, bottom=20mm}
\usepackage{listings}
\lstset{
    basicstyle=\ttfamily\footnotesize,
    xleftmargin=.1\textwidth, 
}

\begin{document} \blindtext

\begin{lstlisting}[language=Python] def generate_grid(data, basemap, delta=1): grid = { 'lon': np.arange(-180, 180, delta), 'lat': np.arange(-89.9,89.9, delta) } grid["x"], grid["y"] = np.meshgrid(grid["lon"], grid["lat"]) grid["x"], grid["y"] = basemap(grid["x"], grid["y"]) return grid \end{lstlisting} \blindtext \end{document}

The output looks like this enter image description here

But I want there to be a number on the left side, because I have several lstlisting and I want to refer to them how do I do that?

enter image description here

(sorry for my drawings)

Weiss
  • 75
  • yes that only partly answers my question, because I don't want the title to say listing and I want the reference number on the left side – Weiss Sep 21 '22 at 10:22
  • 1
    You should treat a listing as a type of graphics, don't try to place something that liiks like an equation number on the side. That will only confuse the readers. – daleif Sep 21 '22 at 11:10

2 Answers2

2

I combined `listings` and `sidecap` - Side captions for listings and Put text to the right of figures to get the caption to the center right of the listing. Then to add the parentheses the labelformat=parens was used, and to remove the word 'Listing' I used an empty name= option to \DeclareFloatingEnvironment.

Note that the label and caption need to be set in the regular way (so not as lstlisting options) and the parentheses around the \ref statement need to be added manually because labelformat does not extend to the output of \ref.

MWE:

% sources:
% https://tex.stackexchange.com/questions/125106/listings-and-sidecap-side-captions-for-listings
% https://tex.stackexchange.com/questions/49979/put-text-to-the-right-of-figures

\documentclass{article} \usepackage[utf8]{inputenc} \usepackage{geometry} \usepackage{blindtext} \usepackage{enumerate} \geometry{paper=a4paper, left=24mm, right=23mm, top=20mm, bottom=20mm} \usepackage{listings} \lstset{ basicstyle=\ttfamily\footnotesize, xleftmargin=.1\textwidth, } \usepackage[wide]{sidecap}
\usepackage{caption} \usepackage{newfloat} \DeclareFloatingEnvironment[placement={!ht},name=]{listing} \captionsetup[listing]{labelformat=parens} \sidecaptionvpos{listing}{c} \makeatletter \makeatother

\begin{document} \blindtext \begin{SClisting} \begin{lstlisting}[language=Python] def generate_grid(data, basemap, delta=1): grid = { 'lon': np.arange(-180, 180, delta), 'lat': np.arange(-89.9,89.9, delta) } grid["x"], grid["y"] = np.meshgrid(grid["lon"], grid["lat"]) grid["x"], grid["y"] = basemap(grid["x"], grid["y"]) return grid \end{lstlisting} \caption{} \label{lst:grid} \end{SClisting} \blindtext The grid algorithm is described in (\ref{lst:grid}). \end{document}

Result:

enter image description here

Marijn
  • 37,699
  • Hi thanks for your answer but my code makes the one on the side a bit thick, how can I make it look like yours? – Weiss Sep 21 '22 at 14:47
  • I edited the question shortly after answering to use the normal font for the (1). To do so I removed all the options for \usepackage{caption}, so instead of the first versions where I just copied the line \usepackage[font=footnotesize, format=plain, labelfont={bf,sf}, textfont={it}, width=10pt]{caption}, I removed all the font=, format= etc stuff and used just \usepackage{caption} (17th line of code). – Marijn Sep 21 '22 at 14:58
  • Ok I found my mistake! I have already created \usepackage[labelfont={bf,sf},font={small},% labelsep=space]{caption} defined! But I want to keep the figure captions bold but the code number should not be bold. – Weiss Sep 21 '22 at 15:02
  • You can set separate caption options per type, see the caption package manual for details. – Marijn Sep 21 '22 at 15:03
  • Im new in Latex, how should i do this? – Weiss Sep 21 '22 at 15:04
  • See section 3.2 of the manual (http://mirrors.ctan.org/macros/latex/contrib/caption/caption.pdf) on page 19. You can move the settings from \usepackage to a separate \captionsetup command where you specify that the options should apply only to figures and not to anything else such as listings. – Marijn Sep 21 '22 at 15:06
  • Hi I have another question I have now used \captionsetup{style=base}. However, the numbers on the right side are indented differently, but I don't understand how I can make the numbers appear on one level on the right side. – Weiss Sep 23 '22 at 07:29
  • @Weiss it would be better to ask a separate question about this (i.e., with the Ask Question button) because it is a different issue. To make that question more clear you could try to generalize it a bit, i.e., ask about a caption for a figure instead of for a listing (if the issue indeed also applies to figures, otherwise you can use the listings example from this question again). – Marijn Sep 23 '22 at 09:21
  • I wrote a new question: https://tex.stackexchange.com/questions/659252/numbering-in-the-right-margin-and-in-brackets – Weiss Sep 23 '22 at 15:27
2

With cleveref and its macro \crefname, you can create a custom counter and assign a label to it--I have added python code for demonstration. Then, with minipage, you could create some space at the right-hand side of the code for a number; I have done it with minipage, which by default aligns a number in the middle.

In the code below, I also suggest a custom environment pythoncode with an optional parameter if for some reason you would like to increase/decrease indentation. Of course, you could parameterise any other option of the environment.

enter image description here

\documentclass{article}
% \usepackage[utf8]{inputenc}
\usepackage{geometry}
\geometry{paper=a4paper, left=24mm, right=23mm, top=20mm, bottom=20mm}
\usepackage{blindtext}
\usepackage{enumerate}
\usepackage{listings}
\lstnewenvironment{pythoncode}[1][.1]{%
  \lstset{
    basicstyle=\ttfamily\footnotesize,
    xleftmargin=#1\textwidth,
    language=Python,
  }}{}
\usepackage[noabbrev]{cleveref}

%%% New counter controlling python code numbers \newcounter{lst} \renewcommand*{\thelst}{(\arabic{lst})} % Format the counter (currently (<number>) \crefname{lst}{python code}{python codes} % Adds a label when referencing \AtBeginEnvironment{minipage}{\noindent} % Removes indentation at the beginning of each minipage

\begin{document} \blindtext

\begin{minipage}{\dimexpr\textwidth-3em}% \refstepcounter{lst}\label{lst:a}% \begin{pythoncode} def generate_grid(data, basemap, delta=1): grid = { 'lon': np.arange(-180, 180, delta), 'lat': np.arange(-89.9,89.9, delta) } grid["x"], grid["y"] = np.meshgrid(grid["lon"], grid["lat"]) grid["x"], grid["y"] = basemap(grid["x"], grid["y"]) return grid \end{pythoncode}% \end{minipage}{\raggedleft\thelst\par}

\blindtext

\begin{minipage}{\dimexpr\textwidth-3em} \refstepcounter{lst}\label{lst:b}% \begin{pythoncode} def foo(x): return x**2 \end{pythoncode} \end{minipage}{\raggedleft\thelst\par}

\Cref{lst:a} and \cref{lst:b}. \end{document}

Celdor
  • 9,058
  • This solution is more or less what the caption, newfloat and sidecap packages do 'under the hood', but it is nice to see it implemented without those packages (+1). – Marijn Sep 21 '22 at 15:01
  • @Marijn Thanks. I thought to post a comment but realised I wouldn't have enough space to suggest an alternative approach. – Celdor Sep 21 '22 at 17:07