> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/ja/shu-shi-she-ding/11-code-listing.md).

# コードリスト

## はじめに

LaTeX は科学分野で広く使われており、プログラミングは科学のいくつかの分野で重要な要素になっているため、コードを適切に表示するツールが必要です。この記事では、標準の **verbatim** 環境とパッケージ **listings**、より高度なコード整形機能を提供するもの [この別記事では](/latex/ja/shu-shi-she-ding/12-code-highlighting-with-minted.md) について論じています。 `minted` Python の構文強調表示を行うパッケージ `pygmentize` ライブラリです。

## verbatim 環境

LaTeX でコードを表示するための標準ツールは `verbatim`で、等幅フォントの出力を生成します。

```latex
\begin{verbatim}
\texttt{verbatim} 環境内に囲まれたテキスト
はそのまま出力され
、すべての \LaTeX{} コマンドは無視されます。
\end{verbatim}
```

[この例をOverleafで開く](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%7D%0A%5Cend%7Bdocument%7D)

上のコードは次の出力を生成します:

![Verbatim1.png](/files/d1d1e019dcc3a3b3823ad63d950e6f8375f3d076)

導入部の例と同様に、すべてのテキストは改行と空白を保持したまま出力されます。このコマンドには、出力が少し異なるスター付き版があります。

```latex
\begin{verbatim*}
\texttt{verbatim} 環境内に囲まれたテキスト
はそのまま出力され
、すべての \LaTeX{} コマンドは無視されます。
\end{verbatim*}
```

[この例をOverleafで開く](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=verbatim+text+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Bverbatim%2A%7D%0AText+enclosed+inside+%5Ctexttt%7Bverbatim%7D+environment+%0Ais+printed+directly+%0Aand+all+%5CLaTeX%7B%7D+commands+are+ignored.%0A%5Cend%7Bverbatim%2A%7D%0A%5Cend%7Bdocument%7D)

上のコードは次の出力を生成します:

![Verbatim2.png](/files/a959df3cd1b7eac2d127f063de8c47864d3cdeb3)

この場合、空白は特別な「可視空白」文字で強調されます: **`␣`**.

verbatim 風のテキストは、段落内でも `\verb` コマンド。

```latex
ディレクトリ \verb|C:\Windows\system32| には、多くの Windows
システムアプリケーションがあります。

\verb+\ldots+ コマンドは \ldots を生成します
```

[この例をOverleafで開く](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=using+the+%5Cverb+command\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cbegin%7Bdocument%7D%0AIn+the+directory+%5Cverb%7CC%3A%5CWindows%5Csystem32%7C+you+can+find+a+lot+of+Windows+%0Asystem+applications.+%0A+%0AThe+%5Cverb%2B%5Cldots%2B+command+produces+%5Cldots%0A%5Cend%7Bdocument%7D)

上のコードは次の出力を生成します:

![Verbatim3OLV2.png](/files/f83631c906fdca6185a0073a92d52e859b56b538)

コマンド `\verb|C:\Windows\system32|` 区切り文字の間にあるテキストを `|` verbatim 形式で出力します。文字と `*`以外の任意の文字を区切り文字として使えます。たとえば `\verb+\ldots+` は `+` を区切り文字として使います。

## listings を使ってコードを強調表示する

を使うには `lstlisting` 環境を文書のプリアンブルに次の行を追加する必要があります:

```latex
\usepackage{listings}
```

次に、 `lstlisting` 環境を使う例を `listings` パッケージを使ったサンプルコードです：

