\startenvironment doc-env
\usemodule[zhfonts]
\definefont[kaiti][name:kaiti]
%\setupalign[granular]
\usecolors[svg]
%\showgrid
\setupinteraction[state=start,focus=standard,color=darkblue]
% 书签
\setupinteractionscreen[option=bookmark]
\placebookmarks[title,chapter,section][chapter]
% 版式
\setuppapersize[A4][A4]
\setuplayout[backspace=3cm,width=15cm,
             topspace=1.5cm,header=1.5cm,
             height=27.2cm,footer=1cm]

% 双面对开
%\setuppagenumbering[alternative=doublesided]
%\showframe
% 段落首行缩进、行间距
\setupindenting[first,always,2em]
\setupinterlinespace[line=1.5\bodyfontsize] 
% 关闭页码，后面会在页眉设置页码
\setuppagenumbering[location=]
% 丑度
%\setuptolerance[horizontal,stretch]
% 图片目录
\setupexternalfigures[directory=figures]
% 标题设置
\setupheads[indentnext=yes]
\setuphead[title][incrementnumber=list]
\setuphead
  [title,chapter]
  [style=\bfb,header=empty,footer=empty,before=,after={\blank[2*line]},align=center]
\setuphead[chapter][alternative=inmargin]
\setuphead[subject,section][style=\bfa,before={\blank},after={\blank}]
\setuphead[subsubject,subsection][style=\bf,before={\blank},after={\blank}]
\definehead[TOC][title]
\setuphead[TOC][before={\blank[quarterline]},after={\blank[quarterline]}]

% 若各章首页前页是空白页，禁止页眉和页脚
\definepagebreak
  [mychapterpagebreak]
  [yes,header,footer,right]
\setuphead
  [chapter,title]
  [page=mychapterpagebreak]

% 若使用了以下文档结构化环境，需要将其分页设定清空
% 方能满足下面的页眉和页脚的断页规则。
%\setupsectionblock [frontpart] [page=]
%\setupsectionblock [bodypart] [page=]
%\setupsectionblock [appendix] [page=]
%\setupsectionblock [backmatter] [page=]

% 目录列表
\setupcombinedlist[content][list={title,chapter,section},criterium=text]
\def\PageNumber#1{\underbars{#1}.}  % 给页码增加下划线
\setuplist
  [title]
  [alternative=a,
   before={\blank[halfline]},
   after={\blank[halfline]},
   style=bold,
   pagecommand=\PageNumber,
   pagestyle=smallitalic,
   width=fit]
%\def\ChapterNumber#1{\doiftext{#1}{第 #1 章\quad}}  % 若 #1 是存在，则将其中文化
\def\ChapterNumber#1{第 #1 章\quad}
\setuplist
  [chapter]
  [alternative=a,
   before={\blank[halfline]},
   after={\blank[halfline]},
   style=bold,
   width=fit,
   pagenumber=no,
   numbercommand=\ChapterNumber]
\def\PageNumber#1{\underbars{#1}.}
\setuplist
  [section]
  [alternative=d,
   style=normal,
   numberstyle=normal, 
   pagecommand=\PageNumber,
   pagestyle=smallitalic]
   
% 目录强制分页
\setinjector[list][13][\page]

% 页眉：通用
\startsetups HeaderFooter
\setupheadertexts[][pagenumber][pagenumber][]
\setupheader[style=\tfx]
\stopsetups
% 页眉：body 部分
\startsetups BodyHeaderFooter
\def\CurrentChapter{%
  第 \headnumber[chapter]\ 章\kern 1em\getmarking[chapter]%
}
\def\CurrentSection{%
  \headnumber[section][current]%
  \quad%
  \getmarking[section][current]%
}
\setupheadertexts[\CurrentChapter][pagenumber][pagenumber][\CONTEXT\ 蹊径]
\setupheader[style=\tfx]
\stopsetups
% 页眉：清空
\startsetups HeaderEmpty
\setupheadertexts[][][][]
\stopsetups

% 脚注里的中文断行
\startsetups footnote:hanzi
\setscript[hanzi]
\stopsetups
\setupnote[footnote][textstyle=bold,setups={footnote:hanzi}]
\setupnotation[footnote][way=bypage] % 来自 wolfgang 的 tip

% 索引
\def\cmdindex#1{\index[#1]{\tex{#1}}}
%---- 列表 ----
\setupfloats[indentnext=yes] 
\setupcaptions[style=\tfx, headstyle=\rm, align=center]
%\setupitemize[each][packed,serried,inmargin][margin=2em]
\setupitemize[each][distance=.4em]
\setupinmargin[left,right][style=\tfx]
\definedescription
  [definition]
  [location=top,hang=20,width=broad,indenting=always,style=\ss,headstyle=\bf]
  
% 表格标题（为了第 6 章表格的演示，这部分内容需要在介绍 \placetable 之后才出现，
% 见 06.tex
%\setupcaption
%  [table]
%  [headstyle=normal,style=small,location=top]

