Skip to content

关于 TeX

Installation of TeXLive

TL;DR

Following the official instruction,

  1. download install-tl
  2. run it, and optionally specify the mirror location for faster download speed
2021 on Rocky

did not click create symlinks to standard directories after running ./install-tl

create module file, /usr/share/Modules/modulefiles/texlive/2021,

set     version         2021
set     app             texlive
set     modroot         /usr/local/$app/$version

prepend-path PATH $modroot/bin/x86_64-linux
prepend-path MANPATH $modroot/texmf-dist/doc/man
prepend-path INFOPATH $modroot/texmf-dist/doc/info

then call it after loading the module,

$ which pdflatex
/usr/bin/pdflatex
$ module load texlive/2021 
$ which pdflatex
/usr/local/texlive/2021/bin/x86_64-linux/pdflatex
2017 -> 2020

The TeXLive 2017 for Ubuntu cannot work for me, it reports

fatal: Could not undump 6994 4-byte item(s) …

and try

fmtutil-sys –all

refer to Error Message: “tex: fatal: Could not undump 1 4-byte item(s) from”, but does not work.

And I also try uninstall and reinstall TexLive, but it still does not work.

Then finally I decided to install the latest TeXLive 2020, TeX Live - Quick install, follow the instructions, but note that the mirror url should append path/systems/texlive/tlnet.

install-tl --location http://mirror.example.org/ctan/path/systems/texlive/tlnet

And note that the steps for completely removing the installed TeXLive.

If without root privilege, when running install-tl, type D to change the directory, and actually changing the first <1> would change all other directories.

portable mode

目前笔记本上 texlive 还是 2015 版的,而 TikePictures.jl 要求的 lualatex 跑不成功,有 bug。于是考虑安装最新版 texlive 2018,只不过笔记本硬盘空间不够,决定在移动硬盘中安装 texlive。

TexLive 官方说明文档也介绍了 -portable 的安装选项,

其与正常安装时环境变量略有不同,没有单独设置 personal 的配置路径,或许还有其他地方的区别。

另外安装时碰到默认的 mirror 速度很慢的情况,于是考虑换成最近的华为云。

./install-tl -repository https://mirrors.huaweicloud.com/repository/toolkit/CTAN/systems/texlive/tlnet/

路径要指定成

<CTAN/mirror/root/URL>/systems/texlive/tlnet

参考 Change TeX Live Main Repository

Basic

hide date

\date{}. Note that, ignore \date would still show the date.

\xspace: space after LaTeX commands
\usepackage{xspace}
\newcommand\foo{foo\xspace}
\ref vs \ref*

the star version does not create a link. 🔗

Norm: non-breaking space ~ in reference

non-breaking space ~ in Figure~\ref{fig:}.

different ways for line breaks
  • \\, \newline, \tabularnewline : when writing a table, the first one can be confused, while the second one ends the line in a cell, and the latter ends the rows of the table. A good side is that when writing tex using julia, raw"\command" does not need to escape \, but it is still required to use raw"\\\\" to represent \\.
  • break line in cells of table: \makecell{A\\ B} after loading \usepackage{makecell}. 🔗
% at the end of lines

since % starts a comment that goes to the end of the line, then the normal effect is that it does not insert the space (or a par) from the newline. It would be necessary when creating multiple figures horizontally using subfigure environment. An real example. More details can be found in What is the use of percent signs (%) at the end of lines?

fontsize: only recognize 10-12pt

In the following command

\documentclass[12pt]{article}

the option can be recognized only 10pt, 11pt and 12pt.

Refer to How is 14pt giving font size smaller than 12pt?

Norm: punctuation in formula

Displayed equation usually are considered to be part of the preceding sentence, that is it will get the very same punctuation as if it was inline math

Refer to For formal articles, should a displayed equation be followed by a punctuation to conform to the language grammar?

footnote: symbols instead of numbers as markers

\usepackage[symbol]{footmisc} (🔗)

footnote: without marker

