> 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/class-files/03-writing-your-own-package.md).

# 자신만의 패키지 작성하기

문서에서 직접 만든 명령과 매크로를 사용하는 데 가장 좋은 방법은 처음부터 새 패키지를 작성하는 것입니다. 이 글에서는 새 패키지의 기본 구조를 설명합니다.

## 소개

새 패키지를 코딩하기 전에 가장 먼저 해야 할 일은 정말 새 패키지가 필요한지 여부를 판단하는 것입니다. 다음을 검색해 보는 것이 좋습니다. [CTAN(Comprehensive TeX Archive Network)에서](http://www.ctan.org/ctan-portal/search/) 이미 필요한 것과 비슷한 것을 누군가 만들어 두었는지 확인해 보세요.

또 한 가지 중요하게 염두에 둘 것은 [패키지와 클래스의 차이입니다](/latex/ko/class-files/01-understanding-packages-and-class-files.md). 잘못 선택하면 최종 결과물의 유연성에 영향을 줄 수 있습니다.

## 전체 구조

모든 패키지 파일의 구조는 대략 다음 네 부분으로 설명할 수 있습니다:

* ***식별***. 파일은 LaTeX2ε 문법으로 작성된 패키지라고 스스로 선언합니다.
* ***예비 선언***. 여기서 필요한 외부 패키지를 불러옵니다. 또한 파일의 이 부분에는 선언된 옵션에 필요한 명령과 정의가 작성됩니다.
* ***옵션***. 패키지가 옵션을 선언하고 처리합니다.
* ***추가 선언***. 패키지의 본문 부분입니다. 패키지가 수행하는 거의 모든 것이 여기에서 정의됩니다.

다음 소단원에서는 구조에 대한 더 자세한 설명과 함께 동작 예제인 *examplepackage.sty*를 제시합니다.

### 식별

모든 패키지가 반드시 가져야 하는 간단한 명령이 두 가지 있습니다:

```latex
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{examplepackage}[2014/08/24 Example LaTeX package]
```

명령은 `\NeedsTeXFormat{LaTeX2e}` 는 패키지가 사용할 LaTeX 버전을 설정합니다. 추가로 대괄호 안에 날짜를 넣어 필요한 최소 릴리스 날짜를 지정할 수 있습니다.

명령은 `ProvidesPackage{examplepackage}[...]` 는 이 패키지를 *examplepackage* 로 식별하며, 대괄호 안에는 릴리스 날짜와 일부 추가 정보가 포함됩니다. 날짜는 YYYY/MM/DD 형식이어야 합니다.

[Overleaf에서 패키지를 작성하는 예제 열기](https://www.sharelatex.com/project/new/template?zipUrl=/project/53f11ec1eceb82a67658cb02/download/zip\&templateName=PackageExample\&compiler=pdflatex)

### 예비 선언

대부분의 패키지는 기존 패키지를 확장하고 사용자 지정하며, 동작을 위해 외부 패키지도 필요합니다. 아래에서는 샘플 패키지 "examplepackage.sty"에 더 많은 코드가 추가됩니다.

```latex
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{examplepackage}[2014/08/21 Example package]

\RequirePackage{imakeidx}
\RequirePackage{xstring}
\RequirePackage{xcolor}
\definecolor{greycolour}{HTML}{525252}
\definecolor{sharelatexcolour}{HTML}{882B21}
\definecolor{mybluecolour}{HTML}{394773}
\newcommand{\wordcolour}{greycolour}
```

이 부분의 명령은 나중에 옵션을 관리하는 데 사용될 몇몇 매개변수를 초기화하거나 외부 파일을 불러옵니다.

명령은 `\RequirePackage` 는 잘 알려진 `\usepackage`와 매우 비슷하며, 대괄호 안에 선택적 매개변수를 추가하는 것도 가능합니다. 유일한 차이점은 `\usepackage` 는 `\documentclass` 명령 앞에서는 사용할 수 없다는 점입니다. 새 패키지나 클래스를 작성할 때는 `\RequirePackage` 를 사용하는 것을 강력히 권장합니다.

[Overleaf에서 패키지를 작성하는 예제 열기](https://www.sharelatex.com/project/new/template?zipUrl=/project/53f11ec1eceb82a67658cb02/download/zip\&templateName=PackageExample\&compiler=pdflatex)

### 옵션

패키지에 어느 정도 유연성을 주기 위해 몇 가지 추가 옵션이 매우 유용합니다. 파일 "examplepackage.sty"의 다음 부분은 패키지 불러오기 문에 전달된 매개변수를 처리합니다.

```latex
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{examplepackage}[2014/08/21 Example package]

\RequirePackage{imakeidx}
\RequirePackage{xstring}
\RequirePackage{xcolor}
\definecolor{greycolour}{HTML}{525252}
\definecolor{sharelatexcolour}{HTML}{882B21}
\definecolor{mybluecolour}{HTML}{394773}
\newcommand{\wordcolour}{greycolour}

\DeclareOption{red}{\renewcommand{\wordcolour}{sharelatexcolour}}
\DeclareOption{blue}{\renewcommand{\wordcolour}{mybluecolour}}
\DeclareOption*{\PackageWarning{examplepackage}{Unknown ‘\CurrentOption’}}
\ProcessOptions\relax
```

아래에는 패키지로 전달된 옵션을 처리할 수 있는 주요 명령에 대한 설명이 나옵니다.

명령은 `\DeclareOption{}{}` 는 주어진 옵션을 처리합니다. 두 개의 매개변수를 가지며, 첫 번째는 옵션 이름이고 두 번째는 해당 옵션이 전달되었을 때 실행할 코드입니다.

명령은 `\OptionNotUsed` 는 컴파일러와 로그에 메시지를 출력하며, 해당 옵션은 사용되지 않습니다.

명령은 `\Declareoption*{}` 는 명시적으로 정의되지 않은 모든 옵션을 처리합니다. 하나의 매개변수만 가지며, 알 수 없는 옵션이 전달되었을 때 실행할 코드를 받습니다. 이 경우 다음 명령을 통해 경고를 출력합니다:

`\PackageWarning{}{}`. 자세한 설명은 [오류 처리](#handling-errors) 에서 이 명령이 하는 일을 참조하세요.

`\CurrentOption` 은 특정 시점에 처리 중인 패키지 옵션의 이름을 저장합니다.

명령은 `\ProcessOptions\relax` 는 각 옵션에 대해 코드를 실행하며, 모든 옵션 처리 명령을 입력한 뒤에 삽입해야 합니다. 이 명령에는 별표 버전이 있으며, 호출한 명령이 지정한 정확한 순서대로 옵션을 실행합니다.

예제에서는 옵션 *red* 또는 *blue* 가 `\usepackage` 명령에 문서 안에서 전달되면, 명령 `\wordcolor` 이 다시 정의됩니다. 두 색상과 기본 회색은 [예비 선언](#preliminary-declaration) 에서 *xcolor* 패키지.

[Overleaf에서 패키지를 작성하는 예제 열기](https://www.sharelatex.com/project/new/template?zipUrl=/project/53f11ec1eceb82a67658cb02/download/zip\&templateName=PackageExample\&compiler=pdflatex)

### 추가 선언

이 부분에는 대부분의 명령이 나타납니다. "examplepackage.sty"에서는 아래에서 전체 패키지 파일을 볼 수 있습니다.

```latex
\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{examplepackage}[2014/08/21 Example package]

\RequirePackage{imakeidx}
\RequirePackage{xstring}
\RequirePackage{xcolor}
\definecolor{greycolour}{HTML}{525252}
\definecolor{sharelatexcolour}{HTML}{882B21}
\definecolor{mybluecolour}{HTML}{394773}
\newcommand{\wordcolour}{greycolour}

\DeclareOption{red}{\renewcommand{\wordcolour}{sharelatexcolour}}
\DeclareOption{blue}{\renewcommand{\wordcolour}{mybluecolour}}
\DeclareOption*{\PackageWarning{examplepackage}{Unknown ‘\CurrentOption’}}
\ProcessOptions\relax

%%번호가 매겨진 환경
\\newcounter{example}[section]
\\newenvironment{example}[1][]{\\refstepcounter{example}\\par\\medskip
\noindent \textbf{My~environment~\theexample. #1} \rmfamily}{\medskip}

%%중요한 단어는 색인에 추가되고 다른 색으로 출력됩니다
\newcommand{\important}[1]
{\IfSubStr{#1}{!}
    {\textcolor{\wordcolour}{\textbf{\StrBefore{#1}{!}~\StrBehind{#1}{!}}}\index{#1}}
    {\textcolor{\wordcolour}{\textbf{#1}}\index{#1}\kern-1pt}
}
```

이 패키지는 새로운 환경 `예제`과 새로운 명령 `\important`를 정의하며, 단어를 특별한 색으로 출력하고 색인에 추가합니다.

각 명령을 완전히 이해하려면 [참조 안내서](#reference-guide) 와 [추가 읽기 섹션의](#further-reading).

아래에는 패키지를 사용하는 문서가 있습니다 *examplepackage.sty*.

```latex
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage[red]{examplepackage}

\makeindex

\title{Package Example}
\author{Team Learn ShareLaTeX}
\date{ }

\begin{document}

\maketitle

\section{Introduction}
이 문서에서는 새 패키지를 테스트합니다. 이 패키지는 특별한 번호가 매겨진
환경

\\begin{example}
이 텍스트는 특별한 환경 안에 있으며, 일부 굵은 글씨 텍스트가 출력됩니다
처음에 그리고 새로운 들여쓰기가 설정됩니다.
\\end{example}

또한 \important{important!words}를 위한 특별한 명령이 있으며, 이는
에서 사용한 매개변수에 따라 특별한 \important{colour}로
\important{package} 불러오기 문에 따라 출력됩니다. 왜냐하면 이것은 \important{important}이기 때문입니다.

\printindex

\end{document}
```

![WrittingPackagesEx1.png](/files/4741b21fddb15d0d394f2211a0a2a2c181210c54)

명령을 확인하세요

```latex
\usepackage[red]{examplepackage}
```

[Overleaf에서 패키지를 작성하는 예제 열기](https://www.sharelatex.com/project/new/template?zipUrl=/project/53f11ec1eceb82a67658cb02/download/zip\&templateName=PackageExample\&compiler=pdflatex)

## 오류 처리

새 패키지를 개발할 때는 문제가 생겼음을 사용자에게 알릴 수 있도록 가능한 오류를 처리하는 것이 중요합니다. 컴파일러에서 오류를 보고하는 주요 명령은 네 가지가 있습니다.

* `\PackageError{*package-name*}{*error-text*}{*help-text*}`. 각각 중괄호 안에 있는 세 개의 매개변수를 받습니다: 패키지 이름, 표시될 오류 텍스트(컴파일 과정이 일시 중지됨), 그리고 오류 때문에 컴파일이 일시 중지되었을 때 사용자가 "h"를 누르면 출력될 도움말 텍스트입니다.
* `\PackageWarning{*package-name*}{*warning-text*}`. 이 경우 텍스트는 표시되지만 컴파일 과정은 중단되지 않습니다. 경고가 발생한 줄 번호가 표시됩니다.
* `\PackageWarningNoLine{*package-name*}{*warning-text*}`. 이전 명령과 거의 같지만, 경고가 발생한 줄은 표시하지 않습니다.
* `\PackageInfo{*package-name*}{*info-text*}`. 이 경우 두 번째 매개변수의 정보는 줄 번호를 포함하여 전사 파일에만 출력됩니다.

[Overleaf에서 패키지를 작성하는 예제 열기](https://www.sharelatex.com/project/new/template?zipUrl=/project/53f11ec1eceb82a67658cb02/download/zip\&templateName=PackageExample\&compiler=pdflatex)

## 참조 안내서

**패키지와 클래스에서 흔히 사용되는 명령 목록**

* `\newcommand{*name*}{*definition*}`. [새 명령을 정의합니다](/latex/ko/commands/01-commands.md#defining-a-new-command), 첫 번째 매개변수는 새 명령의 이름이고, 두 번째 매개변수는 명령이 수행할 일입니다.
* `\renewcommand{}{}`. `\newcommand` 는 동일하지만 기존 명령을 덮어씁니다.
* `\providecommand{}{}`. `\newcommand` 와 동일하게 동작하지만, 명령이 이미 정의되어 있으면 조용히 무시됩니다.
* `\CheckCommand{}{}`. 문법은 `\newcommand`와 같지만, 대신 명령이 존재하는지 এবং 예상한 정의를 갖고 있는지 확인합니다. 명령이 이제 `\CheckCommand` 가 예상한 것과 다르면 LaTeX가 경고를 표시합니다.
* `\setlength{}{}`. 첫 번째 매개변수로 전달된 요소의 길이를 두 번째 매개변수에 적힌 값으로 설정합니다.
* `\mbox{}`. 중괄호 안에 적힌 요소를 담는 상자를 만듭니다.
* `\fbox{}`. `\mbox`, 하지만 내용 주위에 실제로 상자가 출력됩니다.

## 추가 읽을거리

자세한 내용은 다음을 참조하세요

* [패키지와 클래스 파일 이해하기](/latex/ko/class-files/01-understanding-packages-and-class-files.md)
* [자신만의 클래스 작성하기](/latex/ko/class-files/04-writing-your-own-class.md)
* [명령](/latex/ko/commands/01-commands.md) 및 [환경](/latex/ko/commands/02-environments.md)
* [LaTeX의 길이](/latex/ko/formatting/01-lengths-in-latex.md)
* [LaTeX에서 색상 사용](/latex/ko/formatting/13-using-colors-in-latex.md)
* [대규모 프로젝트에서의 관리](/latex/ko/document-structure/07-management-in-a-large-project.md)
* [패키지와 패키지 작성자를 위한 LaTeX2ε](http://www.latex-project.org/guides/clsguide.pdf)
* [tex에서의 프로그래밍 노트](http://pgfplots.sourceforge.net/TeX-programming-notes.pdf)
* [시간보다 짧은 분: LaTeX 리소스 사용하기](https://tug.org/pracjourn/2005-4/hefferon/hefferon.pdf)
* [The LaTeX Companion. 제2판](http://ptgmedia.pearsoncmg.com/images/9780201362992/samplepages/0201362996.pdf)


---

# 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/class-files/03-writing-your-own-package.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.