% 抄录
\setuplinenumbering[style=small]
%\setuptyping[option=color,palet=graypretty,
%	     before={\blank[.5em]\setupinterlinespace[line=1.2em]},
%             after={\blank[.5em]}]

\startuniqueMPgraphic{box quote}
path p, q;
numeric w, h, u;
u := .7BodyFontSize;
w := OverlayWidth; h := .8OverlayHeight;
color framecolor; framecolor := white randomized (.7, .7, .7);
pickup pencircle scaled 1pt;
% upper left corner
p := ((0, h) -- (u, h)) shifted (-.1u, 0);
q := ((0, h) -- (0, h - .75u)) shifted (0, .1u);
draw p withcolor framecolor;
draw q withcolor framecolor;
% lower right corner
p := ((w - u, 0) -- (w, 0)) shifted (.1u, 0);
q := ((w, 0) -- (w, .75u)) shifted (0, -.1u);
draw p withcolor framecolor;
draw q withcolor framecolor;
\stopuniqueMPgraphic
\defineoverlay[boxquotebg][\uniqueMPgraphic{box quote}]
\def\boxquote#1{%
  \kern.25em%
  \inframed[frame=off,
            background=boxquotebg,
            offset=0pt,
            loffset=.25em,
            roffset=.25em]{#1}%
  \kern.25em%
}

\startMPinclusions
def fancybox(expr u) =
  numeric w, h;
  w := OverlayWidth; h := OverlayHeight;
  color framecolor; framecolor := white randomized (.7, .7, .7);
  drawoptions(withpen pencircle scaled 1.25pt withcolor .3[framecolor, white]);
  path p, q;
  % 左上角
  p := ((0, h) -- (2u, h));
  q := ((0, h) -- (0, h - 1.25u));
  draw p; draw q;
  % 左下角
  p := ((0, 0) -- (2u, 0));
  q := ((0, 0) -- (0, 1.25u));
  draw p; draw q;
  % 右上角
  p := ((w - 2u, h) -- (w, h));
  q := ((w, h) -- (w, h - 1.25u));
  draw p; draw q;
  
  % 右下角
  p := ((w - 2u, 0) -- (w, 0));
  q := ((w, 0) -- (w, 1.25u));
  draw p; draw q;
enddef;
\stopMPinclusions
\startuseMPgraphic{strange box}
fancybox(.35BodyFontSize);
\stopuseMPgraphic
\defineoverlay[strangeboxbg][\uniqueMPgraphic{strange box}]
\defineframedtext
  [strangebox]
  [frame=off,background=strangeboxbg,
    offset=0pt,loffset=.5em,roffset=.5em,before={\blank},after={\blank[.95em]}]

\setuptype[color=darkred]
\definetyping[mycmd]
\setuptyping[mycmd]
  [before={\setupinterlinespace[line=3ex]\startstrangebox[width=\textwidth]},
   after={\stopstrangebox\setupinterlinespace[line=3.75ex]},
   style=\switchtobodyfont[tt,10pt],
   escape=yes]
\setuptyping
  [before={\startstrangebox[width=\textwidth]},
   after={\stopstrangebox},
   style=\switchtobodyfont[tt,10pt],
   escape=yes]
% 抄录环境里的单引号，会被替换为汉字单引号，我需要定义一个
% 西文等宽字体，将其修正回来，即 /BTEX{\Qt'}/ETEX
\definefont[Qt][lmmono10regular at 11pt]

% ---------- example ----------------------
\definebuffer[example]
\definefloat[Example][Examples]
\setuplabeltext[cn][Example={例 }]

\newdimen\LeftExampleWidth
\newdimen\RightResultWidth
\def\defineLeftExampleWidth#1{%
  \LeftExampleWidth=\textwidth
  \RightResultWidth=\wd#1
  \ifdim\RightResultWidth>0pt
    \advance\LeftExampleWidth by -\RightResultWidth
    \advance\LeftExampleWidth by -1em
  \fi
}
\def\example[#1][#2]#3#4{%
  \setbox\scratchbox\hbox{#4}%
  \defineLeftExampleWidth{\scratchbox}%
  \placeExample[force][#2]{#3}{%
    \hbox to \textwidth{%
      \hbox{\typeexample[#1,
                        before={\startstrangebox[width=\LeftExampleWidth]},
                        after={\stopstrangebox}]}\hss\unhbox\scratchbox}%
  }%
}
\def\simpleexample[#1]#2{%
  \setbox\scratchbox\hbox{#2}%
  \defineLeftExampleWidth{\scratchbox}%
  \placeExample[force,none][]{}{%
    \hbox to \textwidth{%
      \hbox{\typeexample[#1,
                        before={\startstrangebox[width=\LeftExampleWidth]},
                        after={\stopstrangebox}]}\hss\unhbox\scratchbox}%
  }%
  \blank[back]
}

% 修改 MPcode 代码部分高亮颜色
\definestartstop
    [MetapostSnippetName]
    [color=darkblue,
     style=boldface]
\definestartstop
    [MetapostSnippetNamePrimitive]
    [color=darkgreen,
      style=boldface]

\def\BibTeX{B\scale[height=.5em]{IB}\TeX}
\stopenvironment
