Skip to content

Latest commit

 

History

History
805 lines (633 loc) · 29.3 KB

latex-tips.md

File metadata and controls

805 lines (633 loc) · 29.3 KB

(La)TeX Tips

Distributions

TeX Live

tlmgr

# FIXME: need no indent to enable highlighting
# list all schemes (installed are prefixed with "!")
tlmgr info schemes

# list all collections
tlmgr info collections

# list all installed packages
tlmgr info --only-installed

# show package info
tlmgr info amsmath

# show content of a scheme/collection/package under "depends" or "run files" key
tlmgr info --list scheme-basic

tlmgr info --list --json collection-basic | jq --compact-output '.[].depends[0:5]'
# ["amsfonts","bibtex","cm","colorprofiles","dvipdfmx"]
  • Get space separated list of installed packages (GNU ggrep used for its -P option):

    $ tlmgr list --only-installed | ggrep -oP '(?<=i )\w+(?=:)' | tr '\n' ' '
  • Show or modify user configurations https://www.tug.org/texlive/doc/tlmgr.html#conf

    # show all config settings
    $ tlmgr conf [texmf | tlmgr | updmap]
    
    # show, set, and delete one `texmf` (TeX and Metafont) config
    $ tlmgr conf texmf max_print_line
    $ tlmgr conf texmf max_print_line 2000
    $ tlmgr conf texmf --delete max_print_line

texdoc

  • TUG page https://tug.org/texdoc/

  • Repo https://github.com/TeX-Live/texdoc

  • Doc texdoc texdoc

  • Remark: command texdoc installed by MiKTeX is just a shortcut for an independent program mthelp.

  • Show results with corresponding scores

    # long option: texdoc --list --machine amsmath
    $ texdoc -lM amsmath | head -5
    amsmath	11.5	/path/to/texmf-dist/doc/latex/amsmath/amsldoc.pdf	en	User guide (English)
    amsmath	5.5	/path/to/texmf-dist/doc/latex/amsmath/amsmath.pdf
    amsmath	5.0	/path/to/texmf-dist/doc/latex/amsmath/subeqn.pdf	en	Sub-equation usage
    amsmath	5.0	/path/to/texmf-dist/doc/latex/amsmath/technote.pdf	en	Technical details
    amsmath	5.0	/path/to/texmf-dist/doc/latex/amsmath/testmath.pdf	en	Examples paper

kpsewhich

  • texdoc kpathsea, sec. 5.6.1 "Path searching options"
# --format
kpsewhich --format=texmfscripts arara.sh

MiKTeX

  • MiKTeX now supports Win/Mac/Linux, and provides Docker image.
  • Unique TeX features
    • automatic package installation: --disable-installer and --enable-installer
    • list of package usage: --record-package-usages=<file>
    • additional input directories: --include-directory=<dir>
    • specific directory for auxiliary files: --aux-directory=<dir>
  • List of packages contained in MiKTeX, and the current (compressed) packages files distributed by CTAN mirrors

