リストでPythonコメントを非表示にする

リストでPythonコメントを非表示にする

リストでフォーマットされる Python コードを含めたいのですが、コードは簡潔で整然としたものにしたいだけです。コメントは一切印刷されず、空行も印刷されません。

簡単解決策としては、コードからコメントを削除することが考えられますが、それでは問題を回避し、解決策を見つけることはできません。解決策が必要です。解決策とは、インポートするソースファイルを編集する必要がないことを意味します。

私は次のことを試しました:

アプローチ1

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [l][\nullfont]{\#},
    emptylines   = *1,
}

これはコメントを印刷しませんが、テキストが出力に到達すると行はそこに残ります。LaTeX はそれを で印刷しますnullfont

アプローチ2

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [is]{\#}{\^^M},
    emptylines   = *1,
}

アプローチ 2 では、行の終わりまでのすべてのコメント行が無視されます#。問題は、行の終わりも消えてしまうことです。次のコードがあるとします。

def foo():
    if cond1: bar() #Some explanation
    if cond2: baz() #Some other explanation
    if cond3: bye() #Even more explanations

次のように印刷されます:

def foo():
    if cond1: bar()        if cond2: baz()        if cond3: bye()

それは望ましくなく、非ピュートン的で、醜いものです。

アプローチ3

\lstdefinestyle{py_without_comments}{%
    language     = python,
    morecomment  = [il]{\#},
    emptylines   = *1,
}

これはうまく動作するはずですが、何らかの理由で最初のコメントからすべてのコードが消去されます (foo()例を参照)。

そこで、何か他の方法を試してみようと思っています。リストではこれができないのでしょうか?

よろしくお願いします。


編集1:

MWEは見つかりますここ

答え1

ここに、動作するものがあります。これは、内部の一部で動作しますlistings。より良い解決策があるかどうかはわかりません。行末区切り文字 (上記のアプローチ 2) を消費し、行が空でない場合はそれを追加し直すことは、機能しないようです。

\documentclass[11pt]{article}
\usepackage{xcolor}
\usepackage{listings}

% Default settings.
\lstset{
  basicstyle=\ttfamily,
  numbers=left,
  numbersep=5pt,
  numberstyle=\tiny\color{gray},
  rulecolor=\color{black},
}

% The \incomment macro and auxiliary stuff.
\newif\ifnocomment
\newif\ifemptyline
\makeatletter
% When a line starts, it's empty and we're not in a comment.
\lst@AddToHook{InitVarsBOL}{\global\emptylinetrue\global\nocommenttrue}
% When something is printed, the line is not empty.
\lst@AddToHook{PostOutput}{\global\emptylinefalse}
% When we're in a comment...
\def\incomment#1{%
  % if we just entered...
  \ifnocomment%
    \global\nocommentfalse%
    % and the line is empty, then remove this line.
    \ifemptyline\global\advance\lst@newlines\m@ne\fi%
  \fi}
\makeatother

\lstdefinestyle{python_without_comments}{%
  language=python,
  morecomment=[l][\incomment]{\#},
}

\begin{document}
\begin{lstlisting}[style=python_without_comments]
def f(x): return x + 1 #

# This is function foo...
def foo():
  if cond1: bar()  # Some explanation
  if cond2: baz()  # Some other explanation
  if cond3: bye()  # Even more explanations

# And this is function bar
def bar():  # let's see
  # some more comment
  return 42 # here?
\end{lstlisting}
\end{document}

結果は次のとおりです。 結果

そこにコメントがある場合は、テキストの最後に空行が印刷されることがあります。これを削除する方法がわかりません。


編集: 私の最初の回答OutputBoxでは、 の代わりにhook を使用しましたPostOutput。これはタブではうまく機能しませんでした。

関連情報