```latex
\begin{lstlisting}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #インシデンス行列になる予定
    VT = np.zeros((n*m,1), int)  #ダミー変数

    #ビットごとのXOR行列を計算
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[この `listings` Overleaf の例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

上のコードは次の出力を生成します:

![CodeListingEx1.png](/files/f839c7cad5216e2b2d576ac64032c4243c7af94a)

この例では、出力はすべての LaTeX コマンドを無視し、入力されたすべての改行と空白を保持してテキストを出力します。別の例を見てみましょう:

```latex
\begin{lstlisting}[language=Python]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #インシデンス行列になる予定
    VT = np.zeros((n*m,1), int)  #ダミー変数

    #ビットごとのXOR行列を計算
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[この `listings` Overleaf の例](https://www.overleaf.com/docs?engine=pdflatex\&snip_name=Python+listings+package+example\&snip=%5Cdocumentclass%7Barticle%7D%0A%5Cusepackage%7Blistings%7D%0A%5Cbegin%7Bdocument%7D%0A%5Cbegin%7Blstlisting%7D%5Blanguage%3DPython%5D%0Aimport+numpy+as+np%0A++++%0Adef+incmatrix%28genl1%2Cgenl2%29%3A%0A++++m+%3D+len%28genl1%29%0A++++n+%3D+len%28genl2%29%0A++++M+%3D+None+%23to+become+the+incidence+matrix%0A++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29++%23dummy+variable%0A++++%0A++++%23compute+the+bitwise+xor+matrix%0A++++M1+%3D+bitxormatrix%28genl1%29%0A++++M2+%3D+np.triu%28bitxormatrix%28genl2%29%2C1%29+%0A%0A++++for+i+in+range%28m-1%29%3A%0A++++++++for+j+in+range%28i%2B1%2C+m%29%3A%0A++++++++++++%5Br%2Cc%5D+%3D+np.where%28M2+%3D%3D+M1%5Bi%2Cj%5D%29%0A++++++++++++for+k+in+range%28len%28r%29%29%3A%0A++++++++++++++++VT%5B%28i%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28i%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+r%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++VT%5B%28j%29%2An+%2B+c%5Bk%5D%5D+%3D+1%3B%0A++++++++++++++++%0A++++++++++++++++if+M+is+None%3A%0A++++++++++++++++++++M+%3D+np.copy%28VT%29%0A++++++++++++++++else%3A%0A++++++++++++++++++++M+%3D+np.concatenate%28%28M%2C+VT%29%2C+1%29%0A++++++++++++++++%0A++++++++++++++++VT+%3D+np.zeros%28%28n%2Am%2C1%29%2C+int%29%0A++++%0A++++return+M%0A%5Cend%7Blstlisting%7D%0A%5Cend%7Bdocument%7D)

上のコードは次の出力を生成します:

![CodeListingEx2.png](/files/c79ee0cd7d8c0b37c2f3c1027e1b433533c82f13)

角括弧内の追加パラメータ `[language=Python]` は、この特定のプログラミング言語（Python）のコード強調表示を有効にし、特別な単語は太字で、コメントは斜体で表示されます。 [リファレンスガイド](#reference-guide) 対応しているプログラミング言語の完全な一覧は

## ファイルからコードを取り込む

コードは通常ソースファイルに保存されるため、ファイルからコードを自動的に取り込むコマンドは非常に便利です。

```latex
次のコードはファイルから直接取り込まれます

\lstinputlisting[language=Octave]{BitXorMatrix.m}
```

![CodeListingEx3.png](/files/20ac230483548e79f3be2159fe73baa818a1d329)

コマンド `\lstinputlisting[language=Octave]{BitXorMatrix.m}` は、ファイル *BitXorMatrix.m*、角括弧内の追加パラメータにより Octave プログラミング言語の強調表示が有効になります。ファイルの一部だけを取り込みたい場合は、角括弧内にコンマ区切りの 2 つのパラメータを指定できます。たとえば、2 行目から 12 行目までのコードを取り込むには、前のコマンドは

```latex
\lstinputlisting[language=Octave, firstline=2, lastline=12]{BitXorMatrix.m}
```

もし `firstline` または `lastline` が省略されている場合、その値はそれぞれファイルの先頭、または末尾とみなされます。

## コードのスタイルと色

でのコード整形 **listings** パッケージによるコード整形は非常にカスタマイズ可能です。例を見てみましょう

```latex
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{mystyle}{
    backgroundcolor=\color{backcolour},
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    numbers=left,
    numbersep=5pt,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2
}

\lstset{style=mystyle}

\begin{document}
次のコードはファイルから直接取り込まれます

\lstinputlisting[language=Octave]{BitXorMatrix.m}
\end{document}
```

上のコードは次の出力を生成します:

![CodeListingEx4.png](/files/0ec8e58e971f77cdebcc7d5879f2d8d8ab64e7af)

ご覧のとおり、コードの色付けとスタイル設定により可読性が大幅に向上します。

この例ではパッケージ **xcolor** が読み込まれ、その後コマンド `\definecolor{}{}{}` が rgb 形式で新しい色を定義するために使われ、後で利用されます。詳細は以下を参照してください: [LaTeX で色を使う](/latex/ja/shu-shi-she-ding/13-using-colors-in-latex.md)

この例のスタイルを生成するコマンドは基本的に 2 つあります:

**\lstdefinestyle{mystyle}{...}**

「mystyle」と呼ばれる新しいコード一覧スタイルを定義します。2 組目の波括弧内に、このスタイルを定義するオプションが渡されます。これらおよび他のいくつかのパラメータの詳細は、リファレンスガイドを参照してください。

**\lstset{style=mystyle}**

「mystyle」スタイルを有効にします。このコマンドは、必要に応じて文書内で別のスタイルに切り替えるために使用できます。

## キャプションと Listings の一覧

フロート（[表](/latex/ja/to/01-tables.md) や [図](/latex/ja/sononotopikku/27-inserting-images.md)）と同様に、よりわかりやすくするために listing にキャプションを追加できます。

```latex
\begin{lstlisting}[language=Python, caption=Python example]
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #インシデンス行列になる予定
    VT = np.zeros((n*m,1), int)  #ダミー変数

    #ビットごとのXOR行列を計算
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1)

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{lstlisting}
```

[この `listings` Overleaf の例](/latex/ja/shu-shi-she-ding/11-code-listing.md)

上のコードは次の出力を生成します:

![CodeListingEx5.png](/files/52822f2f9f0f26a4f0540f2d4d7e00c086433479)

コンマ区切りのパラメータ `caption=Python example` を角括弧内に追加すると、キャプションが有効になります。このキャプションは後で Listings の一覧で使用できます。

```latex
\lstlistoflistings
```

![CodeListingEx6OLV2.png](/files/a213c8ba28ad2342f0e89d4b93104c9c562838d2)

## Overleaf のサンプルプロジェクト

このリンクを開いて [を試してみてください `listings` Overleaf でのパッケージの例。](https://www.overleaf.com/project/new/template/20053?id=68266290\&templateName=listings+package+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

## リファレンスガイド

### 対応言語

**対応言語（可能であればその方言も。方言は括弧内に示され、既定の方言は斜体で示されます）:**

|                                                        |                                                  |
| ------------------------------------------------------ | ------------------------------------------------ |
| ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, *R/3 6.10*) | ACSL                                             |
| Ada (*2005*, 83, 95)                                   | Algol (60, *68*)                                 |
| Ant                                                    | Assembler (Motorola68k, x86masm)                 |
| Awk (*gnu*, POSIX)                                     | bash                                             |
| Basic (Visual)                                         | C (*ANSI*, Handel, Objective, Sharp)             |
| C++ (ANSI, GNU, *ISO*, Visual)                         | Caml (*light*, Objective)                        |
| CIL                                                    | Clean                                            |
| Cobol (1974, *1985*, ibm)                              | Comal 80                                         |
| command.com (*WinXP*)                                  | Comsol                                           |
| csh                                                    | Delphi                                           |
| Eiffel                                                 | Elan                                             |
| erlang                                                 | Euphoria                                         |
| Fortran (77, 90, *95*)                                 | GCL                                              |
| Gnuplot                                                | Haskell                                          |
| HTML                                                   | IDL (empty, CORBA)                               |
| inform                                                 | Java (empty, AspectJ)                            |
| JVMIS                                                  | ksh                                              |
| Lingo                                                  | Lisp (empty, Auto)                               |
| Logo                                                   | make (empty, gnu)                                |
| Mathematica (1.0, 3.0, *5.2*)                          | Matlab                                           |
| Mercury                                                | MetaPost                                         |
| Miranda                                                | Mizar                                            |
| ML                                                     | Modula-2                                         |
| MuPAD                                                  | NASTRAN                                          |
| Oberon-2                                               | OCL (decorative, *OMG*)                          |
| Octave                                                 | Oz                                               |
| Pascal (Borland6, *標準*, XSC)                           | Perl                                             |
| PHP                                                    | PL/I                                             |
| Plasm                                                  | PostScript                                       |
| POV                                                    | Prolog                                           |
| Promela                                                | PSTricks                                         |
| Python                                                 | R                                                |
| Reduce                                                 | Rexx                                             |
| RSL                                                    | Ruby                                             |
| S (empty, PLUS)                                        | SAS                                              |
| Scilab                                                 | sh                                               |
| SHELXL                                                 | Simula (*67*, CII, DEC, IBM)                     |
| SPARQL                                                 | SQL                                              |
| tcl (empty, tk)                                        | TeX (AlLaTeX, common, LaTeX, *plain*, primitive) |
| VBScript                                               | Verilog                                          |
| VHDL (empty, AMS)                                      | VRML (*97*)                                      |
| XML                                                    | XSLT                                             |

### コード一覧スタイルをカスタマイズするためのオプション

* **backgroundcolor** - 背景色。外部の ***color*** または ***xcolor*** パッケージが必要です。
* **commentstyle** - ソース言語のコメントのスタイル。
* **basicstyle** - ソースのフォントサイズ/書体など（例: `basicstyle=\ttfamily\small`)
* **keywordstyle** - ソース言語のキーワードのスタイル（例: `keywordstyle=\color{red}`)
* **numberstyle** - 行番号に使うスタイル
* **numbersep** - コードから行番号までの距離
* **stringstyle** - ソース言語の文字列のスタイル
* **showspaces** - コード内の空白を強調表示するか（true/false）
* **showstringspaces** - 文字列内の空白を強調表示するか（true/false）
* **showtabs** - コード内のタブを強調表示するか（true/false）
* **numbers** - 行番号の位置（left/right/none、つまり行番号なし）
* **prebreak** - 折り返し行の末尾に表示する印（例: `prebreak=\raisebox{0ex}[0ex][0ex]{\ensuremath{\hookleftarrow}}`)
* **captionpos** - キャプションの位置（t/b）
* **frame** - コード外に枠を表示するか（none/leftline/topline/bottomline/lines/single/shadowbox）
* **breakatwhitespace** - 自動改行を空白でのみ行うかどうかを設定します
* **breaklines** - 自動改行
* **keepspaces** - コード内の空白を保持する。字下げに便利
* **tabsize** - 既定のタブ幅
* **escapeinside** - ソースコードから LaTeX にエスケープするための文字を指定する（例: `escapeinside={\%*}{*)}`)
* **rulecolor** - フレームボックスの色を指定する

## さらに読む

詳しくは以下を参照してください：

* [minted を使ったコードの強調表示](/latex/ja/shu-shi-she-ding/12-code-highlighting-with-minted.md)
* [LaTeXで色を使う](/latex/ja/shu-shi-she-ding/13-using-colors-in-latex.md)
* [目次](/latex/ja/wen-shu-gou-zao/02-table-of-contents.md)
* [大規模プロジェクトでの管理](/latex/ja/wen-shu-gou-zao/07-management-in-a-large-project.md)
* [複数ファイルの LaTeX プロジェクト](/latex/ja/wen-shu-gou-zao/08-multi-file-latex-projects.md)
* [フォントサイズ、ファミリー、スタイル](/latex/ja/fonto/01-font-sizes-families-and-styles.md)
* [フォントの書体](/latex/ja/fonto/02-font-typefaces.md)
* [**listings** パッケージのドキュメント](https://texdoc.org/serve/listings/0)
* [**listings** CTAN ウェブサイト](http://www.ctan.org/pkg/listings)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/ja/shu-shi-she-ding/11-code-listing.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
