> 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/ko/formatting/11-code-listing.md).

# 코드 목록

## 소개

LaTeX은 과학 분야에서 널리 사용되며, 프로그래밍은 과학의 여러 분야에서 중요한 측면이 되었기 때문에 코드를 올바르게 표시하는 도구가 필요합니다. 이 글에서는 표준 **verbatim** 환경과 패키지 **listings**를 사용하여 더 고급 코드 서식 지정 기능을 제공합니다. [이 별도의 글은](/latex/ko/formatting/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/68ec87b5e3833a371fc9aa3bb2fe019713a7d0d9)

도입부의 예에서와 마찬가지로, 모든 텍스트는 줄바꿈과 공백을 유지한 채 출력됩니다. 이 명령에는 별표 버전이 있으며, 출력이 약간 다릅니다.

```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/c19ca4f0bf29ad5c70d9e4fdd4d7fec67cc4134c)

이 경우 공백은 특수한 "보이는 공백" 문자로 강조됩니다: **`␣`**.

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/a2faa4e42498e51d43355138f8076f1b5c21c2c5)

명령 `\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/f8fa946e935077d34ddc8d6c4db85c81c30a71b5)

이 예에서 출력은 모든 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/55f73f422ea5f3a8aa56dd31fc11b2694199b746)

괄호 안의 추가 매개변수 `[language=Python]` 는 이 특정 프로그래밍 언어(Python)에 대한 코드 강조를 활성화하며, 특수 단어는 굵은 글꼴로, 주석은 기울임꼴로 표시됩니다. 다음을 참조하세요. [참조 가이드](#reference-guide) 지원되는 프로그래밍 언어의 전체 목록을 보려면

## 파일에서 코드 가져오기

코드는 보통 소스 파일에 저장되므로, 파일에서 코드를 자동으로 불러오는 명령은 매우 유용합니다.

```latex
다음 코드는 파일에서 직접 가져옵니다

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

![CodeListingEx3.png](/files/da9c2f981556650a7fa9bf59496fa1601593db8c)

명령 `\lstinputlisting[language=Octave]{BitXorMatrix.m}` 은 파일에서 코드를 가져옵니다 *BitXorMatrix.m*괄호 안의 추가 매개변수는 Octave 프로그래밍 언어에 대한 언어 강조를 활성화합니다. 파일의 일부만 가져와야 하는 경우 괄호 안에 쉼표로 구분된 두 매개변수를 지정할 수 있습니다. 예를 들어 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/206933f55449da2608e18c259a1bf24381a4aa05)

보시다시피, 코드 색상과 스타일링은 가독성을 크게 향상시킵니다.

이 예에서 패키지 **xcolor** 가 가져와진 뒤 명령 `\definecolor{}{}{}` 가 이후에 사용할 rgb 형식의 새 색상을 정의하는 데 사용됩니다. 자세한 내용은 다음을 참조하세요: [LaTeX에서 색상 사용하기](/latex/ko/formatting/13-using-colors-in-latex.md)

이 예의 스타일을 생성하는 명령은 본질적으로 두 가지입니다:

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

"mystyle"이라는 새 코드 목록 스타일을 정의합니다. 두 번째 중괄호 쌍 안에 이 스타일을 정의하는 옵션이 전달됩니다. 이러한 옵션과 몇 가지 다른 매개변수에 대한 전체 설명은 참고서를 참조하세요.

**\lstset{style=mystyle}**

"mystyle" 스타일을 활성화합니다. 이 명령은 필요할 때 문서 내에서 다른 스타일로 전환하는 데 사용할 수 있습니다.

## 캡션과 목록의 목록

float([표](/latex/ko/figures-and-tables/01-tables.md) 및 [그림](/latex/ko/more-topics/27-inserting-images.md))에서와 마찬가지로, 더 명확한 표시를 위해 목록에 캡션을 추가할 수 있습니다.

```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/ko/formatting/11-code-listing.md)

위 코드는 다음 출력을 생성합니다:

![CodeListingEx5.png](/files/4dc1b6f4a04e53013e5a750cc3f587f8d0b8e308)

쉼표로 구분된 매개변수 `caption=Python example` 를 괄호 안에 추가하면 캡션이 활성화됩니다. 이 캡션은 나중에 목록의 목록에서 사용할 수 있습니다.

```latex
\lstlistoflistings
```

![CodeListingEx6OLV2.png](/files/3bc516b1910e4dd122ebd6f1aedfdcde2b8383a5)

## 샘플 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/ko/formatting/12-code-highlighting-with-minted.md)
* [LaTeX에서 색상 사용하기](/latex/ko/formatting/13-using-colors-in-latex.md)
* [목차](/latex/ko/document-structure/02-table-of-contents.md)
* [대규모 프로젝트에서의 관리](/latex/ko/document-structure/07-management-in-a-large-project.md)
* [다중 파일 LaTeX 프로젝트](/latex/ko/document-structure/08-multi-file-latex-projects.md)
* [글꼴 크기, 패밀리 및 스타일](/latex/ko/fonts/01-font-sizes-families-and-styles.md)
* [글꼴 서체](/latex/ko/fonts/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/ko/formatting/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.
