Изменить нумерацию Latex Minted/Listings, чтобы включить текущий раздел

я использую чеканились вместе с списки пакеты LaTeX для стилей фрагментов кода в моей статье.

я пытаюсь изменить систему нумерации фрагментов кода, чтобы быть section.numberinsection. Таким образом, два фрагмента кода в моем примере ниже будут 1.1 и 1.2. Если бы в разделе 2 был третий фрагмент, он был бы пронумерован 2.1.

я делаю это так list of code snippets имеет аналогичную схему нумерации для list of tables и list of figures это уже в моей статье и имеет поведение, которое я ищу по умолчанию.

в настоящее время счетчик для фрагментов просто увеличивается от 1 для каждого фрагмента в статье.

я пытаюсь изменить вывод, используя эту конкретную строку в коде ниже:AtBeginDocument{renewcommand*{thelstlisting}{thesection.arabic{lstlisting}}} но, похоже, это не работает.

мысли?

пример Латекс:

documentclass{thesis}

% Imports
usepackage{listings}
usepackage{minted}

% Style Minted
usemintedstyle{default}
definecolor{codebg}{rgb}{0.96,0.96,0.96}
newminted{python}{bgcolor=codebg,
                    linenos=true,
                    frame=lines,
                    numbersep=5pt,
                    fontsize=footnotesize}
renewcommandlistoflistingscaption{LIST OF CODE SNIPPETS}
renewcommandlistingscaption{Code Snippet}

% Style Listings
AtBeginDocument{renewcommand*{thelstlisting}{thesection.arabic{lstlisting}}}


begin{document}
listoflistings

chapter{A Chapter}
section{A Section}
subsection{A Sub-Section}

Nam pulvinar euismod facilisis. Quisque vel sagittis diam. In ut egestas sem. Cras sit amet purus elementum, tempor nisi at, imperdiet diam. Mauris rhoncus vitae erat vel laoreet. Suspendisse interdum aliquet bibendum. Quisque venenatis leo eget neque blandit ullamcorper.

begin{listing}[H]
begin{pythoncode}
def get_path_leaf(path):
    """ return the leaf of a path. """
    if not isinstance(path, str):
        path = str(path)
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)
end{pythoncode}
caption{SPARQL Endpoint}
label{lst:SPARQL Endpoint}
end{listing}

Aenean pharetra at mauris at posuere. Vivamus ante libero, posuere et luctus in, condimentum in lacus. Nam rhoncus mi nunc, consequat rhoncus sapien lobortis eu. Fusce feugiat orci nec sollicitudin cursus. Nunc at ligula mi. Vestibulum nec pharetra lacus. Suspendisse a ultrices massa. Nulla mauris purus, tempus quis convallis id, pellentesque vel nibh.

begin{listing}[H]
begin{pythoncode}
def get_path_leaf(path):
    """ return the leaf of a path. """
    if not isinstance(path, str):
        path = str(path)
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)
end{pythoncode}
caption{SPARQL Endpoint}
label{lst:SPARQL Endpoint}
end{listing}

end{document}

выход:

enter image description hereenter image description here

Edit:

появляется minted имеет поддержку того, что мне нужно. minted уже использует listings пакет, чтобы сделать то, что он делает, поэтому мне нужно было остановить импорт listings явно, и изменил usepackage{minted} to usepackage[chapter]{minted}. Если бы я использовал section это будет номер списки против section, но также subsection (например,1.1.1 и 1.1.2 из выше образец.

мне все еще нужен способ изменить поведение нумерации на имя против section, но игнорировать subsection.

1 ответов


во-первых, разделы нумеруются \thechapter.\arabic{section}, Так что я предполагаю, что нумерация \thesection.<listing> как бы 1.1.1, 1.1.2, ...

при использовании minted счетчик в игре не lstlisting, а listing. Итак, вам нужно

\makeatletter
\renewcommand*{\thelisting}{\thesection.\arabic{listing}}
\@addtoreset{listing}{section}
\makeatother

в преамбуле. Последнее \@addtoreset сброс listing счетчик с каждым новым \section. Вы также можете сделать это за один шаг, если используете chngcntr пакет:

\usepackage{chngcntr}% http://ctan.org/pkg/chngcntr
\counterwithin{listing}{section}

на \counterwithin выполняет обе вышеупомянутые операции (представление \thelisting а также доворота).

enter image description here

\documentclass{report}

% Imports
%\usepackage{listings}
\usepackage{minted,xcolor,chngcntr}

% Style Minted
\usemintedstyle{default}
\definecolor{codebg}{rgb}{0.96,0.96,0.96}
\newminted{python}{bgcolor=codebg,
                    linenos=true,
                    frame=lines,
                    numbersep=5pt,
                    fontsize=\footnotesize}
\renewcommand\listoflistingscaption{LIST OF CODE SNIPPETS}
\renewcommand\listingscaption{Code Snippet}

% Style Listings
\counterwithin{listing}{section}

\begin{document}
\listoflistings

\chapter{A Chapter}
\section{A Section}
\subsection{A Sub-Section}

Nam pulvinar euismod facilisis. Quisque vel sagittis diam. In ut egestas sem. Cras sit amet purus elementum, tempor nisi at, imperdiet diam. Mauris rhoncus vitae erat vel laoreet. Suspendisse interdum aliquet bibendum. Quisque venenatis leo eget neque blandit ullamcorper.

\begin{listing}[H]
\begin{pythoncode}
def get_path_leaf(path):
    """ return the leaf of a path. """
    if not isinstance(path, str):
        path = str(path)
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)
\end{pythoncode}
\caption{SPARQL Endpoint}
%\label{lst:SPARQL Endpoint}
\end{listing}

Aenean pharetra at mauris at posuere. Vivamus ante libero, posuere et luctus in, condimentum in lacus. Nam rhoncus mi nunc, consequat rhoncus sapien lobortis eu. Fusce feugiat orci nec sollicitudin cursus. Nunc at ligula mi. Vestibulum nec pharetra lacus. Suspendisse a ultrices massa. Nulla mauris purus, tempus quis convallis id, pellentesque vel nibh.

\begin{listing}[H]
\begin{pythoncode}
def get_path_leaf(path):
    """ return the leaf of a path. """
    if not isinstance(path, str):
        path = str(path)
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)
\end{pythoncode}
\caption{SPARQL Endpoint}
%\label{lst:SPARQL Endpoint}
\end{listing}

\section{Another section}

Aenean pharetra at mauris at posuere. Vivamus ante libero, posuere et luctus in, condimentum in lacus. Nam rhoncus mi nunc, consequat rhoncus sapien lobortis eu. Fusce feugiat orci nec sollicitudin cursus. Nunc at ligula mi. Vestibulum nec pharetra lacus. Suspendisse a ultrices massa. Nulla mauris purus, tempus quis convallis id, pellentesque vel nibh.

\begin{listing}[H]
\begin{pythoncode}
def get_path_leaf(path):
    """ return the leaf of a path. """
    if not isinstance(path, str):
        path = str(path)
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)
\end{pythoncode}
\caption{SPARQL Endpoint}
%\label{lst:SPARQL Endpoint}
\end{listing}

\end{document} 

Вы заметите, что я использовал report класс документа, так как у меня нет thesis. Однако я предполагаю, что в какой-то степени это было бы похоже.