\newcommand\blfootnote[1]{%
    \begingroup
    \renewcommand\thefootnote{}\footnote{#1}%
    \addtocounter{footnote}{-1}%
    \endgroup
}
Refer to 🔗

Two Columns

  • use star version table* and figure* to cross two columns, and note that not support [H] option. See also 🔗, 🔗
  • use \columnwidth instead of \textwidth (or use 0.5\textwidth), see also 🔗

Beamer

  • customize aspect ratio, from default 4:3 to 16:9 : \documentclass[aspectratio=169]{beamer} 🔗

fragile option

参考 LaTeX 技巧 573:beamer 中使用 Listings 包出现的错误

错误描述

Runaway argument?
! Paragraph ended before \lst@next was complete.
<to be read again>
                   \par
l.68 \end{frame}
?

解决方案

\begin{frame}[fragile]
\frametitle{Your title}

\begin{lstlisting}
code
\end{lstlisting}
\end{frame}

incompatible with enumitem

详见lists - Trouble combining enumitem and beamer - TeX - LaTeX Stack Exchange

摘录其中一句话

enumitem “disturbs” beamer.

而其中 enumitem 可以实现将列表的序号由数字改成字母,详见 How do I change the enumerate list format to use letters instead of the default Arabic numerals?

import video

Can XeLaTeX | LuaTeX import movies?

之前用 xelatex + animate 试过展示动态视频,但是只能在 Acrobat Reader 中起作用,不能在 Ubuntu 18.04 上通过 evince 或者 okular 播放。参考 How to make Okular play embedded video,建议使用 multimedia 包,但是这个包不支持 xelatex,会报错

! Undefined control sequence. \pdfmark

参考 multimedia 的文档,里面确实强调了,

The package can be used together with both dvips plus ps2pdf and pdflatex, though the special sound support is available only in pdflatex.

所以只能用 pdflatex, 不过根据 Video in Beamer with multimedia, undefined control sequence, 似乎也可以用 LuaLaTeX.

Fonts

fontsize

\fontfamily{pcr}

Selects the “Courier” font family for the document. This font family is a fixed-width font that is commonly used for programming code or computer terminal outputs. (chatGPT)

For other “font package name” and its “font code”, see also: 🔗

some nice font family

refer to Suggest a “nice” font family for my basic LaTeX template (text and math)

and currently I prefer to newpxtext and newpxmath.

missing font

报错信息如下图

解决方案为

sudo apt-get install texlive-fonts-extra

有时需要考虑

sudo apt-get install texlive-fonts-recommand

common font styles in math formula

refer to What are all the font styles I can use in math mode?

bm: 加粗保留斜体

使用 \mathbf 加粗完后斜体不见了,这不是想要的结果

\usepackage{amsmath}
\boldmath
$$
f(x,y) = 3(x+y)y / (2xy-7)
$$
\unboldmath

\usepackage{bm}
$$
\bm{f(x,y) = 3(x+y)y / (2xy-7)}
$$

参考 LaTeX 数学字体加粗问题

use serif math font in beamer

默认数学字体挺丑的,可以在导言区加入

\usefonttheme[onlymath]{serif}

下面摘录自 Beamer 中数学符号字体

关于tex的字体样式,其实是通用的,与css和windows字体等,都是通用的。来源于西方的字母写法,大致可分为两类:serif (衬线)和sans-serif(无衬线)。

所谓衬线是字体的末端加强,便于阅读。如通常见的Times New Roman, 宋体。sans-serif(sans 源自法语,表示“没有”)字体的代表如Arial,隶书,幼圆。由于衬线的强化作用,serif字体作为正文具有易读性。因此存在大段文本的情况下,常使用衬线字体。但做幻灯片的话,衬线字体会因字体粗细不同,反倒可能降低辨识度。因此建议标题用衬线字体,正文用非衬线字体。

数学符号用衬线字体相对美观一些,而Beamer如果不另行设置,默认全文使用sans-serif字体。因此按上述方式设置一下即可。

List

设置item之间的间隔

直接用itemsep命令,如

\begin{itemize}
  \setlength\itemsep{1em}
  \item one
  \item two
  \item three
\end{itemize}
small left margin (locally for current slide)

 \addtolength{\leftmargini}{-4\labelsep}
This is useful when using \column to add notes, but the margin seems too large.

itemize 环境下不同 item 中数学公式对齐

参考Sharing alignment between equations in two different items

Low-Level

Bibliography

  • biber and bibtex are external programs to process .bib file
  • biblatex and natbib are LaTeX packages that format citations and bibliographies
    • natbib works only with bibtex
    • biblatex works with both biber and bibtex
  • rm In:: insert \renewbibmacro{in:}{} after loading the package biblatex.

Refer to Bibtex, Latex compiling - TeX - LaTeX Stack Exchange

Based on my understanding and experience, biber + biblatex is more advanced, and it can easily handle accent characters.

  • (2021-10-07 20:55:35) Just encountered that accented characters are correctly displayed in .bib file as UTF8 encoding, but after processing with bibtex, the accented characters are messy. (Refer to 🔗 for more details.)

biblatex -> natbib

Info

Post: 2021-10-07 21:13:41 See also: 🔗

To switch from “biblatex + biber” to “natbib + bibtex”,

\usepackage[backend=biber,citestyle=authoryear,sortcites=true,natbib,sorting=nyt,style=apa]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\usepackage[authoryear]{natbib}
\bibliographystyle{imsart-nameyear}

We can just modify the header definition without replacing the commands in the main document.

The idea is to define the command in natbib+bibtex as biblatex+biber, and keep the main content unchanged. Specifically,

\newcommand{\parencite}[1]{\citep{#1}}
\newcommand{\textcite}[1]{\citet{#1}}
% \addbibresource{ref_biblatex.bib}
\newcommand{\printbibliography}{\bibliography{ref_bibtex.bib}}

A well known issue for biber older than 2.2

missing recode_data.xml file

bibtex文献加颜色

两种方式

第一种

\hypersetup{
    colorlinks,
    citecolor=green,
    linkcolor=black
}

但这个只会对参考文献中可点击的部分起作用,比如实际中只对年份起了作用。

第二种可以自定义命令

\DeclareCiteCommand{\cite}
  {\color{red}\usebibmacro{prenote}}%
  {\usebibmacro{citeindex}%
   \usebibmacro{cite}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

\DeclareCiteCommand{\parencite}[\mkcolorbibparens]
  {\usebibmacro{prenote}}%
  {\usebibmacro{citeindex}%
   \usebibmacro{cite}}
  {\multicitedelim}
  {\usebibmacro{postnote}}

参考 Beamer, Citation coloring

实战例子:szcf-weiya/zju-thesis

modify style of specific field

例如想加粗并用橙色显示 note field, 则可以采用

\DeclareFieldFormat{note}{\bfseries\color{orange}{#1}}

例如 🔗

另见 Biblatex Change field format for a specific entry type - TeX - LaTeX Stack Exchange

将引用的年份用括号框起来

参考Put parentheses around year in citation

采用natbib中的\citet

但若已经按照上个问题设置了颜色,则颜色失效。

Biblatex/biber fails with a strange error about missing recode_data.xml file

参考Biblatex/biber fails with a strange error about missing recode_data.xml file

APA

  • APA 带编号

默认 APA 格式的参考文献是不带标号的,如果需要,参考

APA bibliography style with numbers

  • 保留大小写

除了第一个单词的首字母,默认会将 title 中其它单词的首字母的大写改成小写,如果没有被 {{}} 保护的话。

使用

\DeclareFieldFormat{apacase}{#1}

例如 🔗

export to .bib from Zotero

Tip

The plugin Better BibTeX can keep the .bib file once new references are added. Also, it can be exported to either biblatex or bibtex.

  • With biblatex, do not care about the accented characters, just use its original format
  • With bibtex, it will automatically convert the accented characters with necessary backslashes.

The original abstract field is,

Karhunen–Lo`{e}ve decomposition

after exporting to .bib file, it becomes

Karhunen–Lo{\textbackslash}`{e}ve decomposition

and it throws an error when compiling,

! File ended while scanning use of \field.

My first solution is to check if there are some setting when exporting to .bib file to drop some field, such as abstract here, but finally I failed to find one, and here is a discussion in the Zotero community.

Then I try to replace

`{e}

with

{`e}

in the Zotero’s abstract field as said in How to write “ä” and other umlauts and accented letters in bibliography?, which also list several accented characters,

{"a} {\^e} {`i} {.I} {\o} {'u} {\aa} {\c c} {\u g} {\l} {~n} {\H o} {\v r} {\ss} {\r u}

but it still doesnt work.

Finally, I directly correct the exported file using the above technique, and it works. But I still think it is not a good idea since I prefer to export without any further modifications. [TODO]

display full name

For natbib, check the documentation of natbib by typing

texdoc natbib

longnamesfirst option will display full name for the first citation of any given reference, but all subsequent ones will be used with et al.

  • without longnamesfirst, all citations would be et al.
  • with \citet*, \citep*, the citation would be full author list.

For biblatex, seems that we can set the global argument maxcitenames to control the number of author in the citation, such as only display all authors, of multi-author works, the first time a citation is used with biblatex

DeclareLanguageMapping

\DeclareLanguageMapping{american}{american-apa}

refer to Problem with \mkbibdateapalongextra of biblatex-apa

printbibliography

\usepackage[american]{babel}
\usepackage[style=apa,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa} %Literaturverzeichnis american-apa style
\addbibresource{library.bib}
\usepackage[babel,threshold=2]{csquotes}

and then

\printbibliography[heading=bibintoc,title=References]

refer to Problems with \printbibliography

TiKZ

  \tikzset{%
    in place/.style={
      auto=false,
      fill=white,
      inner sep=2pt,
    },
  }

refer to avoid overlapping of labels and arcs in Tikz - TeX - LaTeX Stack Exchange

Figures

  • force subfigures to have same height and scale proportionally: 🔗
    • examples:

Formula

Some ways to number equations

  • split for a single number
  • multiline for a single number
  • align* with tag

more details refer to A test of Equation Numbering

align multi cases

refer to How can I align multiple cases environment simultaneously?

Key point: enclose one of the entries in the first cases environment in a box whose width is that of the longest of the second cases environment.

or use \hphantom{}.

\hat 时的上标

\hat\beta^n
\hat\beta^n

\hat\beta{}^n
\hat\beta{}^n

参考 Position of superscript when superscriptd item has \hat over it

二阶导数符号

在tex中一般直接用

$f''$

但是在md中,当渲染成网页后,有时会渲染成了普通的引号,如下图

参考How to write doubleprime in latex

  1. \dprime\trprime需要unicode-math
  2. f^{\prime\prime}代替f''可以解决问题。

数学公式插入图片

参考 Can I insert an image into an equation?

同时在等号上下注明

参考 Writing above and below a symbol simultaneously

\hat f 的脚标太远

当对 f 同时加上 hat 和脚标时,脚标会离得很远,感觉很丑,如

一种解决方案如图所示,将 hat 框住脚标。当然这个解决方案对于其它字符并不需要,比如对于 pi, 反而不好。

Theorem

bold for theorem title.

Without amsthm, the title is bold by default. Refer to Title of the theorem.

With amsthm, one solution is to add these in the preamble.

\usepackage{amsthm}
\makeatletter
\def\th@plain{%
  \thm@notefont{}% same as heading font
  \itshape % body font
}
\def\th@definition{%
  \thm@notefont{}% same as heading font
  \normalfont % body font
}
\makeatother

refer to How to make the optional title of a theorem bold with amsthm?

proof by parts

\newtheorem{proofpart}{Part}
\newtheorem{theorem}{Theorem}
\makeatletter
\@addtoreset{proofpart}{theorem}
\makeatother

here \@addtoreset{foo}{bar} is to add counter foo to the list of counters \cl@bar to be reset when counter bar is stepped.

Refer to Parts numbering in Proofs

缺少 .sty 文件

比如缺少 mhchem.sty

! LaTeX Error: File 'mhchem.sty' not found
解决方案为
# 1. 检查是否存在 `mhchem.sty` 文件
$ locate mhchem.sty
# 2. 查找需要安装的 package
$ apt-cache search mhchem | grep tex
# texlive-science - TeX Live: Natural and computer sciences
# 3. 安装相应的package
$ sudo apt-get install texlive-science

参考 Latex can’t find .sty files altough packages are installed — TexLive, Ubuntu 12.04

调整目录的显示层数

在使用 tableofcontents 命令的时候,可分别显示 chaptersectionsubsectionsubsubsection 等目录,有时候,不希望显示级别较低的内容,比如只显示到 chaptersection,而 subsectionsubsubsection 不显示,这时候可通过命令 setcounter 命令来控制,具体做法如下:

\setcounter{tocdepth}{2}

即只显示两级目录。

pdf 添加 Metadata 信息

\usepackage[pdfauthor={Your Name},
            pdftitle={The Title},
            pdfsubject={The Subject},
            pdfkeywords={Some Keywords},
            pdfproducer={XeLateX with hyperref},
            pdfcreator={Xelatex}]{hyperref}

“texi2dvi” command not found

sudo apt-get install texinfo

Why can’t the end code of an environment contain an argument?

参考Why can’t the end code of an environment contain an argument?

Formatting section titles

参考Formatting section titles

Table

multirow and multicolumn

Example

private project

\usepackage{multirow}
\multirow{number of rows}{width}{text} % using `*` as width implies natural width

% no extra package
\multicolumn{number of cols}{align}{text} % align `l, c, r`

refer to Multi-column and multi-row cells in LaTeX tables

If we want to add line break in multi rows, we add specify the width, and also center the text, such as

\multirow{3}{2cm}{\centering some long sentences}

midrule

resizebox

It is defined in graphics, so it is necessary to load \usepackage{graphicx}.

$ latexdef -f resizebox

\resizebox:
undefined

$ latexdef -p graphicx -f resizebox
\resizebox first defined in "graphics.sty".

\resizebox:
\protected macro:->\leavevmode \@ifstar {\Gscale@@box \totalheight }{\Gscale@@box \height }

Question

In general, how can I find the packages that a command belongs to? Here is a dicussion, but seems not enough.

the basic grammar is

\begin{table}
\resizebox{\textwidth}{!}{
    \begin{tabular}
    ...
  \end{tabular}
}
\end{table}

it works for images and tables

For rescaling in general you can use a resizebox (from the graphicx package), which also works for tikzpicture. The first argument is the width, the second the height, or ! to scale proportionally.

source: @Marijn

and application in

Example

  • in table
  • use in beamer to shrink tables, and refer to 🔗 for alternative ways.

Bug

Error: extra alignment tab has been changed to \cr

check the number of columns.

替换换行符

详见strings - Replacing substrings by linebreaks - TeX - LaTeX Stack Exchange

这是 zju-thesis 模板允许封面标题换行的处理策略,同时参见

  1. Line break inside \makebox

fancyhdr warning headheight is too small after setting font size

Refer to headheight-problem

[re]newcommand

Capacity exceeded [semantic nest …]

check your newcommand definition, to see if there is some silly definition such as

\newcommand\silly{\silly}

refer to Capacity exceeded

avoid space after command

with definition,

\newcommand\test{test}

will cause no space in the middle of text. A remedy is to use \test\ in the middle of text, refer to

for other possible solutions.

standalone 环境

  1. 不支持 algorithm
  2. 对于 algorithmic 要加上 varwidthpreview 选项。

参考

Greek Symbols

howto bold

\mathbf 只对公式中的普通字母 ABC...abcdef 等起作用。

\usepackage{amsmath}
\boldsymbol{\sigma}
\usepackage{bm}
\bm{\sigma}

variant forms

详见 Variant forms of Greek symbols

Operator

operatorname vs mathrm

\operatorname:

The argument is written in upright mode but with some additional space before and behind.

\mathrm:

It is like math mode (no spaces), but in upright mode. The font size isn’t changed.

What’s the difference between \mathrm and \operatorname?

\limits is allowed only on operators

image

New usage of cases

see

\ind{A} = \cases{
        1 & if $A$ is true,\\
        0 & otherwise,}

refer to Matching Content to MathJax, which originally for illustrating the typeface of mathjax.

Make a love heart

  • by equation:
  • by pure latex
  • by tikz based on filtered paths

refer to Can we make a love heart with LaTeX?

Change section title without altering the cleveref cross-referencing system

Info

Contributed by ZexiCAI on 2021-09-06.

Suppose you

  1. want the section title to be “Good Title 1”, “Good Title 2”, etc., and
  2. you want cross-reference two sections at the same time as “Good Titles 1 and 2” instead of “Good Title 1 and Good Title 2”. Although one can do it mannually, the author is lazy and would like the cross-referencing system to do it automatically.

The simplest way to do (1) is to change the \thesection definition:

\renewcommand{\thesection}{Good Title \arabic{section}}

However, when you do cross-referencing (“cref” or “Cref”), it will appear to be “section Good Title 1” and “section Good Title 2”. A feasible way to do it is to directly modify the definition of \section command. Its original definition is

\newcommand\section{\@startsection {section}{1}{\z@}%
{-3.5ex \@plus -1ex \@minus -.2ex}%
{2.3ex \@plus.2ex}%
{\normalfont\Large\bfseries}}

We can modify it as

\renewcommand\section{\@startsection {section}{1}{\z@}%
{-3.5ex \@plus -1ex \@minus -.2ex}%
{2.3ex \@plus.2ex}%
{\normalfont\Large\bfseries\noindent Good Title~}}

This solves (1). To solve (2), we need to change the name of section when calling “cref” or “Cref”, by doing

\crefname{section}{Good Title}{Good Titles}
\Crefname{section}{Good Title}{Good Titles}

Warning

Note that however this will change the name globally.

Comments