BasicTeX

  • https://tug.org/mactex/morepackages.html brew info basictex

  • upgrade basictex

    # backup package list
    tlmgr list --only-installed | sed -e 's/^i \([^:]*\): .*$/\1/' > tl_packages
    
    brew upgrade basictex
    
    # set ctan repository
    sudo tlmgr option repository https://mirrors.tuna.tsinghua.edu.cn/CTAN/systems/texlive/tlnet
    
    # install docs
    sudo tlmgr option docfiles 1
    sudo tlmgr install --reinstall $(tlmgr list --only-installed | sed -e 's/^i \([^:]*\): .*$/\1/')
    
    sudo tlmgr install "$(cat tl_packages)"
    
    # rename versioned directory used by TEXMFVAR and TEXMFCONFIG
    #     TEXMFCONFIG=~/Library/texlive/2023basic/texmf-config
    #     TEXMFVAR=~/Library/texlive/2023basic/texmf-var
    mv ~/Library/texlive/{2023,2024}basic
    
    # for xetex: (re)create hard links for fonts so they can be found by xetex with family name
    rm -f ~/Library/Fonts/texlive-opentype/*
    rm -f ~/Library/Fonts/texlive-truetype/*
    find `kpsewhich -var-value TEXMFDIST`/fonts/opentype -name '*.otc' -type f \
      -exec ln \{\} ~/Library/Fonts/texlive-opentype \;
    find `kpsewhich -var-value TEXMFDIST`/fonts/truetype -name '*.ttf' -type f \
      -exec ln \{\} ~/Library/Fonts/texlive-truetype \;
    
    # for luatex
    sudo tlmgr conf texmf OSFONTDIR /System/Library/AssetsV2/com_apple_MobileAsset_Font7

Engines and Backends

pdfTeX

XeTeX

  • Git repo hosted on sourceforge and the mirror on GitHub
  • Precedence of font names used by XeTeX (ref)
    • Full name > Family-Style > PostScript name > Family
    • To let XeTeX auto-load variations, Family is recommended
  • Show font info: aat-info.tex and opentype-info.tex, located in $TEXMFDIST/tex/xetex/xetexfontinfo

Specials

LuaTeX

  • \immediateassignment and \immediateassigned, texdoc luatex sec. 2.8.8
    \newcount\mycount
    
    \edef\TestMe{\advance\mycount 1 foo:\the\mycount}
    \show\TestMe % ->\advance \mycount 1 foo:0.
    
    \mycount=0
    \edef\TestMe{\immediateassignment\advance\mycount 1 foo:\the\mycount}
    \show\TestMe % ->foo:1.
    
    \mycount=0
    \edef\TestMe{\immediateassigned{\advance\mycount 1 }foo:\the\mycount}
    \show\TestMe % ->foo:1.

dvipdfm-x

Formats

LaTeX

Docs

Only texdoc names listed.

  • Basic: source2e, classes, usrguide-historic (previously called usrguide), fntguide, encguide
  • LaTeX3: interface3, source3, expl3
  • Hook management*: lthooks, ltcmdhooks, ltfilehook, ltshipout, ltpara
  • New modules: ltmarks*, usrguide (previously called usrguide3)
  • LaTeX-lab: documentmetadata-support*, latex-lab-footnotes, latex-lab-new-or, latex-lab-prototype, latex-lab-testphase

*: with variants -doc and -code

Format version

  • \fmtversion, \patch@level, and \ExplFileDate
  • All-in-one
    \ExpandArgs{c}\def{show@release@info}#1{#1\par}\texttt{\the\LaTeXReleaseInfo}
    % LaTeX2e <2024-06-01> patch level 2
    % L3 programming layer <2024-05-27>

Hooks

  • Default labels

    • texdoc lthooks, sec. 2.1.5 Hook names and default labels
    • \AddToHook{<hook>}{<code>} executed in the main document uses label top-level; otherwise uses current filename as label
      • More precisely, in files loaded with \@onefilewithoptions (thus \@pushfilename is invoked), default label is the current filename. In the main document, files loaded with \input, \include, and \InputIfFileExists, default label is top-level.
    • current default label can be altered (to non-top-level) by \PushDefaultHookLabel or \SetDefaultHookLabel
    • \AddToHook{<hook>}{<code>} has arg-spec mo+m hence is equivalent to \hook_gput_code:non {<hook>} {\c_novalue_tl} {<code>}, which is further equivalent to \hook_gput_code:non {<hook>} {.} {<code>} using the dot-syntax
  • Execution order code chunks (all other labels), top-level label, next invocation

    • reversed hooks uses reversed order: next, top-level, chunks
    • ordering rules (\DeclareHookRule) only affect execution order inside code chunks
    • next invocation code (\AddToHookNext) is not orderable

Commands for class and package writers

  • \disable@package@load{<pkg>}{<alternate-code>}, requires LaTeX2e 2020/10/01

Notable LaTeX NEWS

  • ltnews28, 2018-04-01, A general rollback concept for packages and classes
    % in "doc.pkg"
    \DeclareRelease{v2}{2021-06-01}{doc-2021-06-01.sty}
    
    % in "main.tex"
    \usepackage{doc}[=v2]

ConTeXt

  • Recommended ConTeXt Docs, Q&A on TeX-SX
  • Auto-generated list of all commands, without descriptions
  • Renamed primitives \normal<primitive csname> (done in source files norm-*.mkii in TEXMFDIST/tex/context/base/mkii/)

Fonts

Font encodings

  • Main doc: texdoc fontenc
  • EU1 encoding (eu1enc.def): provided by package euenc
  • T3 encoding (t3enc.def): provided by package tipa

[xetex] Show full path of fonts

Add \XeTeXtracingfonts=1 before \documentclass, and find full path of fonts in .log, like

Requested font "[lmroman10-bold]:mapping=tex-text;" at 10.0pt
 -> /usr/local/texlive/2018basic/texmf-dist/fonts/opentype/public/lm/lmroman10-
bold.otf

[macOS] Using extra fonts with lualatex

lualatex can use fonts in directory /Library/Fonts, but not those added to new library of Font Book.app.

$ tlmgr conf texmf OSFONTDIR <path>

Packages

HTML docs

latex3

CHANGELOG

Docs

  • l3backend
  • l3kernel (directory $(kpsewhich --var-value TEXMFDIST)/doc/latex/l3kernel)
    • expl3.pdf, interface3.pdf
    • l3term-glossary.pdf, l3styleguide.pdf
    • l3news.pdf, l3syntax-changes.pdf, l3obsolete.pdf
    • l3prefixes.pdf
    • l3doc.pdf (for l3doc.cls), l3docstrip.pdf (stub file, see docstrip.pdf)
  • l3experimental
  • l3packages
  • l3trial

Modules

  • l3debug.dtx, generates l3debug.def which will be loaded by \sys_load_debug:
    • no l3debug.pdf generated nor part of interface3.pdf as of 2023-05
    • in l3debug.def, \debug_on:n is redefined to do the real setting.
    • starting from l3kernel 2023-05-23 (commit 1ec8adb6), \sys_load_debug: is integrated into \debug_on:n.
    • enable debugging without explicitly loading expl3 package
      %% before
      \sys_load_debug:
      \debug_on:n { ... }
      %% from `l3kernel` 2023-05-23 on
      \debug_on:n { check-declarations , check-expressions , deprecation , log-functions }
      % or equivalently
      \debug_on:n { all }

Workaround: use tikzmark package with xelatex

According to discussions on TeX-SX and the bug report to pgf project, this is a pgf driver bug. A workaround, which recovers the definition of \pgfsys@hboxsynced from dvipdfmx version to the common driver version, is firstly suggested in an answer on TeX-SX.

Workaround: redefine \pgfsys@hboxsynced, see below

\usepackage{tikz}
\usetikzlibrary{tikzmark}
% WORKAROUND:
% Definition copied from pgfsys-common-pdf-via-dvi.def
% http://tex.stackexchange.com/a/339975/
% Compare http://tex.stackexchange.com/q/229500 and comments!
\makeatletter
\def\pgfsys@hboxsynced#1{%
  {%
    \pgfsys@beginscope%
    \setbox\pgf@hbox=\hbox{%
      \hskip\pgf@pt@x%
      \raise\pgf@pt@y\hbox{%
        \pgf@pt@x=0pt%
        \pgf@pt@y=0pt%
        \special{pdf: content q}%
        \pgflowlevelsynccm%
        \pgfsys@invoke{q -1 0 0 -1 0 0 cm}%
        \special{pdf: content -1 0 0 -1 0 0 cm q}% translate to original coordinate system
        \pgfsys@invoke{0 J [] 0 d}% reset line cap and dash
        \wd#1=0pt%
        \ht#1=0pt%
        \dp#1=0pt%
        \box#1%
        \pgfsys@invoke{n Q Q Q}%
      }%
      \hss%
    }%
    \wd\pgf@hbox=0pt%
    \ht\pgf@hbox=0pt%
    \dp\pgf@hbox=0pt%
    \pgfsys@hbox\pgf@hbox%
    \pgfsys@endscope%
  }%
}
\makeatother

Workaround: use tikz-feynman package with lualatex

According to the discussions (and workaround) under project luaotfload, an updated version of function pgf_lookup_and_require causes this problem. The bug has been reported to pgf.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{graphdrawing}

\usepackage{luacode}
\begin{luacode*}
function pgf_lookup_and_require(name)
    local sep = package.config:sub(1,1)
    local function lookup(name)
        local sub = name:gsub('%.',sep)
        if kpse.find_file(sub, 'lua') then
            require(name)
        elseif kpse.find_file(sub, 'clua') then
            collectgarbage('stop')
            require(name)
            collectgarbage('restart')
        else
            return false
        end
        return true
    end
    return
        lookup('pgf.gd.' .. name .. '.library') or
        lookup('pgf.gd.' .. name) or
        lookup(name .. '.library') or
        lookup(name)
end
\end{luacode*}

\usegdlibrary{circular}
\usepackage[compat=1.1.0]{tikz-feynman}
\begin{document}
% normal feynman usage
\feynmandiagram[ ... ]{ ... };
\end{document}

[hyperref] Allow unicode-math math symbols in bookmark

\hypersetup{
    psdextra = true,
    unicode  = true
}

[hyperref] Package options

  • Package option: hyperindex

[hyperref] Package internals

  • backend files: hpdftex.def, hxetex.def, hluatex.def
  • common internals:
\section{title}\label{key}

\ref{key} -> \hyper@link{link}{section.1}{1}
\contentsline -> \hyper@linkstart
biblatex.sty: \hyper@natlinkstart -> \hyper@linkstart
% only in hxetex.def, \hyper@link depends \hyper@linkstart
\def\hyper@link#1#2#3{%
  \hyper@linkstart{#1}{#2}#3\Hy@xspace@end\hyper@linkend
}

[hyperref] Page hyperlinks in index

Auto page hyperlinks added to index entries may affect order of row pages and encaped pages. A special .ist can be used to overcome this, see [gh/latex3/hyperref#243].

% special .ist file
\begin{filecontents}[noheader, force]{hyperpage.ist}
delim_0 ", \\hyperpageIdx{"
delim_1 ", \\hyperpageIdx{"
delim_2 ", \\hyperpageIdx{"
delim_n "}\\nil, \\hyperpageIdx{"
delim_t "}\\nil"
encap_prefix "\\"
encap_infix "}{{"
encap_suffix "}"
\end{filecontents}

% preamble settings
\usepackage{etoolbox} % for \ifstrempty
\usepackage{makeidx}
\makeindex
\usepackage[hyperindex=false]{hyperref}

% no encap,   e.g., \hyperpageIdx{1}\relax
% with encap, e.g., \hyperpageIdx{\seealso{bar}}{{2}}\relax
\def\hyperpageIdx#1#2\nil{%
  \ifstrempty{#2}
    {\hyperpage{#1}}
    {\ignorespaces#1{\hyperpage#2}}%
}

[fontspec] Use with math font packages

Pass no-math option to fontspec, e.g.,

\usepackage[no-math]{fontspec}
\usepackage{stix2}

ref: answer on TeX-SX by Heiko Oberdiek

[beamer] Doc of pgfpicture environment

Manual of pgf only documents pgfpicture environment without any arguments, while source code of beamer uses an old version of that environment,

The usage of pgfpicture environment in beamer, with four braced arguments, is defined in pgfcorescopes.code.tex and not documented in pgf manual yet.

[minted] Highlight @ as command name letter

Modify python class TeXLexer in file pygments/lexers/markup.py.

class TexLexer(RegexLexer):
    # [... ...]
    tokens = {
        # [...]
        'root': [
            (r'\\\[', String.Backtick, 'displaymath'),
            (r'\\\(', String, 'inlinemath'),
            (r'\$\$', String.Backtick, 'displaymath'),
            (r'\$', String, 'inlinemath'),
            # (r'\\([a-zA-Z]+|.)', Keyword, 'command'),  # before
            (r'\\([a-zA-Z@]+|.)', Keyword, 'command'),  # after
            (r'\\$', Keyword),
            include('general'),
            (r'[^\\$%&_^{}]+', Text),
        ],
        'math': [
            # (r'\\([a-zA-Z]+|.)', Name.Variable), # before
            (r'\\([a-zA-Z@]+|.)', Name.Variable),  # after
            include('general'),
            (r'[0-9]+', Number),
            (r'[-=!+*/()\[\]]', Operator),
            (r'[^=!+*/()\[\]\\$%&_^{}0-9-]+', Name.Builtin),
        ],
        # [...]
    }
    # [... ...]

