段階 4 · 構造と相互参照 32 / 48 ≈ 20 分で読める

fancyhdrで組むLaTeXの頁眉・頁フッターとページ番号

頁の家具は、あなたが打った場所ではなく出力ルーチンが組み立てます。ヘッダーにマークが必要なのも、headheight が使われる前に宣言されていなければならないのも、章の第一ページだけ別のスタイルが残るのも、すべて同じ理由からです。この課では縦の積層を枠ごとに分解し、奇数・偶数、前置き、ページ番号の通し方まで扱います。

    ページは帯の積層で、本文が通るのは一つだけ

    \textheight より上には三つの長さがあり、TeX 自身が加えるものがもう一つ控えています。用紙の上端から順に、指定しても現れない 1 インチ(TeX のプリミティブ由来のオフセットで、マニュアルの「天辺」が実測と一致しないのはこのせいです)、次に \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(罫線なしの二行の running head をマークから作る)、myheadings(同じ書式で、中身を自分の \markboth が供給する)です。

    この二重状態が生む衝突が、第一ページに関する定番の質問です。単位を開くコマンドは自分自身の \thispagestyle を発すからです。\maketitle は plain を使い、\chapter も plain、\part と \tableofcontents も同様で、\cleardoublepage は挟み込む空頁に empty を当てます。つまり \thispagestyle{empty} は \maketitle より後に書く必要があり、前に書けば後発が勝ちます。章の第一ページだけ番号を消したいときに頁ごとの呼び出しと殴り合うのは正解ではなく、その呼び出しが指名しているスタイルを定義し直します。\fancypagestyle{plain}{...} はそのための部品です。

    titlepage 環境へ自分で表紙を書いたとしても規則は変わらず、\thispagestyle{empty} は \begin{titlepage} の直後へ置きます。環境は閉じるときに頁を出力し、家具はその瞬間に「最後に見た呼び出し」から選ばれるためです。

    fancyhdr を読む前でも headings を一度は使ってみる価値があります。running head が何でできているかが裸で見えるからです。偶数頁に \leftmark、奇数頁に \rightmark、あとはマークだけで構成されます。続く節で詳しく見る仕組みは、これの拡張にすぎません。

    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} が定番の鏡合わせ running head で、左開きに章、右開きに節が入ります。\fancyhead[L] を「左ページ」と解釈するのは早合点で、これは「左枠」の意味です。反転ヘッダーのデバッグの大半はこの読み替えから始まります。

    実装に由来する性質が三つ、普通の文書でも効いてきます。空の枠も箱には違いなく、fancyhdr は \strut 相当を詰めて行の高さを作るため、「ヘッダーの中身ゼロ」でも \headheight は非ゼロのままです。罫線は \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.
    1 ページごとに六つの名前付き枠、両面指定ではそれが二倍になります。選択子の文字が「どの頁のどの枠か」を決めます。
    \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(警告が印字した値でも可)を足し、素の \setlength なら前文に \setlength{\headheight}{15pt} と書きます。変更しても \textheight は自動で再計算されないため、本文は用紙の下へ流れ続ける点に注意。その後必ず再コンパイルして見直してください。ヘッダーの高さを変えるのは \textheight の周囲の材料をまとめて動かす話なので改頁がずれ、改頁がずれればマークが動き、マークが動けば幅が変わり、別の数値で同じ警告が再発します。

    原因は必ず四つのどれかです。ヘッダー行に \frac などディスプレイ寄りの数式が混ざると、本文行よりはるかに背が高くなるので、\scriptstyle で小さくするか \mbox{} に入れて \footnotesize を掛けます。二段のヘッダーは概ね倍の高さを要求し、積層ヘッダーの学位論文が 26pt 以上を宣言するのはこのためです。ロゴ画像などを \includegraphics で読み込むケース。そして 12pt でクラスが \headheight を極小に設定したままのケースで、標準クラスがまさにやっています。

    同じくらい現実的な関連警告として、fancyhdr は headwidth("\headwidth... overwritten")も出します。fancyhdr が読んだ後に geometry などのパッケージが本文塊を変えてしまったときです。footerrule 系の衝突は、フッターと \footskip の合計が用紙から突き出るときに出ます。どちらも、geometry を先に、値を全部決めた状態で読み、その後に fancyhdr を読み、以後は二つの長さを手で触らない、で治ります。

    マーク:ヘッダーが現在地を知る仕組み

    ヘッダーは「今どの節か」を尋ねに行けません。組まれる頃には節見出しコマンドはとっくに消え、頁は出力ルーチンに切られた後だからです。手段は マークで、\markboth{left text}{right text} が呼び出された位置の縦リストへ覚え書きを落とし、出力ルーチンは出力対象の頁に見つかったメモを読みます。標準クラスはこれを代行していて、\section は \sectionmark{...}——中身は \markboth{...}{...}——を発します。running head の文言はここから来ます。

    取り出し側に混乱が住んでいて、カーネル文書の記述は厳密です。\leftmark はその頁で最後の左マークを返し、\rightmark は最初の右マークを返します。非対称は意図的で、めくった瞬間に章を左開きへ、入った瞬間に節を右開きへ出す設計です。だから枠の選び方しだいでヘッダーは一節遅れても見え、一節先に見えます。\topmark(頁の最上段で有効だったマーク)、\firstmark、\botmark もあります。

    2020 年のマーク更新以降、LaTeX は各マーク級について最初と最後の値を分けて保持し、不足だった組み合わせを取り出せます。\markboth/\markright が使う級の名前は 2e-left、2e-right、2e-right-nonempty、汎用の取り出し側は \TopMark{class}、\FirstMark{class}、\LastMark{class} です。「いま読んでいるのはここだ」型のヘッダーが欲しいなら、その頁の最後の節を返す \LastMark{2e-right} になります。自作マークは \NewMarkClass{status} に \InsertMark{status}{text} を組み合わせますが、マニュアルの注記を二つ。マークの読み出しは出力ルーチンの中でだけ意味を持ち、片面指定では標準クラスは右マークしか立てないので、\leftmark は設計どおり空になります。

    マークが生む実務上の問題二つは、どちらも一行で片付きます。大文字化は、標準クラスがマークへ \MakeUppercase を仕込むのに対し、fancyhdr 側が打ち消す \nouppercase を用意しているので、慣用形は \fancyhead[RE]{\nouppercase{\leftmark}}。アクセントや数式を含む見出しは、マークに入るのが組まれた形である点が効いてきます。見出しに \texorpdfstring や \footnote を入れる場合は省略形の第 1 引数——\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.
    マークは見出しが組まれた位置に落とされ、ヘッダーは後で、頁が切れるときに組み立てられます。読むのが最初か最後かは枠しだいです。
    \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 は片面なので、同じヘッダーコードが二つの土台で別々に振る舞います。article では動いたのに論文で壊れた、という報告の大元です。

    もう一つの構造的な差が章の立ち上がりです。openright(book の既定)では \chapter が \cleardoublepage を走らせ、章が左開きに乗り始めそうなら空頁が挟まります。挟まれた頁には \thispagestyle{empty} が既に当たっているので番号も出ません。印刷する本では正しく、PDF レビューではバグに見える挙動で、消すスイッチが openany です。なお、こうして入った空頁も通し番号は消費するため、番号を手で制御していると枚数と印刷された数字が一致しなくなります。

    従う価値のある慣行もあります。単行本ではページ番号を丁か半かの外側上、もしくは外側下へ置き、見開きの両頁とも中央に置くのは避けます。中央の番号はノドへ流れ込みます。running head は左開きに章、右開きに節を、スモールキャップかイタリックで。同じ頁に二つは並べません。印刷を伴うなら、一ページ目を右開きとして数えるか印刷所へ確認してください。番号が逆側に現れる文書は、ほぼ例外なく前置きの空頁で一枚ずれています。

    最後に両面の偶奇判定ですが、正解は \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 は飾りではありません。前者はローマ数字へ切り替え、後者はアラビア数字へ戻してなおかつ数え直します。article で同じことを手で再現するなら \pagenumbering{roman}、\clearpage、\pagenumbering{arabic} の順です。\setcounter{page}{1} と \thepage の書き換えで済ませるのは、PDF の重複した宛先が生まれる道です。

    表紙の番号消しは二行の仕事ですが、曲者は順序だけです。前置き全体を無番号にするなら \maketitle より前に \pagestyle{empty}、その頁だけなら \maketitle より後に \thispagestyle{empty}。最初の頁を完全に裸にしつつ次の頁から 1 を出さねばならない文書では、カウンターを明示的にずらすほうが堅く、\maketitle の前に \setcounter{page}{0} を置けば翌頁が 1 になります。

    「3 頁 / 全 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 を足すのではなく、plain を \fancypagestyle で定義し直します。

    一番驚かれるのは、何も出ないという事態です。原因は可能性の高い順に、\pagestyle{fancy} が打たれていない、もしくは宣言の位置が \usepackage{fancyhdr} より前だった。見ているその頁だけを \chapter、\maketitle、\tableofcontents の発する \thispagestyle{plain} が覆している。選択子を間違えた枠に書いている——両面文書で \fancyhead[L] と書くと全頁の左枠が埋まり、鏡合わせ組版では隠れます。\headheight が 0 で箱ごと捨てられている。

    次に、別の見出しが出るケース。これは家具ではなくマークの問題で、最初と最後の非対称を念頭に置いて \leftmark と \rightmark を読み、番号付きでない見出しの直後は \markboth{}{} で自分でマークを置いてください。章開きの頁は plain を使うので、マークがいくら正しくてもヘッダーは出ません。

    三つ目は、脆いコマンドに関する警告が並ぶケース。\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}

    よくある間違い

    • \thispagestyle{empty} を \maketitle や \chapter{...} より前に書いている。これらのコマンドは自分自身の \thispagestyle{plain} を発し、後発のほうが勝ちます。上書きは後ろへ移すか、\fancypagestyle で plain を定義し直してください。
    • \headheight is too small 警告を無視している。ヘッダー箱は縮まず頁も組み直されず、内容はそのまま一行目の本文に重なり、そう書かれているのはログだけです。
    • \setlength で \headheight を変えると本文塊もついてくると期待している。ページ計算は geometry にやり直させるか、用紙に対して \textheight が不正になったまま受け入れるかの二択です。
    • 両面指定の book で \fancyhead[L]{...} を「左ページ」と呼んでしまう。L が選ぶのは左の枠で、頁を選ぶのは E、O、左開きの L、右開きの R です。書くなら \fancyhead[LE,RO] の形になります。
    • 片面指定の article で \leftmark が素直に動くと期待している。片面では標準クラスは右マークしか維持せず、しかも \leftmark はその頁の最後の左マーク、\rightmark は最初の右マークです。
    • \pagenumbering{arabic} の代わりに \setcounter{page}{1} で番号を打ち直している。同じ 1 を読む頁が二枚出て宛先が衝突し、hyperref が重複した page 名を報告します。
    • ヘッダーに \marginpar、\footnote、ディスプレイ数式を置いている。出力ルーチンの内側で頁挿入はできないため、何も出ないか走行が停止します。

    この課に関する質問

    LaTeX でページ番号を右上に出すには?
    fancyhdr を読み、\pagestyle{fancy}、スロットを空にする \fancyhf{}、そして \fancyhead[R]{\thepage} とします。両面文書で外側の隅に出すなら \fancyhead[LE,RO]{\thepage} です。geometry のオプションで headheight を宣言してください。省略すると fancyhdr が警告を出し、ヘッダーが本文一行目に重なります。
    章の第一ページにヘッダーが出ないのはなぜ?
    \chapter が自分の \thispagestyle{plain} を発し、plain は fancy とは別のスタイルだからです。一回だけなら \chapter の直後に \thispagestyle{fancy} を置き、恒久対策は \fancypagestyle{plain}{...} でスタイル側を定義し直すこと。そうすれば章開きも目次も図目表も同じ家具になります。
    fancyhdr の headheight 警告はどういう意味?
    定義したヘッダーの自然高を測ったら、クラスが宣言した \headheight より背が高かったという報告です。頁を切り直さない限り帯は伸びないので、ヘッダーは最初の本文行へかぶさります。警告が示した値を geometry の headheight= に設定して再コンパイルしてください。高さの変更で改頁が動き、より大きい要求が新たに見えることがあります。
    現在の節名をヘッダーに出すには?
    クラスが見出しをマークへ書き込むので、奇数頁は \rightmark、偶数頁は \leftmark を使い、クラスが大文字化していれば \nouppercase で包みます。カーネル文書どおり、\leftmark はその頁の最後の左マーク、\rightmark は最初の右マークです。逆の組み合わせが要るなら \LastMark{2e-right} や \FirstMark{2e-left} を使います。
    フッターに「3 頁 / 全 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)を持っており、そこで手で決めた長さと混ぜ込むのは、たいてい版面をめぐる喧嘩になります。

    ライブ playground:LaTeX を編集して即描画

    入力すると即座にプレビューが更新されます。わざと壊してエラーの見た目も確認しましょう。

    KaTeX エラー
    例を試す

    続けて読む

    同じ話題への三つの入口:記法そのもの、それを教える課、そして実際に使っている記事。