跳转至

ConTeXt学习笔记

欢迎加入本人建的"LuaTeX ConTeXt 学习互助"群:431714622,互助学习LuaTeX ConTeXt LaTeX相关技术,以及通过Lua、Python实现格式化文本、数据的自动排版。

注意:为了避免本博客的jinja引擎误解析,已经在{+#之间,以及对应的}之前加入空格


本文主要学习如下资料的笔记:

涉及LuaTeX的部分,请参见LuaTeX-CLD-TEX学习笔记

引言#

ConTeXt格式的目标是通用排版,更适合设计;而LaTeX最初目标是数学相关的学术排版。

ConTeXt版本:

  • MKII,已经冻结,使用PDFTEX (和XETEX);
  • MKIV,使用LUATEX (和LUAJITTEX)
  • LMTX,最新版,还在进化,使用LuaMetaTeX引擎

学习资源#

环境和编译#

命令#

编译脚本文档

1
2
3
4
# 默认使用LuaMetaTeX
context test.mkiv
# 或指定使用luatex
context --luatex test.mkiv

其他命令行选项(通过--help选项查看)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
--run                  process (one or more) files (default action)
--make                 生成context格式文件(formats),改变系统文件时需要这样才生效
--ctx=name             use ctx file (process management specification)
--noctx                ignore ctx directives and flags
--interface            use specified user interface (default: en)
--autopdf              close pdf file in viewer and start pdf viewer afterwards
--purge                purge files either or not after a run (--pattern=...)
--purgeall             purge all files either or not after a run (--pattern=...)
--usemodule=list       load the given module or style, normally part of the distribution
--environment=list     load the given environment file first (document styles)
--mode=list            enable given the modes (conditional processing in styles)
--path=list            also consult the given paths when files are looked for
--arguments=list       set variables that can be consulted during a run (key/value pairs)
--randomseed=number    set the randomseed
--result=name          rename the resulting output to the given name
--trackers=list        set tracker variables (show list with --showtrackers)
--directives=list      set directive variables (show list with --showdirectives)
--silent=list          disable logcatgories (show list with --showlogcategories)
--strip                strip Lua code (only meant for production where no errors are expected)
--errors=list          show errors at the end of a run, quit when in list (also when --silent)
--htmlerrorpage        generate html error page instead (optional: =scite)
--noconsole            disable logging to the console (logfile only)
--nodummy              don't create a dummy file (can confuse pdf viewers that keep file in view)
--purgeresult          purge result file before run
--forcexml             force xml stub
--forcecld             force cld (context lua document) stub
--forcelua             force lua stub (like texlua)
--forcemp              force mp stub
--arrange              run extra imposition pass, given that the style sets up imposition
--noarrange            ignore imposition specifications in the style
--pages                report pagenumbers of names pages and list references (--page=... or --page=...)
--jit                  use luajittex with jit turned off (only use the faster virtual machine)
--jiton                use luajittex with jit turned on (in most cases not faster, even slower)
--once                 only run once (no multipass data file is produced)
--runs                 process at most this many times
--forcedruns           process this many times (permits for optimization trial runs)
--batchmode            run without stopping and do not show messages on the console
--nonstopmode          run without stopping
--nosynctex            never initializes synctex (for production runs)
--synctex              run with synctex enabled (better use \setupsynctex[state=start])
--nodates              omit runtime dates in pdf file (optional value: a number (this 1970 offset time) or string "YYYY-MM-DD HH:MM")
--nocompression        forcefully turns off compression in the backend
--trailerid            alternative trailer id (or constant one)
--generate             生成文件数据等(如luatools的作用),安装第三方模块时需要这样才生效
--paranoid             do not descend to .. and ../..
--version              report installed context version
--global               assume given file present elsewhere
--nofile               use dummy file as jobname

使用官方vscode扩展#

安装官方的vscode扩展说明

必须打开指定的颜色主题ConTeXt;只有语法高亮,没有Snippet(可以使用Tabnine)。

1
"D:/Users/ah21/AppData/Local/Programs/Microsoft VS Code/Code.exe" --extensions-dir "D:/venvs/context-win64/tex/texmf-context/context/data/vscode/extensions/" --install-extension context

vscode语法高亮插件#

ConTeXt Syntax

搜索路径#

排版脚本、宏插件、字体文件等,似乎也遵循以下规则。

以下参考:context reference manual 2.4 Directories

在工作目录中找不到的文件,ConTEXt会搜索父目录们。也就是说环境文件(environment)可以放在产品文件的父目录中。例如:

  • /texfiles/course/layout.tex
  • /texfiles/course/teacher/manual.tex
  • /texfiles/course/student/learnmat.tex
  • /texfiles/course/otherdoc/sheets.tex

后三个文件在不同的字目录中,都使用相同的环境文件layout.tex。

以下参考 https://tex.stackexchange.com/questions/330771/context-configuration

ConTeXt搜索\environment文件的次序如下:

  1. 当前目录( current directory,即运行contex的PWD,而不是tex主文件所在的PWD)
  2. 父目录 ../
  3. 祖目录 ../../
  4. \(TEXMF/tex/context// 之下的目录(\)TEXMFHOME/tex/context//,在Mac/Linux中,\(TEXMFHOME默认为\)HOME/.texmf)

ConTeXt遵循TeX目录结构(TeX Directory Structure,简称TDS)。TDS手册:tug.org/tds/tds.html

以下参考: https://tex.stackexchange.com/questions/192542/get-or-change-context-path-for-components-projects-environment

还可以指定路径:

  • \usepath[...]
  • \usesubpath[...]

instruction 指令 /command 命令:#

  • control sequence 控制序列
    • primitive 基元
    • macro 宏
  • control symbol
  • control word

ConTeXt指令一般只分为保留字(所构成的控制符号?)和命令两类:

  • 控制符号:\+非字母(符号)
  • 命令:\+字母词(直到遇到一个非字母前终止,如果遇到一个或多个空白字符则将其丢弃,可用{}作为边界,或用\␣显式保留空格)

11个保留字\ % { } # ~ | $ _ ^ &;没有保留字参与的情况下,都视作一般文本。要想输入这些字符,除以下三者,都可以用\先转义: \ \backslash
~ \lettertilde
^ \letterhat

也可以用\type*{*\type+}+输入。

组和环境#

  • { ... },或\bgroup ... \egroup,两对控制序列同义,可以混用
  • \begingroup ... \endgroup,允许更深层的错误检查
  • \start ... \stop
  • 数学环境: $ ... $
  • 某些命令/环境: \startSomething ... \endsomething
  • 某些命令会自动生成一个组,如\hbox, \vbox

组是一个明示的作业单元/解释单元。组内的定义、格式、赋值,组外无效。

组还可以用来界定前面命令的作用范围/输入范围,比如$4^2x$表示\(4^2x\),而$4^{2x}$表示\(4^{2x}\)

空组没有显示意义,但可以用来表示命令边界(比如避免吃掉后面的空格)。

环境一般用于段落以上的内容,除非用\bgroup ... \egroup明示为组,否则不是组。

1
2
3
4
5
6
7
8
9
In {\it The \TeX Book}, {\sc Knuth}
explained everything you need to know
about \TeX.

\framed{Tweedledum and Tweedledee}

\startitemize
...
\stopitemize

命令语法#

  • \command[Option1, Option2, ...]
  • \command[Variable1=value, Variable2=value, ...]
  • 不能这样:\command[Option1, Variable1=value, ...]

配套命令#

  • command (or environment)
  • setupcommand,配置现存command
  • definecommand,克隆现存command
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
\framed[width=3cm,height=1cm]{Tweedledum}
\setupframed
[
    width=3cm,
    height=1cm
]

\defineframed[MySpecialFrame]
\setupframed
[MySpecialFrame]
[
    width=3cm,
    height=1cm
]

定义命令#

\define[NumArguments]\CommandName{TeXtToReplace}

  • NumArguments,参数数量,可省略。
  • CommandName,命令名称,遵守一般命令名规范,可以是单个非字母,或一个至多个字母
  • TextToReplace,命令展开后原位置要替换成的文本,包括格式。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
\define\Tite{\quotation{O Tite tute Tati tibi tanta tyranne tulisti}}

\define[2]\LetterHeading{
    \rightaligned{Peter Smith}\par
    \rightaligned{Consultant}\par
    Maryborough, \date\par
    #1\ #2,\par
}

\LetterHeading{Dear Ms}{Eloise Merriweather}

处理可选参数:

https://wiki.contextgarden.net/Commands_with_optional_arguments

定义环境#

\definestartstop[Name][Options]

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
\definestartstop[TextWithBar][
    before=\startmarginrule\noindentation, % 如果希望此环境是一个组,则必须明式加入\bgroup
    after=\stopmarginrule, % 同上,加入\egroup
    style=\ss\sl
]

\starttext
    The first two fundamental laws of human stupidity state unambiguously that:
    \startTextWithBar
        \startitemize[n,broad]
            \item Always and inevitably we underestimate the number of stupid individuals in the world.
            \item The probability that a given person is stupid is independent of any other characteristic of the same person.
        \stopitemize
    \stopTextWithBar
\stoptext

设置变量#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
% stores value in variable namespace:key
\setvariables[namespace][key=value]
% stores the expanded value
\setevariables[namespace][key=value]
% global
\setgvariables[namespace][key=value]
% global and expanded value
\setxvariables[namespace][key=value]

\setvariables[Letter:opening]
    [before=\blank,
        after={\blank[2*big]},
    ]

% gets value of the variable namespace:key
\getvariable{namespace}{key}

\long\def\Opening#1{%
    \getvariable{Letter:opening}{before}
    \noindent{\begstrut#1\endstrut}
    \getvariable{Letter:opening}{after}
}

尺寸#

Name Name in ConTEXt Equivalent
Inch in 1 in = 2.54 cm
Centimetre cm 2.54 cm = 1 inch
Millimetre mm 100 mm = 1 cm
Point pt 72.27 pt = 1 inch
Big point bp 72 bp = 1 inch
Scaled point sp 65536 sp = 1 point
Pica pc 1 pc = 12 points
Didot dd 1157 dd = 1238 points
Cicero cc 1 cc = 12 didots
当前“M”的宽度 em
当前“x”的高度 ex
1
2
3
4
5
6
7
% 改变段落缩进的三种形式
\parindent=0pt
\parindent 0pt
\parindent0pt

% 等同于
\noindentation

某些尺寸使用弹性赋值

\MeasureName plus MaxIncrement minus MaxDecrease

1
\parskip 3pt plus 2pt minus 1pt

输入特殊字符#

  • 空格和tab \␣
  • 不断行空格 ~
  • 两个以上的断行为段(显示为空行),也可用一个显式空行\blank代替
  • 有时断行被解释为一个空格,而行尾注释%以避免引入空格(写宏的时候)
  • 破折号与连接号:断词用-,输入-\hyphen;连接数字用,输入--\endash;连接句子用,输入---\emdash;减号/负号用,输入$-$\minus

文档与项目结构#

1
2
3
4
5
6
7
8
9
% First line of the document
% Preamble area:
% Containing the global configuration
% commands for the document
\starttext % The body of the document begins here
...
... % Document contents
...
\stoptext % End of the document

插入文件内容

  • \input FileName
  • \ReadFile{FileName} % 文件不存在时不会报错
  • \readfile{FileName}{TextIfExists}{TextIfNotExists}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
% General configuration commands:
\input MyConfiguration
\starttext
\input PageTitle
\input Preface
\input Chap1
\input Chap2
\input Chap3
...
\stoptext

环境文件

命名法:MyMacros_env.texenv_MyMacros.tex

1
2
3
4
5
6
\startenvironment MyEnvironment
    \mainlanguage[en]
    \setupbodyfont[modern]
    \setupwhitespace[big]
    ...
\stopenvironment

插入环境文件内容的方法:

  • \environment File
  • \environment[File]

组件文件

1
2
3
4
5
6
\environment MyEnvironment
\environment MyMacros
\startcomponent Chapter1
    \startchapter[title={Chapter 1}]
    ...
\stopcomponent

成品文件

1
2
3
4
5
6
7
8
\environment MyEnvironment
\environment MyMacros
\startproduct MyBook
    \component Chapter1
    \component Chapter2
    \component Chapter3
    ...
\stopproduct

项目文件

1
2
3
4
5
6
7
8
\startproject MyCollection
    \environment MyEnvironment
    \environment MyMacros
    \product Book01
    \product Book02
    \product Book03
    ...
\stopproject

页面和分页#

  • 版面逻辑尺寸和印刷物理尺寸(通常一致) \setuppapersize[LogicalPage][PhysicalPage]
  • 自定义尺寸常量: \definepapersize
  • 拼版 \setuparranging
  • 显式版面框架: \showframe

文档任何位置都可以重设。

纸张适配内容

  • \startMPpage, MetaPost图形页
  • \startpagefigure,图及文明文字页
  • \startTEXpage,文本页

\startTEXpage[Options] ... \stopTEXpage

widthheight可赋值fit

  • \pagebreak
  • \page

页面元素和版面布局#

layout

  • 5X5块加空布局;
  • 头、顶;脚、底;左右边、沿;

\setuplayout[Name] [Options]

  • 给页面组件设置尺寸
  • 设置逻辑页在物理页上的位置(结合\setuparranging设置逻辑页布局方式)

多种页面布局:

1
2
3
4
\definelayout[Name/Number][Configuration]
\setuplayout[LayoutName]
...
\setuplayout[reset]

调整指定页面的高度或行数,用于定版前的微调,放导言区:

\adaptlayout[Pages] [Options]

指定布局的页码范围,在导言区:

1
2
\definelayout[1][...]
\definelayout[3][reset]

单双页布局:

  • \definelayout[even]
  • \definelayout[odd]

展示页面布局:

  • \showsetups
  • \showframe
  • \showlayout,兼有前二者的功能

获取版心/文本区域宽高:

  • \textwidth
  • \textheight

设置页码#

  • \setuppagenumbering
  • \setupuserpagenumber

配合\defineconversionset使用

获取页码:

  • \userpagenumber,用户定制页码
  • \pagenumber,页码的阿拉伯数字
  • \realpagenumber,未考虑定制的实际页码的数字

对应形式的末页页码:

  • \lastuserpagenumber
  • \lastpagenumber
  • \lastrealpagenumber.

建议分页/不分页、强制分页#

\page

选项:

  • no,不建议分页
  • preference,建议分页
  • bigpreference,强烈建议分页

选项:

  • yes,强制分页
  • makeup,立即分页,不预先放置挂起的浮动体
  • empty,插入空页
  • even,插入页直到双页
  • odd,插入页直到单页
  • left, right,同前两项,仅用于根据单双页转换不同天头、地脚和页边的双册印刷文档
  • quadruple,插入页直到4的倍数页

TEX boxe是不能分页的

\vbox{Material}

有些环境使用了盒子,如framedtext,也不会分页。

天头、地脚的配置#

  • \setupheadertexts
  • \setupfootertexts

1
2
\setupfootertexts[pagenumber] % 居中显式
\setupheadertexts[Preface][pagenumber] % 左右分别显式
可选参数(这些符号名称只能单独使用,否则视作普通字符串):

  • 日期:date, currentdate;
  • 页码:pagenumber;
  • 结构: part, chapter, section...;
  • 结构序号: partnumber, chapternumber, sectionnumber...

也可使用相应的命令:

\date \currentdate \pagenumber \getmarking[chapter] \getmarking[chapternumber]

格式化配置:

  • \setupheader
  • \setupfooter

定义后链接到小节命令中:

1
2
\definetext[ChapterFirstPage] [footer] [pagenumber]
\setuphead[chapter][header=high, footer=ChapterFirstPage]

关闭天头地脚\noheaderandfooterlines

生成无页码的页\page[blank]

页面外边edges、内边margins插入元素#

  • \setuptoptexts: 上边
  • \setupbottomtexts: 下边
  • \margindata,实例:
    • \inleftmargin defined as \definemargindata[inleftmargin][left][margin=margin,width=\leftmarginwidth,style=,color=]
    • \inrightmargin defined as \definemargindata[inrightmargin][right][margin=margin,width=\rightmarginwidth,style=,color=]
    • \inoutermargin defined as \definemargindata[inoutermargin][outer][margin=margin,width=\outermarginwidth,style=,color=]
    • \ininnermargin defined as \definemargindata[ininnermargin][inner][margin=margin,width=\innermarginwidth,style=,color=]
    • \inleftedge defined as \definemargindata[inleftedge][left][margin=edge,width=\leftedgewidth,style=,color=,category=edge]
    • \inrightedge defined as \definemargindata[inrightedge][right][margin=edge,width=\rightedgewidth,style=,color=,category=edge]
    • \inouteredge defined as \definemargindata[inouteredge][outer][margin=edge,width=\outeredgewidth,style=,color=,category=edge]
    • \ininneredge defined as \definemargindata[ininneredge][inner][margin=edge,width=\inneredgewidth,style=,color=,category=edge]
    • \atleftmargin defined as \definemargindata[atleftmargin][left][margin=normal,width=\leftmarginwidth,style=,color=]
    • \atrightmargin defined as \definemargindata[atrightmargin][right][margin=normal,width=\rightmarginwidth,style=,color=]
    • \inleft defined as \definemargindata[inleft][left][margin=margin,width=\leftmarginwidth,align=flushright]
    • \inright defined as \definemargindata[inright][right][margin=margin,width=\rightmarginwidth,align=flushleft]
    • \inouter defined as \definemargindata[inouter][outer][margin=margin,width=\outermarginwidth,align=inner]
    • \ininner defined as \definemargindata[ininner][inner][margin=margin,width=\innermarginwidth,align=outer]
    • \inmargin defined as \definemargindata[inmargin][left][margin=margin,width=\leftmarginwidth,align=flushright]
    • \inother defined as \definemargindata[inother][right][margin=margin,width=\rightmarginwidth,align=flushleft]
    • \margintext defined as \definemargindata[margintext][left][margin=margin,width=\leftmarginwidth,align=flushright,stack=yes]

语法:

\CommandName[Reference][Configuration]{Text}

全局配置页边文本:

\setupmargindata[right][style=slanted]

字体脚本 typescript#

官方配置脚本(增补)

D:\venvs\texlive\2021\texmf-dist\tex\context\fonts\mkiv\type-imp-mscore.mkiv

用法参考: https://wiki.contextgarden.net/Chinese_Japanese_and_Korean

增补用法:

1
2
3
4
5
6
7
8
9
% Enable fonts
\usetypescriptfile[mscore]
% \usebodyfont   [mschinese,12pt]
% \usebodyfont   [mschinese-light,12pt]
\usebodyfont   [mschinese-literate,12pt]
% 或
% \setupbodyfont [mschinese-literate,12pt]
\definebodyfontenvironment[24pt]
\definebodyfontenvironment[18pt]

拼音字体设置

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
% tex/texmf-fonts/tex/context/user/type-ahpinyin.tex
\starttypescript [ahpinyin]
% \definefontsynonym[Human readable]       [file:filename without extension]
  \definefontsynonym[NotoSerif-Regular]    [file:AHPinYin]
  \definefontsynonym[NotoSerif-Italic]     [file:AHPinYin]
  \definefontsynonym[NotoSerif-Bold]       [file:AHPinYin]
  \definefontsynonym[NotoSerif-BoldItalic] [file:AHPinYin]
\stoptypescript

\starttypescript [ahpinyin]
  \setups[font:fallback:serif]          % 安全设置: 如果没有发现时使用备用字体
% \definefontsynonym[ConTeXt basics name] [Human readable]       [features=default]
  \definefontsynonym[Serif]                [NotoSerif-Regular]    [features=default]
  \definefontsynonym[SerifItalic]          [NotoSerif-Italic]     [features=default]
  \definefontsynonym[SerifBold]            [NotoSerif-Bold]       [features=default]
  \definefontsynonym[SerifBoldItalic]      [NotoSerif-BoldItalic] [features=default]
\stoptypescript

% #3. 把"ahpinyin"字体脚本中的四种变体包定义为calligraphic typeface
\starttypescript [ahpinyin]
  \definetypeface [ahpinyin]  [cg] [calligraphic] [ahpinyin]    [default]
\stoptypescript

% 使用字体脚本`type-ahpinyin.tex`设置拼音字体
% \usetypescriptfile[ahpinyin]
% \definefont[pinyin][ahpinyin]
% 或者直接使用
% \definefont[pinyin][name:ahpinying*default at 9pt]

更新手动安装的(outside of tlmgr)文件数据:context --generate

中文字体设置

参考: http://liyanrui.is-programmer.com/2009/10/21/not-just-for-chinese.12264.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
% 字体脚本typescript `type-myfonts.tex`
% 定义一个脚本,名为[serif][zhfont],衬线体
\starttypescript[serif][zhfont]
    % 字体各变体与系统中对应的字体名称
    \definefontsynonym[Serif][name:adobesongstd]
    \definefontsynonym[SerifBold][name:adobesongstd]
    \definefontsynonym[SerifItalic][name:adobesongstd]
    \definefontsynonym[SerifBoldItalic][name:adobesongstd]
\stoptypescript

% 再定义一个脚本,名为[sans][zhfont],无衬线体
\starttypescript [sans][zhfont]
    \definefontsynonym[Sans][name:adobeheitistd]
    \definefontsynonym[SansBold][name:adobeheitistd]
    \definefontsynonym[SansItalic][name:adobeheitistd]
    \definefontsynonym[SansBoldItalic][name:adobeheitistd]
\stoptypescript

% 再定义一个脚本,名为[mono][zhfont],等宽字体
\starttypescript [mono][zhfont]
    \definefontsynonym[Mono][name:adobefangsongstd]
    \definefontsynonym[MonoBold][name:adobefangsongstd]
    \definefontsynonym[MonoItalic][name:adobefangsongstd]
    \definefontsynonym[MonoBoldItalic][name:adobefangsongstd]
\stoptypescript

% 定义脚本[myfonts],其中定义typeface
\starttypescript[myfonts]
    % 定义typeface[myfonts],
    % 使用[serif][zhfont]为rm字体
    \definetypeface[myfonts][rm][serif][zhfont]
    % 使用[sans][zhfont]为ss字体
    \definetypeface[myfonts][ss][sans][zhfont]
    % 使用[mono][zhfont]为tt字体
    \definetypeface[myfonts][tt][mono][zhfont]
\stoptypescript

在文稿中使用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
% 使用字体脚本文件
\usetypescriptfile[myfonts]
% 使用字体脚本
\usetypescript[myfonts]
% 设置主字体
\setupbodyfont[myfonts,rm,12pt]

\starttext

所有动物都生而平等,但有些动物比其他动物更平等

\ss 所有动物都生而平等,但有些动物比其他动物更平等

\tt 所有动物都生而平等,但有些动物比其他动物更平等

\stoptext

定义后备字体(多语言字体)newsong:

1
2
3
4
5
\definefontsynonym[song][name:adobesongstd]
% 指定应用范围的后备字体
\definefontfallback[hereos][name:texgyreherosregular][0x0000-0x0400]
\definefontsynonym[fbsong][song][fallbacks=hereos]
\definefont[newsong][fbsong]

安装字体#

字体文件可以出放在tex/texmf-fonts/fonts/,或tex/texmf-fonts/fonts/truetype/vendor/fontfamily(注意对应字体类型)

使用系统字体,先设置环境变量:

set OSFONTDIR=C:\Windows\Fonts

索引:

mtxrun --generate mtxrun --script font --reload

查找你想要字体(包括文件名和符号名称),比如:

mtxrun --script fonts --list --all --pattern=pinin

1
2
3
4
5
identifier         familyname   fontname    filename                        subfont   instances
---
ahpinying          ahpinying    ahpinying   c:/windows/fonts/AHPinYin.TTF
ahpinyingnormal    ahpinying    ahpinying   c:/windows/fonts/AHPinYin.TTF
ahpinyingregular   ahpinying    ahpinying   c:/windows/fonts/AHPinYin.TTF

或列出四种特性:

mtxrun --script fonts --list --spec deng-light

1
2
familyname   weight   style    width    variant   fontname        filename                     subfont   fontweight
dengxian     light    normal   normal   normal    dengxianlight   c:/windows/fonts/Dengl.ttf
  1. weight black bold demi demibold extrabold heavy light medium mediumbold normal regular semi semibold ultra ultrabold ultralight
  2. style italic normal oblique regular reverseitalic reverseoblique roman slanted
  3. width book condensed expanded normal thin
  4. variant normal oldstyle smallcaps

然后定义名称后使用\definefont[pinyin][name:ahpinying*default at 9pt](或定义后立即自动使用\definedfont)。格式如下:

  • \definefont[PublicReference][filename*featurenames scaling] % filename可以附加前缀name:,表示使用符号名称; file:表示使用文件名,可以使用后缀.ttf等;featurenames可以使用预制的default,或使用\definefontfeature定义
  • \definefont[PublicReference][filename:featurespecication scaling] % 仅用户XƎTEX样式的字体
  • \definefont[PublicReference][filename@virtualconstructor scaling] % 适用于虚拟字体,如数学字体,虚拟特性可参考m-punk.mkiv文件

指定字号的方法:

  • at 72pt,有赖于设计尺寸,不可靠
  • scaled 2400,硬编码缩放
  • sa 2.4,相对于body font尺寸缩放,scaled at the body font size
    • \definefont [TitleFont] [Serif sa b]
    • \definefont [TitleFont] [Serif],会转换为\definefont [TitleFont] [Serif sa *],展开为当前字体尺寸

字体还可用关键字匹配查询(查找算法比较灵活而复杂/不可靠):

1
2
3
4
5
6
7
8
9
\definefallbackfamily [documentfont] [rm] [notoserifcjksc] [preset=range:chinese] % 例外,见下
\definefallbackfamily [documentfont] [ss] [Noto Sans CJK SC][preset=range:chinese]
\definefallbackfamily [documentfont] [tt] [Noto Sans Mono CJK SC][preset=range:chinese]

\definefontfamily [documentfont] [rm] [Noto Serif]
\definefontfamily [documentfont] [ss] [Noto Sans]
\definefontfamily [documentfont] [tt] [Noto Sans Mono]

\setupbodyfont [documentfont]

当一个字体文件被分列为多条时,如:

1
2
3
notoserifcjksc             notoserifcjksc      notoserifcjkscregular      c:/windows/fonts/NotoSerifCJKsc-Regular.otf
notoserifcjkscnormal       notoserifcjksc      notoserifcjkscregular      c:/windows/fonts/NotoSerifCJKsc-Regular.otf
notoserifcjkscregular      notoserifcjksc      notoserifcjkscregular      c:/windows/fonts/NotoSerifCJKsc-Regular.otf

首次无法通过字体文件名或关键字匹配查询来使用,而只能通过主条(最短一条)的identifier(即notoserifcjksc)使用;此后可一通过关键字匹配查询来使用(可能是优先匹配已缓存字体的缘故)。

汉字字间拉伸胶:scrp-cjk.lua,一个测试版本确实补偿了蹩脚的半宽,但我们最好在字体定义时进行补偿,并且/或者只是假设一个正确的字体。

字体颜色特性

颜文字着色

1
2
3
4
5
6
7
8
9
\definefontfeature[colored][colr=yes]
\definefontsynonym[Emoji][file:seguiemj.ttf*default,colored]
\definesymbol[bug][\getglyphdirect{Emoji}{\char"1F41B}]
\definesymbol[ant][\getglyphdirect{Emoji}{\char"1F41C}]
\definesymbol[bee][\getglyphdirect{Emoji}{\char"1F41D}]

% 或者用svg
\definefontfeature[svg][svg=yes]
\definefontsynonym[Emoji][file:emojionecolor-svginot.ttf*default,svg]

字体知识#

  • \setupbodyfont[Options] 设置主字体,影响相关文本元素,字号范围有限定
  • \switchtobodyfont 在特定范围切换主字体,字号会伸缩至指定大小
  • \showbodyfont[Options] 查看字体字号信息
  • \showfont[FontName]

显式主体字体(风格*变形+字号)\showbodyfont[schola, 8pt]

字体抽象层次:

  • typeface 字面/字体(所有字体的总称)
  • font family / font style 字体风格/字体家族,有特定设计特征的多个字体构成的集合;也可以随意指定不同字体为一族。
    • font 字体(字面的子集,有特定的尺寸、字重、风格等)
      • alternative 变体
        • glyph/character 字模

font style 字体风格/字体家族

Style Symbolic names & Commands
Roman \rm, \roman, \serif, \regular
Sans Serif \ss, \sans, \support, \sansserif
Monospaced \tt, \modo, type, \teletype
Handwritten \hw, \handwritten
Calligraphic \cg, \calligraphic

font alternative 字体变体

Alternative Commands that enable it
Normal \tf(typeface), \normal
Italic \it, \italic
Bold \bf(boldface), \bold
Bold-italic \bi, \bolditalic, \italicbold
Slanted \sl, \slanted
Bold-slanted \bs, \boldslanted, \slantedbold
Small caps \sc, \smallcaps
Medieval \os, \mediaeval

6个改变字号的变体后缀

{\tfxx test}, {\tfx test}, {\tf test}, {\tfa test}, {\tfb test}, {\tfc test}, {\tfd test}

在段落开头使用临时切换字体命令时,推荐前置\dontleavehmode,以免发生意外的副作用

定制后缀的缩放权重(主字体环境)

  • \definebodyfontenvironment[particular size][scaled]
    • \definebodyfontenvironment[10pt][a=12pt,b=14pt,c=2, d=3]
  • \definebodyfontenvironment[default][scaled]
    • \definebodyfontenvironment[default][a=1.3,b=1.6,c=2.5,d=4]

除后缀外,以下关键词也可以定制:big, small, script, scriptscript,会影响这些命令:

  • \smallbold
  • \smallslanted
  • \smallboldslanted
  • \smallslantedbold
  • \smallbolditalic
  • \smallitalicbold
  • \smallbodyfont
  • \bigbodyfont

显式后缀的缩放权重(主字体环境)

\showbodyfontenvironment[Font]

为字体风格、变形、尺寸定义命令和关键词

  • \definebodyfontswitch[eight][8pt]
  • \definefontstyle[paloseco][ss]
  • \definefontstyle[paloseco, sosa, sinrebordes][ss]
  • \definealternativestyle[strong][\bf][]

意大利体、斜体和强调体 \it, \sl and \em

  • \setupbodyfontenvironment[default][em=italic]

小型大写与伪小型大写 Small caps and fake small caps

  • \cap and \Cap

颜色#

  • \definehighlight[important][color=red]
    • \important{Very important text}
  • \color[ColourName]{Text to colour}
    • \color[red]{Very important text}
  • \colored[r=0.1, g=0.8, b=0.8]{coloured}
  • \startcolor[ColourName] ... \stopcolor
  • \setupcolors[textcolor=red]
  • \setuphead[chapter][color=blue]
  • \setupbackgrounds[page][background=color,backgroundcolor=blue]

预定义颜色

Name Light tone Medium tone Dark tone
black
white
gray lightgray middlegray darkgray
red lightred middlered darkred
green lightgreen middlegreen darkgreen
blue lightblue middleblue darkblue
cyan middlecyan darkcyan
magenta middlemagenta darmagenta
yellow middleyellow darkyellow

预定义色谱

  • \showcolor[CollectionName]
  • \showcolorcomponents[ColourName]
    • \showcolorcomponents[darkgoldenrod]
  • \usecolors[CollectionName]

    • \usecolors[xwi]
    • \color[darkgoldenrod]{Tweedledum and Tweedledee}
  • “crayola”, 235 colours imitating marker shades.

  • “dem”, 91 colours.
  • “ema”, 540 colour definitions based on colours used by Emacs.
  • “rainbow”, 91 colours for use in maths formulas.
  • “ral”, 213 colour definitions from the Deutsches Institut für Gütesicherung und Kennzeichnung (German Institute for Quality Assurance and Labelling).
  • “rgb”, 223 colours.
  • “solarized”, 16 colours based on the solarized scheme.
  • “svg”, 147 colours.
  • “x11”, 450 standard colours for X11.
  • “xwi”, 124 colours.

自定义颜色

  • \definecolor[New colour][Old colour]
    • \definecolor[maincolour][0.6(orange)]
  • \definecolor[ColourName][Definition]
    • \definecolor[lime 1][r=0.75, g=1, b=0]
    • \definecolor[lime 2][x=BFFF00]
    • \definecolor[lime 3][c=0.25, m=0, y=1, k=0]
    • \definecolor[lime 4][h=75, s=1, v=1]
    • \definecolor[Azure][h=75, w=0.2, b=0.7]
    • \definecolor[light grey][s=0.65]

文档结构#

目录#

官方文档

目录是内置的联合列表(combinedlist)。

  • 设置目录联合列表:\setupcombinedlist[content][list={chapter,section},alternative=c]
    • list选项指定head级别,\definehead自定义级别必须额外指定
    • alternative选项指定版式:a...g,可通过\setuplist设置
  • 设置目录的pdf交互:\setupinteraction[state=start,focus=width]
  • 放置目录:
    • \completecontent,会在目录前自动生成 \title{目录},目录标题名称可以更改:\setupheadtext[chinese][content=目次]
    • \placecontent,根据放置位置生成其下各级目录,如放在章、节下则只能显式本章、节之下的目录
      • criterium选项指定内容:all previous [part, chapter, section, subsection..] component
  • 条目格式化 \setuplist[Element][Configuration]
    • \definelistalternative定义alternative

默认只加入编号的目录, 手动加入未编号head级别:\setuphead[title][incrementnumber=yes]

手动加入指定head实例:

1
2
\subject{Bibliography}
\writetolist[section]{}{Bibliography}

条目间加入分割:

\writebetweenlist[section]{\hrule}

目录与实际标题不同:

  • \SectionType [Options], or with \startSectionType [Options]
  • 特定文字不列入列表用 \nolist or \nomarking
    • \chapter[title={An \nolist{approximate and slightly repetitive}introduction to the reality of the obvious}]

列表和联合列表#

根据列表生成列表、联合列表和目录。列表需要三个元素:

  1. The number.
  2. The name or title.
  3. The page where it is found.

有序号的标题(无序号标题加入选项incrementnumber=yes)和\place...(如\placetable, \placefigure)命令生成的列表,都能满足要求。

生成、设置与使用列表与目录近似:

  • \definelist[ListName][Configuration]
  • \setuplist[ListName][Configuration]
  • \placelist[ListName][Options]
  • \completelist

联合列表

  • \definecombinedlist[Name][Lists][Options],Lists如part, chapter, section, subsection,会自动生成放置命令\placeName
  • \setupcombinedlist

结构列表#

用于结构复杂的列表,比如练习题。

\startitemize[Options][Configuration] ... \stopitemize

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
% 设置结构列表,标题字体风格,标题后命令
\setupitemize[headstyle=bold,afterhead={\blank[medium]}]

\startitemize
  \starthead{标题}
    \input 列表项目1正文
  \stophead
  \startitem
    \input 列表项目2正文
  \stopitem
\stopitemize

自定义类似\startitemize的结构列表:

  • \defineitemgroup[myitems]
  • \setupitemgroup [myitems] [each] [joinedup]
  • \setupitemgroup [myitems] [each] [itemalign=flushright]

索引#

  • \index[Alphabetical]{Index entry}
    • \index{Entry 1+Entry 2+Entry 3},多级别(最多三级)
  • \seeindex[Alphabetical] {Entry1} {Entry2+Entry 3},参见Entry2+Entry 3
  • \placeindex
  • \placeindex
  • \completindex
  • \setupregister[index][Configuration]

生成其他索引

  • \defineregister[IndexName] [Configuration],自动生成命令:
    • \IndexName
    • \placeIndexName
    • completeIndexName
  • \setupregister[IndexName] [Configuration]

引用和超链接#

pdf书签

  • \placebookmarks[List of sections]
    • \placebookmarks[all]

先设置交互,再设置书签才有效。

同义词#

排序#

mark#

  • \marking[IDENTIFIER][CONTENT], TEX \mark
  • \getmarking [IDENTIFIER...][first|last|previous|both|all|current]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
\definemarking[words]
\marking[words]{first}first word ...
\marking[words]{second}second word ...
\page
\marking[words]{third}third word ...
\marking[words]{fourth}fourth word ...
\page
\marking[words]{fifth}fifth word ...
\page

\setupfootertexts
[{\getmarking[words][previous]} --
{\getmarking[words][first]} --
{\getmarking[words][last]}]
[]

\setupfootertexts[chapter][sectionnumber]

\definehead[category][subsection]
\setupfootertexts[chapter][category]
\definemarking[category]
\couplemarking[category][subsection]

引用#

参考: https://wiki.contextgarden.net/References

  • 交叉引用模块: https://wiki.contextgarden.net/Cross_Referencing
    • \setupcrossreftext
    • \crossref
  • 段落引用模块: https://wiki.contextgarden.net/Paragraph_Referencing

设置:

  • \setupreferencing
  • \definereferenceformat 设置自己的引用命令
  • \setupinteraction 控制链接交互的格式
  • \setupreferencestructureprefix [default] [prefixsegments=2:2]
  • \definestructureseparatorset [default] [,,-]

锚点:

  • \reference[reference,...]{text}
    • \chapter[reference]{text}
    • \pagereference[reference,...]
    • \textreference[reference,...]{text}

[reference]可使用命名空间进行分类:[fig:cow]

引用:

  • \in {text}{text}[reference] 引用数字编号,只适用于编号的条目
  • \at {text}{text}[reference] 引用页码
    • \atpage [reference]
    • \somewhere {text}{text}[reference]
  • \about {text}[reference] 引用文本(引用的标题)
    • \setupreferencing 改变\about的输出
  • \ref[default| text| title| number| page| realpage][reference] 自定义用,可结合\goto
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
\section{FirstSection}

\reference[ref]{Gerald Manley}
---Gerald Manley Hopkins

Look in \in{chapter}[hotel] on \at{page}[hotel] for a complete
overview of accommodation in \pagereference[accommodation]Hasselt.

\section{SecondSection}

\starttabulate[|l|l|l|]
\NC title:       \NC \ref[title]   [ref] \NC \ref[title]   [sec] \NC \NR
\NC number:      \NC \ref[number]  [ref] \NC \ref[number]  [sec] \NC \NR
\NC text:        \NC \ref[text]    [ref] \NC \ref[text]    [sec] \NC \NR
\NC realpage:    \NC \ref[realpage][ref] \NC \ref[realpage][sec] \NC \NR
\NC page number: \NC \ref[page]    [ref] \NC \ref[page]    [sec] \NC \NR
\stoptabulate

\at{page}[accommodation].

在校样上显示引用 \showreferences

预置引用#

注册器#

字符、词语、文本和水平间距#

大小写

  • \word{text}: 小写
  • \Word{text}: 首字母大写
  • \Words{text}: 多词语首字母大写
  • \WORD{text} or \WORDS{text}: 全部大写
  • \cap{...\nocap{...}...} 小型大写字母
  • \Cap{} 伪小型大写字母

上下标

  • \high{Text}
  • \low{Text}
  • \lohi{Subscript}{Superscript}
  • 公式中用“_” and “^”

字面文本 Verbatim text

  • \type 第一个参数是边界符号
    • \type {This is without curly bracket}
    • \type This is a closing curly bracket: ‘}’
    • \type 1Tweedledum and Tweedledee1
    • \type |Tweedledum and Tweedledee|
    • \type zTweedledum and Tweedledeez
    • \type (Tweedledum and Tweedledee(
  • \starttyping ... \stoptyping
  • \typ 断词版
  • \tex 保留字会执行

水平间距

  • \setupspacing[broad]
  • \setupspacing[packed]

字符间距

  • \stretched[Configuration]{Text}
    • \stretched[width=4cm]{\bf test text}
    • \stretched{test\text} 扩大\指定位置的间距,撑满行
  • \setupstretched
  • \definestretched
  • \setupcharacterkerning
  • \definecharacterkerning

增加水平间距

  • \, 千分位空格
  • \space or “\␣” 半角空格
  • \enskip, \quad and \qquad 半个em, 1 em or 2 ems
  • \hskip and \hfill 绝对值(可以是负值)空格,\hfill可用在行头行尾
    • This is \hskip 1cm 1centimetre
    • This is \hskip 2cm 2centimetres
    • This is \hskip 2.5cm 2.5centimetres

某种字体的词语间距 \fontdimen2\font \fontdimen2\font \fontdimen4\font

字距 \kern⟨dimen⟩, \mkern⟨mudimen⟩.

复合词语的连接

文本的语言设置

  • \mainlanguage
  • \language \<语言代码> 文档中临时改变
  • \setuplanguage[Language][Configuration]
    • \setuplanguage[en][patterns={en, agr}] 英语和古希腊语(防止替换)

English en, eng, english Japanese ja, japanese chinese cn, chinese

会影响:

  • 断词
  • 某些词语的输出格式
  • 某些的排版传统

自动标签的语言设置

  • \setuplabeltext[Language][Key=Label]
    • \setuplabeltext[es][figure=Imagen~]
    • \setuplabeltext[chapter=Chapter~]

可参考语言文件lang-txt.lua

语言相关命令

  • \currentdate[month, dd, weekday]
  • \date[d=6, m=7, y=1957][weekday]
  • \month
  • \translate[es=Su carta de fecha, en=Your letter dated] 根据语言取值
  • \quote and \quotation

段落、行和行距/垂直间距#

分段:

  • 连续一个到多个空行
  • \par
  • \endgraf

插件垂直空白(不建议使用\vskip \vfill):

  • \godown[Dimension],可以累加
  • \blank[Dimension],累加无效

段落缩进:

\setupindenting[...,...]

[...,...] [+-]small [+-]medium [+-]big none no not first next yes always never odd even normal reset toggle dimension name

  • always:所有段落缩进
  • yes:一般段落缩进。特点段落额外增加垂直间距,如小节起始段落;后面跟着某些环境的段落不缩进。
  • no, not, never, none:禁用段落缩进。
1
\setupindenting[yes, 2em]

指定段落缩进:

\startnarrower[Options] ... \stopnarrower

垂直段落间距:

\setupwhitespace

  • none
  • small, medium, big:相对字号而言
  • line, halfline, quarterline:相对行高而言
  • DIMENSION:指定绝对尺寸,如\setupwhitespace[5pt].

无段落间距

\startpacked[Space] ... \stoppacked

指定位置插件间距,比如标题后

1
2
3
4
5
\setuphead[chapter][
    page=yes,
    before={\blank[4cm, force]},
    after={\blank[3*medium]}
]
  • \setupblank
  • \defineblank[Name] [Configuration]

行间距、行距:

% 设定行间距、行距 %尺寸;符号:reset、small、medium、big、on、off;或用\defineinterlinespace定义的名字; %或命名参数:line=8ex(line, height, depth, minheight, mindepth,distance, top, bottom, stretch and shrink.)

1
2
3
\setupinterlinespace[line=3.2ex]
\setupinterlinespace[big]
\setupinterlinespace[reset]

断词

  • \hyphenation{union-ised, man-slaughter}
  • \unhyphenated
  • \hbox 盒子不会断开
  • \pretolerance and \tolerance
  • \break, \crlf or \

行内间距

\setupinterlinespace [..Interline space..]

手动断行

\startlines One-one was a race horse. Two-two was one too. One-one won one race. Two-two won one too. \stoplines

可配置:\startlines[indenting={yes, small, even}]...\stoplines

或全局配置:\setuplines[indenting={yes, small, even}]

带行号:

\startlinenumbering[Options] ... \stoplinenumbering

** 水平对齐:**

  • \setupalign[right] %全文设置
    • \setupalign[horizontal, morehyphenation]
    • \setupalign[reset]
  • \startalignment[Options] ... \stopalignment % 对齐

选项:

broad wide bottom height line high low lohi flushright flushleft middle yes no width normal reset inner outer flushinner flushouter left right center disable last end paragraph lefttoright righttoleft l2r r2l table lesshyphenation morehyphenation hanging(标点悬挂/突出 protrusion) hangingboth nothanging hz fullhz nohz hyphenated nothyphenated tolerant verytolerant stretch extremestretch final 1*final 2*final 3*final 4*final more 1*more 2*more

  • normal or width or yes,对齐
  • middle,行居中对齐 (实测会拉伸字距,等于center, wide,当是与center弄反了)
  • flushleft or no or right,左对齐/右填充 (right源于ragged-right,不建议用)
  • flushright or lef,右对齐/左填充(同上)
  • inner,推向内边(margin)
  • outer,推向外边
  • disable,仅用于单行段落,等于flushleft,但段末\parfillskip为0
  • last,对齐,最后一行居中

怎么控制行宽

  • wide,让ragged-right, ragged-left, and middle行更宽些(实测是保持固定宽度)
  • broad,近似,用于表格

你希望末行在哪里结束

  • bottom,底部填充
  • height,撑满高度
  • line,字下伸触及下面的边界

在盒子中竖向对齐,比如在\framed或表格中

  • high Align to top
  • low Align to bottom
  • lohi Vertically centered

预定义组合

  • table,等价于flushleft,broad,high
  • reset,等价于normal.
  • center,等价于middle, broad(实测不然,不会增加字距,当是与middle弄反了)

排版/文本流方向

  • lefttoright or l2r,"Hello, world."
  • righttoleft or r2l,".dlrow ,olleH"

更好的调整和局部排版

  • hanging,允许悬挂标点/突出(protrusion)
  • nothanging,禁止悬挂标点
  • hz,允许轻微拉伸字符/字体伸展(font expansion).
  • nohz,禁止字体伸展
  • hyphenated,允许断词
  • nothyphenated,禁止断词
  • lesshyphenation,更少断词. Not sure whether this is relative/additive, or absolute.
  • morehyphenation,更多断词. Not sure whether this is relative/additive, or absolute.
  • tolerant,放松最终段落操控(更多断词和拉伸)以避免超出盒子。
  • verytolerant,更加放松最终段落操控
  • stretch,运用空白额外拉伸,通常配合(very)tolerant使用

单行水平对齐:

  • \leftaligned, \midaligned or \rightaligned
  • \wordright,行内词语右移到头

特殊结构和段落#

脚注、尾注、边注、行号注、局部注

分栏:

  • \startmixedcolumns ... \stopmixedcolumns
    • \startitemgroupcolumns ... \stopitemgroupcolumns
    • \startboxedcolumns ... \stopboxedcolumns
    • \startcolumns[Configuration] ...\column...\stopcolumns
    • \setupcolumns[Configuration]

并行段落

有结构列表

描述和枚举

线和框

  • \hairline 整行
  • \thinrule 文中,平均撑满整行(类似\hfill)
  • \thinrules[n=2] 多行
  • \hl[3] and \vl[3] 固定长度的线,单位em
  • \fillinline[width=6cm] text, 用线填充剩余空间(通常是右侧)
  • \fillinrules 填充多行线

文本装饰,与文本关联的线

  • 文字两侧画线
    • \textrule{Example text}
    • \starttextrule[Configuration]{Text on the line} ... \stoptextrule
    • \setuptextrule
  • \setupbar 设置参数
  • \bar 预定义实例
    • \overbar,上画线,与属性模式的\overbarin不同
    • \underbar,下画线,与数学模式的\underbarin不同
    • \overstrike,删除线
    • \understrike,字下删除线,如马克笔效果
    • \overbars,逐词……
    • \underbars
    • \overstrikes
    • \understrikes
    • \underrandom,不规则(随机)下画线
    • \underrandoms
    • \underdash,下画断线
    • \underdashes
    • \underdot,下画点线
    • \underdots
    • \nobar
    • \hiddenbar
  • \definebar 自定义实例
  • \resetbar 清楚

加框文本

  • \inframed 文字齐行
  • \framed 框底齐行
  • \framedtext, 宽度默认为0.75\hsize
  • \startframedtext

可重用的缓存文本

  • \startbuffer[BufferName] ...\stopbuffer
  • \getbuffer[BufferName]

其他环境和建构

  • 化学式
  • 算式
  • (浮动体、图像)联合体
  • 隐藏文本 \starthiding...\stophiding
  • legend 公式说明
  • 行调整(比如在加框的情况下)
  • mode 编译时进行模式匹配
  • 左右也相对
  • 引用
  • standardmakeup标准修饰 如每页有文件名

图像、表格和其他浮动对象#

  • \externalfigure[img.jpg]
  • \placefigure[Options][Label] {Title} {Image}

zhfonts#

标点压缩和字体设置模块

项目地址使用说明标点压缩说明, 字体处理基本知识

安装目录:

D:\venvs\texlive\2021\texmf-dist\tex\context\third\zhfonts\ 使用:

\usemodule[zhfonts] %

可能造成字体找不到的情况(当时汉字码表设置问题),则禁用t-zhfonts.lua中的字体设置功能,只保留标点压缩功能:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function zhfonts.main (param)
    context ('\\setscript[hanzi]')
    zhspuncs.opt ()
    -- local arg_list = string_split_and_strip (param, ',')
    -- if arg_list[1] ~= "none" and arg_list[2] ~= "none" then
    --     context ('\\definefontfeature[zh][default][' .. fontfeatures .. ']')
    --     context ('\\setupalign[hanging, hz]')
    --         zhfonts.gen_typescript ()
    --         if arg_list[1] ~= "hack" and arg_list[2] ~= "hack" then
    --             context ('\\usetypescript[zhfonts]')
    --             context ('\\setupbodyfont[zhfonts, ' .. param .. ']') 
    --         end
    -- end
end

或直接使用仿制的t-zhspuncs.mkiv:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
% t-zhspuncs.mkiv
\writestatus{loading}{ConTeXt User Module / zhspuncs}
\startmodule[zhspuncs]
\unprotect

% 加载lua脚本文件
\ctxloadluafile{t-zhspuncs}
% 宏定义,运行脚本函数
\def\zhspuncs{\ctxlua{moduledata.zhspuncs.opt()}}
% 宏的加载点
\appendtoks \zhspuncs \to \everystarttext

\protect
\stopmodule
\endinput

相应更改t-zhspuncs.lua:

1
2
3
4
5
6
--t-zhspuncs.lua
moduledata = moduledata or {}
moduledata.zhspuncs = moduledata.zhspuncs or {}
zhspuncs = moduledata.zhspuncs
-- zhspuncs = zhspuncs or {}
--以下保持不变

使用:

\usemodule[zhspuncs]

ruby和行间标注#

1
2
3
4
5
6
7
\usemodule[ruby]

\starttext

\ruby{漢字}{かんじ}

\stoptext

设置主体文本(base text)与ruby文本布局:

1
2
3
4
5
\setupruby
    [basestyle=...,
    basecolor=...,
    textstyle=...,
    textcolor=...]

设置ruby文本与周围文本重叠与否:

1
2
  \setupruby
    [overhang=auto|start|end|none] % default: yes

设置ruby和主体文字(base text)的间距:

1
2
  \setupruby
    [inbetween=...] % default: \blank[small]

可以只改变单个命令的设置:

1
  \ruby[..,..=..,..]{...}{...}

叠置/重叠/左右错位/凸排

  • \clap{whatever} 居中叠置
    • 定义为\def\clap#1{\hbox to 0pt{\hss\strut #1\hss} }
  • \llap{whatever} 左侧叠置
    • 定义为\def\llap#1{\hbox to 0pt{\hss #1} }
  • \rlap{whatever} 右侧叠置
    • 定义为\def\rlap#1{\hbox to 0pt{ #1\hss} }

\strut 能利用字体的结构深度(基线、空白等),否则只有轮廓线

\hss胶等于\hskip 0pt plus 1fil minus 1fil, 它会吸掉\llap或\rlap参数的所有宽度,无论正负。

泡泡框tikz宏包

latex

  • \overset{\makebox[0pt]{(\scriptsize animal)}}{Bears}
  • \underset
  • \labeltext

下划线#

1
日本語の表記では“\underbar{漢字}”や

盒子 box#

对齐盒子

1
2
\showboxes % 显式盒子
\hbox{\hbox{one} \vbox{two\par three} \vtop{four\par five}}

更多盒子:

  • \hbox 水平盒子
  • \vbox 底部行对齐前面的元素
  • \vtop 头部行对齐前面的元素
  • \cbox 内容垂直居中
  • \lbox
    • \lbox to 4cm{... text ...}
  • \rbox
  • \sbox 具有strut的高度(字体设计的行间高度,包括留空),可以基线对齐
  • \tbox and \bbox 表格盒子(有strut属性),也用于图表

显式盒子

  • \ruledhbox 带线的盒子
  • \ruledvbox 带线的盒子
  • \ruledvtop 带线的盒子
  • \showboxes 显式所有盒子
  • \showmakeup 显式标记信息(包括盒子)

用盒子标注拼音

中文此间距glue处理似乎没有中文字符盒子的问题

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
% 使用字体脚本`type-ahpinyin.tex`设置拼音字体
% \usetypescriptfile[ahpinyin] % this is the 'some-name-you-like' part of the saved filename
% \definefont[pinyin][ahpinyin]
% 设置拼音字体
\definefont[pinyin][name:ahpinying*default at 9pt]
% 设置注音命令
% \define[2]\Mypy{%TEX
\def\Mypy#1#2{%ConTeXt
    \setbox1 = \hbox{\strut#1}%
    \setbox2 = \hbox{\strut\darkgray \pinyin #2}% \ssxx xx号无衬线体
    \newdimen\maxwd%
    \ifdim \wd1>\wd2 \maxwd=\wd1 \else \maxwd=\wd2 \fi%
    \setbox1 = \hbox to \maxwd{\hfill \box1 \hfill}%
    \setbox2 = \hbox to \maxwd{\hfill \box2 \hfill}%
    \hskip0pt plus5pt\vtop{\box1\godown[-1.1em]\box2}% 加入glue以便正确分行、调词间距
    % #1\llap{\lower 3ex\box2}%
}
\starttext

漢字漢字漢字漢字\Mypy{漢字}{han4 zi4}漢字漢字

\stoptext

文本行缩放#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
\starttext

\startlines
\scale[maxwidth=4cm]{Hello}
\scale[maxwidth=4cm]{Hello World}
\scale[maxwidth=4cm]{Hello World! How}
\scale[maxwidth=4cm]{Hello World! How are}
\scale[maxwidth=4cm]{Hello World! How are you}
\scale[maxwidth=4cm]{Hello World! How are you doing?}
\stoplines

\stoptext

悬挂缩进#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
\definestartstop
  [exdent]
  [before={\startnarrower[left]\setupindenting[-\leftskip,yes]},
   after=\stopnarrower]

\setuphead[section][indentnext=yes]
\section{Test}
\startexdent
\input knuth \endgraf
\stopexdent

缩放、镜像、剪切#

https://wiki.contextgarden.net/Scaling_Rotating_Mirroring_Clipping

系统宏#

https://wiki.contextgarden.net/System_Macros

调试#

Debugging

跟踪

在可能的错误附近打开所有追踪:

1
2
3
\enabletrackers
\enabletrackers[script*] %脚本跟踪,比如标点后注入罚点
\tracingall

grep脚本(源码全文检索):

1
mtxrun --script grep

显示跟踪器和命令列表:

1
2
\showtrackers
\showdirectives
1
2
context --global m-trackers.mkiv
context --global m-directives.mkiv

视觉展示

清理Visual_Debugging

  • \trace...
  • \show...
    • \showglyphs 显示所有字模的方框

缺字跟踪

\enabletrackers[fonts.missing]

缺字替换

\replacemissingcharacters

缺字体时替换为方块,并且可以拷贝、搜索。

段落与页面构成

\showmakeup[...]

[...]makeup reset boxes all hbox vbox vtop kern glue penalty fontkern strut whatsit glyph simple simplehbox simplevbox simplevtop user math italic origin discretionary expansion line space depth

三个快捷选项:

  • makeup,页面布局
  • boxes,盒子构成
  • all,大部分有用选项

项目结构#

项目结构

项目—产品—组件 | |产品环境 项目环境

标题#

有编号 无编号
\part
\chapter \title
\section \subject
\subsection \subsubject
\subsubsection \subsubsubject
... ...

无编号标题不会出现在目录中(可设置)。

均有Start/Stop版本,方便文档转换。

  • \setuphead [Sections][Options]
  • \setupheads [Sections][Options]

选项:

  • placehead: whose values can be “yes”, “no” “hidden”, “empty” or “section
  • number, “yes” and “no”
  • “before” “after,标题排版前后执行的命令
    • before=\hairline,before=\blank,before={\blank[3*big]}
    • after={\blank[0cm]},before={\blank[0cm]}
    • before={\nowhitespace},after={\nowhitespace\vskip5pt}
  • commandbefore” and“commandafter”,标题文本排版前后执行的命令
  • continue=no
  • page,前插页
  • alignment,“align”会影响包含标题的段落的alignment。可包含“flushleft”(left), “flushright” (right), “middle” (centred), “inner” (inner margin) and “outer” (outer margin)等值。
  • Margin
  • Width
  • indentnext
  • alternative,插入时的替代版式:text paragraph normal margin inmargin top middle bottom reverse margintext
  • textdistance,标题文本距离
  • interlinespace,行间距

有编号的设置会影响无编号,反之不然。 上一级的设置会可能影响下一级,反之不然。

\nolist or \nomarking在目录中排除指定字符:

\chapter{Influences of \nomarking{19th century} impressionism \nomarking{in the 21st century}}

层 layer#

元素可以拥有绝对位置,可以开关某些内容。供重复使用,比如用作背景。

未写入正式文档。官方web文档

在pdf文件中添加附件#

1
2
3
4
5
\setupinteraction[state=start]
\attachment[file=\jobname.tex]
\starttext
\input zapf
\stoptext

生僻字造字拼字#

\hbox{\hbox{辶}\kern-.7em\scale[sx=0.7,sy=0.9]{\raise 0.1em\hbox{頃}}}

压缩会导致笔画变细,且横竖向粗细不协调。在ai中,从结构一致的字中拆部件来用是最好的。

自定义命令#

\def \define

mkvi(扩展名,或脚本首行标出% macros=mkvi)格式可以使用命名的参数,而不限于编号参数:

1
2
3
4
5
6
7
8
9
\def\TestFour[#one]#two%
   {\def\TestFive[#alpha][#one]%
      { #one, #two, #alpha}}
\TestFour [one]{two}

\starttexdefinition TestSix #oeps
     here: #oeps
\stoptexdefinition
\TestSix  {one}

详见

字间距/字符间距#

inter-glyph kerning, Inter-character kerning, or inter-character spacingis, 通常是在字体设计层面处理的。但也可以调整:

1
2
\definecharacterkerning [extremekerning] [factor=.125]
\setcharacterkerning[extremekerning] ... text ...

标题拉伸(充满给定宽度):

1
2
3
4
5
6
7
8
9
\setupcharacterkerning[stretched][factor=max, width=\availablehsize]
% \setupcharacterkerning[stretched][width=] % 或这样
\stretched{\bfd to the limit}

% 或
\stretched[width=]{\bfd to the limit}

% 或
\ruledhbox{\stretched[width=10cm]{\bfd to the limit}}

观察字符字间:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
\usemodule[typesetting-kerning]
\starttext
    \showcharacterkerningsteps[
        style=Bold,
        sample=how to violate a proper font design,
        text=rubish,
        first=0,
        last=45,
        step=5]
\stoptext

额外的字体字间(Extra font kerns)#

在字体设计的特定字符组合(如AV)间的字间基础上,再设置额外的幅度:

\setextrafontkerns

观察字体字间:

\showfontkerns

浮动体#

  • 浮动体 \definefloat
    • \chemical
    • \figure
    • \table
    • \intermezzo
    • \graphic
  • \startfloattext ... \stopfloattext
    • \startchemicaltext ... \stopchemicaltext
    • \startfiguretext ... \stopfiguretext
    • \starttabletext ... \stoptabletext
    • \startintermezzotext ... \stopintermezzotext
    • \startgraphictext ... \stopgraphictext
  • 行首/首字下沉(Drop caps) \setupinitial
  • 文本围绕行首浮动体悬挂 \starthanging ... \stophanging

存取数据#

  • \definedataset[mydataset][delay=yes]
  • \setdataset[mydataset][mytable][field1=text 1, ...]
  • \datasetvariable{mydataset}{mytable}{myvariable}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
% To define a dataset.
\definedataset[cats]

% 匿名键值表1
\setdataset[cats][name=Gus, job=Theatre Cat]

% 匿名键值表2
\setdataset[cats][scene=crime, name=Macavity, is=not there]

% 命名键值表
\setdataset[cats][culprit][name=Mungojerry]

% 覆盖命名键值表
\setdataset[cats][culprit][name=Rumpleteaser]


% 注意:以下用花括号,为的是生成文本
The name of the culprit was \datasetvariable{cats}{culprit}{name}.

% 第二个匿名表中的name
\datasetvariable{cats}{2}{name}.

lua存取数据:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
\startluacode
  local setdata = job.datasets.setdata
  setdata {
    name  = "dataset_id",
    tag   = "this",
    data  = {
      "does",
      work = {
        "splendidly",
        "for",
        nested = { "tables", "!", {{}} }
      }
    }
  }


local getdata = job.datasets.getdata
table.print(getdata ("dataset_id", "this"), "this")
\stopluacode

参考: https://wiki.contextgarden.net/System_Macros/Key_Value_Assignments#Multi-pass_data

评论