Alternatively, provide a custom lexer.

#!/usr/bin/env python3

from pygments.lexers.markup import TexLexer
from typing import List, Tuple


def update_token_regex(token: List[Tuple], idx,
                       regex_old=r'\\([a-zA-Z]+|.)',
                       regex_new=r'\\([a-zA-Z@]+|.)'):
    node = token[idx]
    idx2 = 0  # index of regex str
    if node[idx2] == regex_old:
        node = list(node)
        node[idx2] = regex_new
        token[idx] = tuple(node)


class TexLexer2(TexLexer):
    """
    Improved lexer for the TeX and LaTeX typesetting languages.
    Character "@" is treated part of command names.
    """

    tokens = TexLexer.tokens
    update_token_regex(tokens['root'], 4)
    update_token_regex(tokens['math'], 0)

Then modify minted (see minted/176) to execute pygmentize with custom lexer and/or formatter.

[listings] Reset output style for - (U+002D)

By default, listings prints character - as in text mode if the current font family is \ttfamily and as in math mode ($-$) otherwise. One can overwrite this scheme by

\makeatletter
\lst@CCPutMacro
    \lst@ProcessOther{"2D}{-{}}
    \@empty\z@\@empty
\makeatother

[listings] literated input absorbs following space in (full)flexible mode

Example (with workaround included):

\documentclass{article}
\usepackage{listings}
\usepackage{etoolbox}

% adapted from example in `texdoc listings`, Sec. 5.4
\lstset{
  literate={:=}{{$\gets$}}1 {<=}{{$\leq$}}1
}

\makeatletter
\patchcmd\lst@Literate
  {\lst@XPrintToken}
  {\lst@XPrintToken\lst@whitespacefalse}
  {}{\fail}
\makeatother

\begin{document}
\begin{lstlisting}[columns=flexible]
flexible:
  if (i <= 0) i := 1;
\end{lstlisting}

\begin{lstlisting}[columns=fullflexible]
fullflexible:
  if (i <= 0) i := 1;
\end{lstlisting}
\end{document}

[equation] Disregard indent of displayed equations inside list env

\everydisplay\expandafter{%
  \the\everydisplay
  \displayindent=0pt%
  \displaywidth=\hsize
}

[pstricks] Get Ghostscript permission required by xdvipdfmx

From:

Example:

\documentclass{article}
\usepackage{pstricks}

\begin{document}
\pscircle(.5,.5){1.5}
\end{document}

xelatex produces

GPL Ghostscript 9.52: Unrecoverable error, exit code 1

xdvipdfmx produces more detailed

[1Error: /invalidfileaccess in --run--

[...]

Last OS error: Permission denied
Current file position is 74
GPL Ghostscript 9.52: Unrecoverable error, exit code 1

xdvipdfmx:warning: Filtering file via command -->[...]<-- failed.
xdvipdfmx:warning: Image format conversion for PSTricks failed.
  • Ghostscript uses flag -dSAFER by default from 9.50, which forbids reading pstricks header files located in $TEXMFDIST/dvips/pstricks.
  • Edit dvipdfmx.cfg by inserting -dNOSAFER to line starting with D "rungs -q.
  • Flag -dNOSAFER or finer --permit-file-read can be added to TeX Live's wrapper rungs, which is a Lua script.

[pythontex]

xelatex main.tex
# Ideally, "pythontex main" is enough.  But since pythontex.py starts with
#     #!/usr/bin/env python
# pythontex will call python2, which has no pygments to use.
python3 `which pythontex` main
xelatex main.tex

Replacements

Topics: table

Variable Rule width

  • vertical rule: !{\vrule width 2pt}
  • horizontal rule: \specialrule{2pt}{0em}{0em} from booktabs, compatible with longtable
    Full syntax: \specialrule{<width>}{<above skip>}{<below skip>}
  • see example tex-sx/646876

PDF

Produce uncompressed PDF

\ifdefined\directlua
  % if luatex
  \edef\pdfcompresslevel{\pdfvariable compresslevel}
  \edef\pdfobjcompresslevel{\pdfvariable objcompresslevel}
\fi
\ifdefined\pdfcompresslevel
  % if pdftex and luatex
  \pdfcompresslevel=0
  \pdfobjcompresslevel=0
\else
  % if xetex
  \special{dvipdfmx:config z 0}
\fi

General

  • Category code
    TeX doesn't change category codes of once tokenized text (unless you use \scantokens). (question comment on TeX-SX)

  • Behavior of \uppercase and \lowercase
    The uppercase/lowercase table in tex (unfortunately) is fixed based on the T1 font encoding. (issue comment on GitHub)

  • Special tokens

  • Significance of MWE
    Writing up a good issue report including a clear MWE (Minimal Working Example) takes some effort, but it is also essential to help us identifying and fixing issues. (LaTeX news article on latex-project.org)

  • How to report bug to LaTeX2e core
    Details on how to report bugs can be found in the article "New rules for reporting bugs in the LaTeX core software". (news article on latex-project.org)

  • Purposes of initializing .aux file with a \relax

    1. catch impossible-to-write error as soon as possible 2) ensure .aux file is never empty (answer on TeX-SX)
  • PGF-TikZ

    • TikZ pictures can't be nested. Sometimes it works but that is a pure coincidence. by hmenke, one of maintainers of tikz
    • tkz-euclide and tkz-base are just 4k+ lines. They uses deprecated arrows tikz library, and fp package instead of fpu tikz library.
  • l3kernel

    • Either fully-expandable or \protected

      The LaTeX3 approach is that everything should be fully-expandable or \protected

      by Joseph Wright

  • l3packages/xtemplate

    It's pretty clear that xtemplate is a set of good ideas but won't go forward: I'm not sure what's best here.

    by Joseph Wright

    meaning that most of us (all? I?) think that xtemplate was a good prototype with good ideas but not necessarily the best or the most appropriate ones in the end and that by the end of the days the final interface will look different even though it will probably incoprporate several of the ideas in xtemplate in one way or the other. And that's what Joseph referred to.

    by Frank Mittelbach

  • DocStrip

    • \endinput has a dual purpose: if used at the start of the line it is interpret as "please end the file here"; in any other position it is considered part of code and will be handled like any other code that is docstripped. So if you need \endinput as part of your code make sure it is not at the beginning of a line. ---by Frank Mittelbach

TeX Core

  • Full list of primitives by engine
  • List of tracing commands
  • whatsits
    • ... represent commands whose execution is delayed or are special commands associated with a particular device or system and are not part of TeX's normal processing flow. (ref)
    • TeX by Topic, sec. 30.3

Expansion

Record file I/O

  • -recorder command line option
    record every file input and output into .fls file
  • \listfiles control sequence
    record every file input caused by \input{...} and \include (but not \input <filename>) into the very end of .log file

Font

Equation

Logging message

PGF/TikZ

Color Stack

Meta

TeX in Other Programming Languages

JavaTeX Project, by Timothy Murphy

An introduction to this Project is published on 1999 TUGboat. This project is also uploaded to CTAN as a package named javatex. The performance is so poor that the author "considers it unusable in practice", by its readme on CTAN.

Journals

The PracTeX Journal, the online journal of the TeX Users Group, has published 20 issues from 2005 to 2012.

Books

The LaTeX Companion, 3rd Edition (tlc3)