단계 4 · 구조와 교차 참조 32 / 48 ≈ 20 분 분량

LaTeX 헤더와 푸터: fancyhdr, 쪽 번호, 페이지 스타일

페이지 가구는 당신이 명령을 친 자리에서가 아니라 출력 루틴에 의해 조판됩니다. 헤더가 mark를 필요로 하고, headheight를 쓰기에 앞서 선언해 두어야 하며, 장의 첫 페이지가 다른 스타일을 유지하는 이유가 전부 거기서 나옵니다. 이 강의는 세로로 쌓인 띠를 칸 하나씩 풀어 봅니다.

    페이지는 띠를 쌓은 더미이고, 그중 하나만 당신의 글이다

    \textheight 위에는 길이 셋과 TeX이 스스로 더하는 하나, 넷이 놓여 있습니다. 용지 맨 위에서부터 세어 보면 이렇습니다. 먼저 아무 글자도 조판되지 않는 1인치가 있습니다 — TeX 프리미티브 오프셋이라서 LaTeX 매뉴얼이 말하는 "상단 여백"이 눈금자로 재낸 값과 한 번도 일치하지 않지요. 이어서 \voffset에 \topmargin을 더한 만큼 내려가면 머리글 상자의 위쪽 가장자리에 닿고, 여기서 \headheight이 그 상자에 선언된 높이만큼 지나갑니다. 마지막으로 \headsep이 가로선과 본문 첫 줄 사이의 틈을 만듭니다. 본문 아래에는 \skip\footins와 각주 삽입물이 자리하고, 이어서 \footskip이 바뀐말 첫 줄의 기준선까지 측정됩니다 — 바뀐말 상자의 위변까지가 아닙니다.

    가장 자주 틀리는 숫자가 \headheight와 \footskip입니다. \headheight는 "내가 원하는 여유"가 아니라 출력 루틴이 그대로 믿는 선언입니다. 머리글 내용의 키가 선언값을 넘으면 TeX은 페이지를 다시 자르지 않습니다. 머리글 상자가 본문 첫 줄을 덮고, 증거는 로그의 한 줄로만 남습니다. \footskip이 너무 작으면 바뀐말이 각주 영역으로 밀려들고, 각주가 많은 문서에서 충돌은 정확히 그 지점에서 터집니다.

    전부 geometry에 맡기고 \textheight가 나머지 페이지와 맞도록 유지하십시오: \usepackage[a4paper,top=2.5cm,bottom=2.8cm,headheight=15pt,headsep=14pt,footskip=26pt]{geometry}. 클래스가 페이지를 계산한 뒤에 \setlength로 손으로 정하는 일도 가능합니다. 옛 클래스들이 그렇게 조절되던 방식이지요. 다만 그러면 \textheight와 \vsize, 상단 여백을 같은 편집에서 함께 고쳐야 하고, 바로 그 산수를 대신하려고 존재하는 패키지가 geometry입니다.

    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    Page geometry: the vertical band stack that carries a header and a footer, and the headwidth a header rule is drawn to THE VERTICAL STACK, TOP OF THE PAPER TO BOTTOM 1in + \voffset + \topmargin (TeX adds the inch itself) \headheight - declared, not measured \headsep \textheight a footnote mark sits in the line; \skip\footins footnote rule, then the notes (an insertion: it is part of the page, not the text) \footskip - measured to the BASELINE of this line the bottom margin that is left over; a footer taller than \footskip reaches into it, and a footer with two lines needs \footskip raised as well headheight headsep textheight footskip HORIZONTAL: THE RULE SPANS headwidth text block = \textwidth \headwidth (fancyheadoffset extends it) L offset R offset the rule is an \hbox to\headwidth, so changing \textwidth without reloading geometry leaves a short rule HOW TO SET IT \usepackage[a4paper,top=2.5cm,bottom=2.8cm, headheight=15pt,headsep=14pt,footskip=26pt]{geometry} geometry keeps textheight consistent with the bands you asked for. \setlength{\headheight}{15pt} % legal, but recompute textheight yourself fancyhdr prints the value it measured - use exactly that number, then recompile: a taller band moves every page break below it, and can raise a new requirement TeX always starts the text 1 inch plus \voffset plus \topmargin below the top edge of the paper, which is why a hand-set \topmargin looks wrong and why geometry's top= is measured from the text block, not the header.
    용지 가장자리에서 가장자리까지 쌓아 올린 세로 더미. headheight와 footskip은 소원이 아니라 선언입니다.

    스타일 모델: pagestyle와 thispagestyle의 분담

    가구에 관해 LaTeX은 상태를 두 개 유지합니다. \pagestyle{X}는 지금부터 모든 페이지의 스타일을 정하고, \thispagestyle{Y}는 그 페이지에서만 덮어쓴 뒤 페이지가 내보내지는 순간 잊힙니다. 내장 스타일은 넷입니다: empty(아무것도 없음), plain(바뀐말 가운데 쪽 번호 — 표준 클래스의 기본값), headings(mark로 만드는, 가로선 없는 두 줄의 이어지는 머리글), myheadings(생김새는 같고 내용만 \markboth로 당신이 직접 넣는 것).

    여기서 생기는 충돌이 첫 페이지에 대해 가장 많이 나오는 질문을 만듭니다. 어떤 단위를 시작하는 명령은 자기 \thispagestyle를 발행하기 때문입니다. \maketitle은 plain을, \chapter도 plain을 쓰고, \part와 \tableofcontents도 같으며, \cleardoublepage는 필요할 때 끼워 넣는 빈 뒷면에 empty를 지정합니다. 그래서 \thispagestyle{empty}는 \maketitle 뒤에 써야 하고 앞에 쓰면 안 됩니다. 나중에 온 호출이 이깁니다. 모든 장의 첫 페이지에서 쪽 번호를 지우는 방법은 페이지별 호출과 싸우는 것이 아니라 그 호출이 지정한 스타일 자체를 다시 정의하는 것이고, 그것을 위해 존재하는 명령이 \fancypagestyle{plain}{...}입니다.

    titlepage 안에서 손으로 만드는 표지에도 같은 규칙이 적용됩니다. \thispagestyle{empty}를 \begin{titlepage} 바로 뒤에 두십시오. 환경은 페이지를 내보내면서 끝나고, 가구 선택은 그 순간에 마지막으로 읽힌 호출을 보고 정해지기 때문입니다.

    headings 스타일은 fancyhdr를 도입하기 전에라도 만져 볼 가치가 있습니다. 이어지는 머리글이 무엇으로 만들어지는지를 그대로 보여주지요: 짝수 페이지에는 \leftmark, 홀수 페이지에는 \rightmark, 그리고 나머지는 전부 mark뿐입니다. 다음 절들이 풀어 나갈 메커니즘 전체가 여기 있습니다.

    fancyhdr: 여섯 칸과 두 문단·세 문단 모델

    fancyhdr는 머리글과 바뀐말을 각각 상자 셋으로 이루어진 가로줄로 대체하므로 칸이 여섯 개가 됩니다: \fancyhead[L], \fancyhead[C], \fancyhead[R] 그리고 \fancyfoot[L], [C], [R]. 설정은 언제나 \fancyhf{}로 시작하십시오. 여섯 칸이 모두 비고, 이 한 줄이 없으면 이전 정의가 남긴 것이 그대로 물려집니다. 한 줄은 \hbox 하나로 조판됩니다. 가운데 칸이 비어도 아무 일이 일어나지 않고, 왼쪽 칸이 너무 넓으면 가운데 칸이 축에서 밀려나는 이유가 그 때문입니다. 모델은 "나란히 놓인 문단 셋"이지 "자유로이 배치하는 독립 상자 셋"이 아닙니다.

    양면 문서에서는 칸이 두 벌로 늘고, 선택자 인자가 어떤 페이지에 무엇을 줄지를 정합니다: E 짝수 페이지, O 홀수 페이지, L 왼쪽 페이지, R 오른쪽 페이지, C 양쪽 모두. \fancyhead[LE,RO]{\thepage}가 전형적인 바깥쪽 쪽 번호이고, \fancyhead[RE]{\leftmark}\fancyhead[LO]{\rightmark}가 전형적인 대칭 머리글입니다 — 장 제목은 뒷면에, 절 제목은 앞면에. \fancyhead[L]을 "왼쪽 페이지"라는 뜻으로 쓰면 안 됩니다. 왼쪽 칸이라는 뜻이고, 대칭 머리글 디버깅의 대부분은 바로 이 구분에서 갈립니다.

    구현 방식에서 세 가지는 평범한 문서에도 그대로 영향을 미칩니다. 빈 칸도 여전히 상자입니다 — fancyhdr는 줄에 높이를 주려고 \strut에 상당하는 것으로 채워 넣기 때문에, 머리글 내용이 아예 없어도 \headheight는 0이 아니어야 합니다. 머리글 아래 가로선은 \headrule이고, \textwidth까지가 아니라 \headwidth까지 그려지며, 두께는 \headrulewidth입니다. 0pt로 두면 선이 사라지고, \renewcommand{\footrulewidth}{0.4pt}를 더하면 바뀐말 위에 대응하는 선이 생깁니다. 그리고 \headwidth는 \fancyheadoffset으로 여백까지 늘릴 수 있는데, 여백 상자까지 뻗는 머리글의 선을 용지 전체 너비로 긋는 보통의 방법이 이것입니다.

    색을 넣고 싶다고 선을 \textcolor로 감싸지 마십시오. 선 자체가 \hbox to\headwidth{\leaders\hrule ...}이니 정의를 고치는 쪽이 맞습니다: \renewcommand{\headrule}{\hbox to\headwidth{\color{accent}\leaders\hrule height \headrulewidth\hfill}}. 이중선도 같은 방법입니다. 상자 안에 서로 다른 높이의 \hrule을 두 개 넣으면 됩니다.

    w_{\text{rule}} = \text{headwidth} = \text{textwidth} + l_{\text{offset}} + r_{\text{offset}}
    w_{\text{rule}} = \text{headwidth} = \text{textwidth} + l_{\text{offset}} + r_{\text{offset}}
    fancyhdr slot model: three boxes per row, doubled by page selector for even and odd pages of a twoside document EVEN (LEFT-HAND) PAGE LE \leftmark CE RE \thepage \headrule, drawn to \headwidth LF CF \today RF ODD (RIGHT-HAND) PAGE LO \rightmark CO RO same row, mirrored content LF CO RF \thepage THE SELECTOR ARGUMENT E even O odd L lefthand R righthand C both [LE,RO] -> folio at the outer top of a twoside book [RE,LO] -> chapter on the verso, section on the recto [L] alone fills the LEFT SLOT on every page, which in a twoside layout is not "left page" - the usual misread \fancyhf{} clears all six; do it before you fill any MECHANICS THAT SHOW UP AS BUGS An empty slot is still a box: fancyhdr keeps a strut in it, so \headheight must be non-zero even with no content. The row is one \hbox, so a wide left box pushes the centre box off the middle of the page - the classic crooked header. \headrulewidth 0pt removes the rule; \footrulewidth adds one. \nouppercase undoes the \MakeUppercase the class put into the mark - the standard classes, not fancyhdr, do that. \fancypagestyle{plain}{...} restyles chapter first pages.
    페이지마다 이름 붙은 칸 여섯 개, 양면 문서에서는 두 벌로 늘어납니다. 선택자 글자가 어느 페이지의 어느 칸인지를 정합니다.
    \documentclass[11pt,a4paper]{article}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    % headheight must be big enough for what the header holds; geometry then
    % keeps \textheight consistent with the rest of the page.
    \usepackage[a4paper,top=2.5cm,bottom=2.8cm,left=3cm,right=3cm,
                headheight=15pt,headsep=14pt,footskip=26pt]{geometry}
    \usepackage{xcolor}
    \usepackage{lastpage}       % \pageref{LastPage} for "of 12"
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}                                % clear all six slots first
    \fancyhead[L]{\small\nouppercase{\leftmark}}
    \fancyhead[R]{\small\itshape A. Student}
    \fancyfoot[C]{\small\thepage\ of \pageref{LastPage}}
    
    \renewcommand{\headrulewidth}{0.4pt}
    \renewcommand{\footrulewidth}{0pt}
    \renewcommand{\headrule}{%
      \hbox to\headwidth{\color{blue!60!black}\leaders\hrule height \headrulewidth\hfill}}
    \setlength{\headwidth}{\textwidth}
    
    \title{Headers and footers, concretely}
    \author{A. Student}
    
    \begin{document}
    \maketitle                      % \maketitle issues its own \thispagestyle{plain}
    \thispagestyle{empty}           % so the override goes AFTER it, never before
    
    \section{Definitions}
    Because the section title is put into the left mark by the class, the header of
    this page reads \emph{Definitions}. A running head has to be produced from a
    mark, not from the heading command itself: the header is typeset when the page
    is shipped out, long after the heading was seen.
    
    \begin{equation}
      \label{eq:cauchy}
      \int_{\gamma} f(z)\,dz = 0
    \end{equation}
    Equation \eqref{eq:cauchy} is unaffected by any of the above, which is the point:
    page furniture and content are laid out by different mechanisms.
    
    \section{Further remarks}
    A two-line header needs a larger \verb|headheight|: ask geometry for
    \verb|headheight=26pt| instead of ignoring the warning, and recompile, because
    the taller band moves every page break below it.
    \end{document}

    headheight 경고와 마땅히 할 일

    메시지는 대충 이렇게 읽힙니다: Package fancyhdr Warning: \headheight is too small (12.0 pt). 이어서 측정된 머리글 치수와 권고값이 따라 나옵니다. 장식용 경고가 아닙니다. fancyhdr는 정의한 머리글 상자의 자연 높이를 계산해 선언된 \headheight와 견주고, 선언이 더 작으면 상자를 줄일 방법이 없습니다 — 페이지는 이미 잘린 뒤라서, 상자는 본문 첫 줄을 덮고 그 사실은 로그에만 남습니다.

    페이지를 정한 그 순서대로, 선언의 뿌리에서 고치면 됩니다. geometry를 쓴다면 옵션에 headheight=15pt(또는 fancyhdr가 인쇄해 준 값)를 더하십시오. \setlength을 직접 쓰는 방식이라면 프리앰블에 \setlength{\headheight}{15pt}를 쓰되, 이 값을 고쳐도 \textheight가 자동으로 다시 계산되지는 않는다는 점을 기억하세요. 본문이 페이지 아래로 더 내려갑니다. 그 다음 다시 컴파일합니다. 머리글 높이가 바뀌면 \textheight 주변 자료가 움직이고, 페이지 나누기가 옮겨가고, 그러면 mark가 바뀌고, 다시 머리글 너비가 바뀌어서 새 숫자로 경고가 되살아날 수 있습니다.

    원인은 언제나 넷 중 하나입니다. 머리글 줄에 \frac이나 디스플레이에 가까운 재료를 넣는 경우 — 본문 줄보다 키가 훨씬 큽니다. 수식은 작게(\scriptstyle) 만들거나 \mbox{} 안에 \footnotesize로 넣으십시오. 두 줄 머리글은 대략 두 배의 높이를 필요로 하며, 층층이 쌓은 머리글을 쓴 논문이 왜 26pt 이상을 선언하는지가 바로 그 때문입니다. \includegraphics 로고를 머리글에 넣는 경우. 그리고 클래스가 12pt에서 \headheight를 아주 작게 놓는 경우 — 표준 클래스가 실제로 그렇습니다.

    관련되면서 똑같이 실제적인 경고도 있습니다. fancyhdr는 headwidth에 대해서도 경고합니다("~headwidth ... overwritten"). geometry 같은 패키지가 fancyhdr가 읽은 뒤에 텍스트 블록을 움직일 때 그렇고, 바뀐말과 \footskip이 페이지 밖으로 나갈 때는 충돌이 이어집니다. 처방은 둘 다 같습니다. geometry를 먼저, 모든 값이 정해진 상태에서 올리고 그다음 fancyhdr를 올리며, 이후에는 두 길이를 손으로 다시 건드리지 마십시오.

    mark: 머리글은 지금 위치를 어떻게 아는가

    머리글은 "내가 어느 절에 들어 있는지"를 물을 수 없습니다. 머리글이 조판되는 시점에는 제목 명령이 이미 지나갔고 페이지는 출력 루틴에 의해 잘린 뒤이기 때문입니다. 메커니즘은 mark입니다. \markboth{left text}{right text}가 호출되는 지점의 세로 목록에 메모를 떨어 놓고, 출력 루틴이 내보내지는 페이지에서 그 메모를 주워 읽습니다. 표준 클래스는 이 일을 대신 해 줍니다 — \section이 \sectionmark{...}를 발행하고, 그 정체가 \markboth{...}{...}입니다 — 이어지는 머리글의 글자는 여기서 나옵니다.

    혼동은 대부분 읽어 내는 쪽에 있습니다. 커널 문서는 여기서 정확합니다: \leftmark는 그 페이지의 마지막 왼쪽 mark를 돌려주고, \rightmark는 처음 오른쪽 mark를 돌려줍니다. 그 비대칭은 의도된 것입니다 — 장은 넘기면서 뒷면에, 절은 들어가면서 앞면에 두는 설계이지요. 그래서 어느 칸을 썼는지에 따라 머리글이 "절 하나 뒤"이거나 "절 하나 앞"으로 보입니다. 그밖에 \topmark(페이지 윗부분에서 유효했던 mark), \firstmark, \botmark도 있습니다.

    2020년 mark 갱신 이후 LaTeX은 mark 클래스마다 처음값과 마지막값을 따로 보관해서, 없던 조합까지 얻을 수 있습니다. \markboth/\markright가 쓰는 클래스 이름은 2e-left, 2e-right, 2e-right-nonempty이고, 일반 읽기 명령은 \TopMark{class}, \FirstMark{class}, \LastMark{class}입니다 — 따라서 \LastMark{2e-right}는 페이지의 마지막 절을 주며, "지금 X를 읽고 있습니다" 형식 머리글이 원하는 것이 정확히 그쪽입니다. 당신만의 mark는 \NewMarkClass{status}에 \InsertMark{status}{text}를 조합해 만듭니다. 매뉴얼이 강조하는 함정도 하나 있습니다: mark 읽기는 출력 루틴 안에서만 의미가 있고, 단면 문서에서는 표준 클래스가 오른쪽 mark만 놓으므로 \leftmark는 설계상 비어 있을 수 있습니다.

    mark가 만드는 실무 문제 둘은 한 줄씩으로 고쳐집니다. 대문자 문제: 표준 클래스는 mark에 \MakeUppercase를 넣어 두고, fancyhdr는 칸에서 그것을 되돌리는 \nouppercase를 제공하므로 상용구가 \fancyhead[RE]{\nouppercase{\leftmark}}가 됩니다. 악센트나 수식을 담은 제목 문제: mark는 조판된 형태를 담기 때문에, \texorpdfstring이나 \footnote가 들어간 절 제목은 짧은 선택 인자가 필요합니다 — \section[Plain form]{Pretty form} — 그렇지 않으면 머리글에 당신이 원치 않은 가구가 함께 들어갑니다.

    \text{leftmark} = \text{last left mark on the page}, \qquad \text{rightmark} = \text{first right mark on the page}
    \text{leftmark} = \text{last left mark on the page}, \qquad \text{rightmark} = \text{first right mark on the page}
    How a running head is produced: a mark is dropped into the vertical list where the heading is typeset and read back by the output routine when the page is cut STEP 1 - THE HEADING DROPS A MARK INTO THE TEXT \section{Modules} the class runs \sectionmark{Modules} \markboth{Modules}{Modules} left class -> even pages right class -> odd pages the mark is not typeset: it is a note left in the vertical list STEP 2 - THE PAGE IS CUT, AND THE ROUTINE READS THE NOTES material collected for this page: mark: "Modules" (first on page) mark: "Ideals" (last on page) \topmark what was current at the top \FirstMark{class} \LastMark{class} \leftmark = LAST left, \rightmark = FIRST right the kernel documents that asymmetry; it is not a bug STEP 3 - THE SLOTS CONSUME THE VALUES \fancyhead[RE]{\nouppercase{\leftmark}} \fancyhead[LO]{\nouppercase{\rightmark}} the header box is built inside the output routine, which is why only marks can drive it - not a counter and not "the last \section" \FirstMark{2e-left} \LastMark{2e-right} THREE CASES THAT LOOK LIKE BROKEN HEADERS unnumbered heading \section*{Acknowledgements} sets no mark at all, so the head still shows the previous section. fix: \markboth{...}{...} by hand, then \addcontentsline for the TOC heading at the very top of a page a section that begins the page is both the first and the last mark - so \rightmark reads the NEW title while \leftmark-style reading of the previous one is what you expected. try \TopMark{2e-right} chapter opening page \chapter issues \thispagestyle{plain}, so no header appears however correct the mark is. fix once for the whole document: \fancypagestyle{plain}{\fancyhf{} \fancyfoot[C]{\thepage}\renewcommand... Why marks rather than state The header of page 40 is typeset after page 40 is full and while the rest of the document is still unread, so it can only ask what notes the material on that page left behind. That is also why a header change alters pagination, and pagination is why the marks resolve differently on the next run - compile twice before trusting a running head.
    mark는 제목이 조판되는 자리에 떨어지고, 머리글은 나중에 페이지가 잘릴 때 만들어지며, 어느 칸이냐에 따라 처음값과 마지막값 중 하나를 읽습니다.
    \documentclass[11pt,a4paper]{report}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[a4paper,margin=2.5cm,headheight=26pt,headsep=16pt]{geometry}
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}
    \fancyhead[L]{%
      \begin{minipage}[t]{.55\headwidth}\raggedright\footnotesize
        \firstleftmark\\[1pt]
        \footnotesize\itshape second line of the header, from a mark of its own
      \end{minipage}%
    }%
    \fancyhead[R]{\footnotesize\thepage}
    \renewcommand{\headrulewidth}{0.4pt}
    
    \makeatletter
    % Two-sided behaviour of \markboth: left part -> even pages, right -> odd.
    % \leftmark reads the LAST left mark of the page, \rightmark the FIRST right mark.
    \newcommand{\firstleftmark}{\FirstMark{2e-left}}
    \makeatother
    
    \begin{document}
    \chapter{Marked material}\label{ch:one}
    
    \section*{A section that is not numbered}
    % Unnumbered headings set no mark, so the running head must be written by hand:
    \markboth{Appendix: unnumbered material}{}
    \addcontentsline{toc}{section}{Unnumbered material}
    The header on the following pages now reads from the mark we set manually.
    
    \section{Numbered from here}
    \subsection{Deeper}
    Because \verb|\rightmark| is the \emph{first} right mark on the page, a page
    that starts with a new section shows that section in the header even when the
    rest of the page belongs to the next one - the asymmetry behind the
    "my header is one heading behind" complaint.
    
    \begin{equation}
      \label{eq:star}
      \sum_{d\mid n} \varphi(d) = n
    \end{equation}
    Equation \eqref{eq:star} has nothing to do with page furniture, but its number
    comes from the same two-pass mechanism, which is why adding a header line that
    changes \verb|\headheight| can move it to another page.
    \end{document}

    양면 문서: 대칭 배치, 빈 페이지, 쪽 번호 자리

    twoside 문서는 같은 페이지를 거울에 비친 것이 아닙니다. 여백 자체가 좌우로 바뀌고, 그것을 표현한 것이 geometry의 inner=/outer=이며, 머리글도 그 뒤를 따릅니다. 표준 클래스에서 book은 기본이 양면이고 article은 단면이라, 똑같은 머리글 코드가 두 템플릿에서 다르게 동작합니다. 리포트에서 잘 돌아가던 머리글이 논문에서 망가진다는 신고의 1순위 원인이 이것입니다.

    장을 여는 페이지는 또 다른 종류의 구조 차이입니다. openright(book의 기본)에서는 \chapter이 \cleardoublepage를 실행하고, 그 때문에 장이 뒷면에서 시작하게 되면 빈 페이지가 하나 끼워집니다 — 이미 \thispagestyle{empty}가 적용된 페이지라 쪽 번호도 없지요. 인쇄용 단행본에는 옳은 동작이고 PDF 리뷰에서는 버그처럼 보입니다. 그 동작을 지우는 스위치가 openany입니다. 이렇게 끼워진 빈 페이지도 쪽 번호 하나는 소비한다는 점은 별도로 기억해 두십시오. 번호를 손으로 맞추는 문서에서는 센 수와 인쇄된 번호가 서로 어긋납니다.

    따를 만한 배치 관습은 이렇습니다. 단행본에서 쪽 번호는 바깥쪽 위나 바깥쪽 아래에 두고, 마주 보는 두 페이지 모두 가운데에는 두지 않습니다 — 가운데 번호는 도련으로 빨려 들어갑니다. 이어지는 머리글은 뒷면에 장 제목, 앞면에 절 제목을 쓰고 작은 대문자나 이탤릭으로 뽑으며, 한 페이지에 둘을 나란히 올리지 않습니다. 실제로 인쇄할 일이 있으면 그 인쇄소가 1페이지를 앞면으로 치는지도 물어보십시오. 쪽 번호가 반대편에 찍히는 문서는 거의 언제나 맨 앞의 빈 페이지 하나만큼 어긋나 있습니다.

    끝으로, 양면 문서의 쪽 번호 문제에는 \thepage로 산수하지 않는 정답이 있습니다. 중요한 것은 물리적 페이지 순서이고, 그걸 묻는 견고한 방법은 oddpage 패키지의 \checkoddpage에 이은 \ifoddpage입니다. 인쇄된 숫자가 아니라 위치를 견주며, 두 번의 통과가 필요합니다. \value{page}를 보고 홀짝을 판정하는 일은 절대 하지 마십시오. 로마자로 매기는 권두 부분과 \includeonly 빌드가 만나면 인쇄 번호와 물리적 페이지가 서로 다른 답을 말합니다.

    \documentclass[12pt,a4paper,twoside]{book}
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath}
    \usepackage[margin=2.6cm,marginparwidth=2.2cm,headheight=16pt]{geometry}
    \usepackage{fancyhdr}
    
    \pagestyle{fancy}
    \fancyhf{}
    % E = even pages, O = odd pages; L/R = left/right slot of that page.
    \fancyhead[LE,RO]{\small\thepage}                       % folio outside
    \fancyhead[RE]{\small\nouppercase{\leftmark}}           % chapter, verso
    \fancyhead[LO]{\small\nouppercase{\rightmark}}          % section, recto
    \fancyfoot[C]{\small\itshape Draft of \today}
    
    \renewcommand{\headrulewidth}{0.4pt}
    \fancyheadoffset[L]{0pt}          % keep the rule exactly at \textwidth
    
    % The style used by \chapter, \part and the TOC: they call \thispagestyle{plain},
    % so redefining plain is how you decorate first pages without touching every call.
    \fancypagestyle{plain}{%
      \fancyhf{}%
      \fancyfoot[C]{\small\thepage}%
      \renewcommand{\headrulewidth}{0pt}%
    }
    
    \begin{document}
    
    \frontmatter                       % roman page numbers, and it resets to i
    \title{A Thesis}
    \author{A. Candidate}
    \date{}
    \maketitle
    \thispagestyle{empty}
    \tableofcontents                   % own \thispagestyle{plain}
    \listoffigures
    
    \mainmatter                        % arabic again, restarting at 1
    \chapter{Rings}
    A chapter opens on a recto here and its first page uses the plain style redefined
    above; later pages use the fancy style, and \verb|\leftmark| carries the chapter
    title on the even pages.
    
    \section{Modules}
    \verb|\rightmark| carries the section title on the odd pages. A section that
    begins at the very top of a page is the classic reason a running head appears
    one section behind, because marks are resolved by the output routine for the
    page as a whole.
    
    \cleardoublepage                   % \thispagestyle{empty} on the blank verso
    \chapter{Fields}
    Both marks are set with \verb|\markboth| by the class: the book class issues
    \verb|\chaptermark| and \verb|\sectionmark|, so the header text is the title
    \emph{as typeset}, uppercase and all, unless \verb|\nouppercase| intercepts it.
    \end{document}

    쪽 번호, 권두 부분, 그리고 지우고 싶은 번호

    쪽 번호는 카운터이고, \pagenumbering{style}은 표기를 바꾸면서 카운터를 1로 리셋합니다 — 그래서 book 계열 클래스의 \frontmatter와 \mainmatter는 장식이 아닙니다. 하나는 로마자로 바꾸고, 다른 하나는 아라비아자로 되돌리면서 다시 1에서 시작하지요. article에서 손으로 재현하려면 \pagenumbering{roman}, 이어서 \clearpage, 그리고 \pagenumbering{arabic}입니다. 대신 \setcounter{page}{1}에 \thepage 재정의의 조합은 PDF 중복 목적지가 태어나는 바로 그 자리입니다.

    표지에서 쪽 번호를 지우는 일은 두 줄이면 됩니다 — 권두 전체를 끄려면 \maketitle 앞에 \pagestyle{empty}, 그 페이지만 끄려면 \maketitle 뒤에 \thispagestyle{empty}. 난이도는 전부가 순서에 있습니다. 첫 페이지는 아무것도 없이 맨숭맨숭해야 하면서 다음 페이지는 여전히 1에서 시작해야 하는 문서에 조금 더 견고한 변형이 있습니다: \maketitle 앞에 \setcounter{page}{0}을 두면 그 다음 페이지가 1이 됩니다.

    "3 of 12"를 뽑으려면 마지막 페이지가 필요하고, 그 값은 한 번의 통과로 알 수 없습니다. lastpage 패키지는 \pageref{LastPage}를 주고 두 번의 실행에서 수렴하며, zref-useri 기반의 zref-lastpage는 \includeonly 빌드와 여러 문서 범위를 넘어가는 변형입니다. 둘 다 이 강의의 다른 모든 것과 같은 부류입니다: 지난 통과만이 채워 줄 수 있는 값.

    재시작과 보정: \addtocounter{page}{-1}은 세면 안 되는 페이지(예를 들어 한 면을 채우는 그림)를 정직하게 보정하는 방법입니다. 동작하긴 하지만 인쇄 번호와 물리 번호를 어긋나게 두어, 링크와 심사자 댓글이 한 페이지 옆으로 갑니다. 대안으로 \thispagestyle{empty}만 걸고 카운터는 그대로 두는 방법은 물리 번호를 온전히 유지하면서 번호만 찍지 않으니, 심사자가 기대하는 쪽은 거의 언제나 후자입니다.

    레시피, 그리고 레시피가 망가지는 모양

    공통분모: \pagestyle{fancy}\fancyhf{}\fancyhead[R]{\small\thepage}\fancyhead[L]{\small\nouppercase{\leftmark}}, 그리고 geometry 옵션에 headheight=15pt. 머리글 선 없애기: \renewcommand{\headrulewidth}{0pt} — \headrule{}도 아니고 \headheight를 통째로 지워 버리는 것도 아닙니다. 왼쪽에 장 제목, 오른쪽에 절 제목, 쪽 번호는 바깥쪽: 칸 절에 나온 세 줄 \fancyhead[LE,RO]/[RE]/[LO]를 그대로. 장의 첫 페이지만 다르게: 매 \chapter 뒤에 \thispagestyle 호출을 늘여 놓는 대신 \fancypagestyle로 plain 스타일을 다시 정의하십시오.

    가장 당황스러운 실패는 아무것도 안 나타나는 경우입니다. 원인부터 가능성 순으로 나열하면: \pagestyle{fancy}를 아예 안 쳤거나 \usepackage{fancyhdr}보다 앞서 쳤다. \chapter/\maketitle/\tableofcontents가 발행하는 \thispagestyle{plain}이 당신이 보고 있는 딱 그 페이지에서 이겼다. 내용이 잘못된 페이지 선택자의 칸에 들어 있다 — 양면 문서에서 \fancyhead[L]을 쓰면 모든 페이지의 왼쪽 칸이 채워지고, 대칭 배치에서는 그게 안 보인다. 아니면 머리글은 통째로 있는데 \headheight가 0이라 상자가 버려지고 본문에 겹친다.

    둘째: 머리글이 다른 제목을 보여줍니다. 그건 가구가 아니라 mark의 일입니다 — \leftmark와 \rightmark를 처음/마지막 비대칭을 염두에 두고 읽고, 번호 없는 제목 다음에는 \markboth{}{}로 mark를 직접 놓으며, 장을 여는 페이지는 plain을 쓰기 때문에 mark가 아무리 옳아도 머리글이 나오지 않는다는 점을 기억하십시오.

    셋째: 머리글이 fragile 명령 경고로 엉킵니다. 머리글 안의 \footnote, \marginpar, 디스플레이 수식은 출력 루틴 안에서 하는 페이지 삽입이라 금지됩니다. \marginpar는 머리글에서 그 자체로 실패하고, \ref를 담은 머리글은 두 번의 통과를 필요로 하며 한 줄에 유지하려고 \mbox{}를 쓰는 것은 정당한 용도입니다. 그리고 장 시작 페이지의 가구까지 실제로 제어해야 한다면 titlesec이 자기 페이지 스타일 창구(\newpagestyle)를 제공합니다. 먼저 \pagestyleset{fancyhdr}를 지정해 두면 이미 배운 어휘를 그대로 쓸 수 있습니다.

    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}
    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}

    이 강의 요약표

    각 소절의 핵심 코드 한 줄씩. 소절 제목을 눌러 해당 위치로 이동하고 코드는 바로 복사하세요.

    소절 핵심 코드
    V = \underbrace{h_{\text{top}}}_{\text{above the header}} + \underbrace{h}_{\text{headheight}} + s_{\text{head}} + \underbrace{T}_{\text{textheight}} + f_{\text{note}} + s_{\text{foot}}
    \documentclass[11pt,a4paper]{article}
    \documentclass[11pt,a4paper]{report}
    \documentclass[12pt,a4paper,twoside]{book}
    h_{\text{measured}} > \text{headheight} \;\Longrightarrow\; \text{warning, and the header eats into the text}

    자주 하는 실수

    • \maketitle이나 \chapter{...} 앞에 \thispagestyle{empty}를 두는 실수. 그 명령들이 자기 \thispagestyle{plain}을 발행하는데 늦게 오므로 이깁니다. 덮어쓰는 호출은 뒤에 두거나, plain을 \fancypagestyle로 다시 정의하십시오.
    • \headheight is too small 경고를 그냥 넘기는 일. 머리글 상자는 줄어들지 않고 페이지도 다시 잘리지 않습니다 — 내용이 본문 첫 줄을 덮을 뿐이고, 그 사실을 말해 주는 곳은 로그 하나뿐입니다.
    • \headheight를 \setlength로 정하면 본문 블록이 따라 움직이길 기대하는 것. geometry로 페이지를 다시 계산하거나, 이제 \textheight가 용지에 맞지 않는다는 사실을 받아들여야 합니다.
    • 양면 book 문서에서 \fancyhead[L]{...}을 써 놓고 결과를 "왼쪽 페이지"라 부르는 것. L이 고르는 것은 왼쪽 칸입니다. 페이지 선택자는 E, O, 왼쪽 페이지를 뜻하는 Lefthand, 오른쪽을 뜻하는 Righthand이고, 그래서 \fancyhead[LE,RO]처럼 씁니다.
    • 단면 article에서 \leftmark가 제 역할을 하길 기대하는 것. 표준 클래스는 한쪽에서 오른쪽 mark만 유지하며, \leftmark는 페이지의 마지막 왼쪽 mark이고 \rightmark은 처음 오른쪽 mark입니다.
    • 쪽 번호를 다시 시작할 때 \pagenumbering{arabic} 대신 \setcounter{page}{1}을 쓰는 것. 그러면 두 페이지가 모두 "1"로 인쇄되고, 목적지가 겹치고, hyperref는 중복 페이지 이름을 보고합니다.
    • 머리글에 \marginpar이나 \footnote, 디스플레이 수식을 집어넣는 것. 출력 루틴 안에서는 페이지 삽입이 허용되지 않아서, 아무것도 안 나오거나 실행이 멈춥니다.

    이 강의에 대한 질문

    LaTeX에서 쪽 번호를 오른쪽 위에 두려면?
    fancyhdr를 올리고 \pagestyle{fancy}, 칸을 비우기 위해 \fancyhf{}를 친 뒤 \fancyhead[R]{\thepage}를 쓰면 됩니다. 양면 문서의 바깥쪽 모서리라면 \fancyhead[LE,RO]{\thepage}이지요. headheight는 geometry 옵션에 선언해 두세요. 그렇지 않으면 fancyhdr가 경고하고 머리글이 본문 첫 줄을 덮습니다.
    장의 첫 페이지에 왜 머리글이 없나요?
    \chapter이 \thispagestyle{plain}을 호출하고, plain은 fancy와 다른 스타일이기 때문입니다. 한 번만 필요하면 \chapter 명령 바로 뒤에 \thispagestyle{fancy}를 두세요. 모든 장의 시작 페이지와 목차, 그림 목록에까지 적용하게 하려면 \fancypagestyle{plain}{...}로 스타일 자체를 다시 정의해서 당신이 원하는 가구를 대신 쓰게 만드면 됩니다.
    fancyhdr의 headheight 경고는 무슨 뜻인가요?
    fancyhdr가 정의한 머리글의 자연 높이를 쟀는데 클래스가 선언한 \headheight보다 그 키가 더 크다는 뜻입니다. TeX은 페이지를 다시 자르지 않고는 띠를 키울 수 없어서 머리글이 본문 첫 줄 위로 넘칩니다. geometry 옵션에 경고가 제안하는 값으로 headheight=를 지정한 뒤 다시 컴파일하세요. 높이가 바뀌면 페이지 나누기가 움직여서 더 큰 요구값이 새로 드러날 수 있습니다.
    머리글에 지금 절의 이름을 보여주려면?
    클래스가 제목마다 mark에 써 두므로 홀수 페이지에는 \rightmark, 짝수 페이지에는 \leftmark를 쓰고, 클래스가 대문자로 바꿔 놓았다면 \nouppercase로 감쌉니다. 커널이 문서화한 비대칭을 기억하세요 — \leftmark는 페이지의 마지막 왼쪽 mark, \rightmark는 처음 오른쪽 mark입니다. 나머지 조합이 필요하면 \LastMark{2e-right} 또는 \FirstMark{2e-left}를 씁니다.
    바뀐말에 "page 3 of 12"처럼 총 쪽 수를 같이 쓰려면?
    lastpage 패키지를 올려 바뀐말 칸에 \thepage\ of \pageref{LastPage}를 적으면 됩니다. 총 쪽 수는 마지막 페이지가 내보내진 뒤에야 정해지므로 두 번 컴파일해야 합니다. \includeonly로 일부만 빌드하는 프로젝트에서는 zref-lastpage를 쓰세요. 문서 범위마다 값을 기록해 두는 변형입니다.
    fancyhdr, titlesec의 pagestyles, KOMA-Script 옵션 중 뭘 써야 하나요?
    표준 클래스에는 fancyhdr입니다. 여섯 칸에 문서가 잘 갖춰져 있고 편집기 튜토리얼들이 전부 그 어휘로 말하지요. titlesec과 titleboth는 같은 모델에 제목용 걸이를 더하고, \pagestyleset{fancyhdr}로 fancyhdr 문법도 이해합니다. KOMA-Script 클래스는 자기 스위치(headings=plainflat, 페이지 치수를 담당하는 typearea)를 갖고 있으니 손으로 정한 길이들과 섞으면 KOMA 페이지 레이아웃 싸움의 대부분이 거기서 시작됩니다.

    실시간 놀이터: LaTeX를 편집하고 바로 렌더링

    입력하면 미리보기가 즉시 갱신됩니다. 일부러 깨뜨려서 오류가 어떻게 보이는지도 확인해 보세요.

    KaTeX 오류
    예제 사용해 보기

    이어서 읽기

    같은 주제로 들어가는 세 갈래: 표기 자체, 그것을 가르치는 강의, 그리고 실제로 쓰는 글.