さまざまなLaTeXコマンドの内容を抽出したいのですが、例えば
- セクション
- 章
- キャプション
- 補足など
ファイルから.tex
。これらの要素は最終的にCSVファイルに保存されます
chapter, chapter 1 title text
chapter, chapter 2 title text
figure, figure text
これには正規表現が必要ですか、それとも車輪の再発明でしょうか?
ファイル.tex
は、Pandoc を介してマークダウン ドキュメントから生成されます。
例A
\documentclass{report}
\usepackage{hyperref}
\newcommand*\Quux{Pouet}
\begin{document}
\chapter[foo]{Foo}
\url{http://www.tex.org}
\end{document}
章と URL を抽出したいと思います。
例B
\documentclass{tufte-book}
\begin{document}
\chapter{A chap}
\marginnote{A note}
\end{document}
余白の注釈を抽出したい
答え1
次のようなファイルを使用して、すべてのセクション コマンドをインストルメント化できます ( と呼びますinstrumenter.tex
)。
\RequirePackage{xparse}
\ExplSyntaxOn
\iow_new:N \l_csgillespie_iow
% #1: sectioning command name as a single token
% #2: character tokens representing the command name, without the backslash
\cs_new_protected:Npn \csgillespie_instrument_sec_cmd:Nn #1#2
{
% Save the original sectioning command
\cs_gset_eq:cN { g_csgillespie_#2_orig: } #1
\RenewDocumentCommand #1 { s O{##3} m }
{
\iow_now:Nn \l_csgillespie_iow { #2 ; ##2 ; ##3 }
\IfBooleanTF {##1}
{ \use:c { g_csgillespie_#2_orig: } * {##3} }
{ \use:c { g_csgillespie_#2_orig: } [##2] {##3} }
}
}
\cs_generate_variant:Nn \csgillespie_instrument_sec_cmd:Nn { c }
% #1: character tokens representing the command name, without the backslash
\cs_new_protected:Npn \csgillespie_instrument_sec_cmd_ifexists:n #1
{
\cs_if_exist:cT {#1}
{ \csgillespie_instrument_sec_cmd:cn {#1} {#1} }
}
\AtBeginDocument
{
\iow_open:Nn \l_csgillespie_iow { sectioning.csv }
\clist_map_inline:nn
{
part, chapter, section, subsection, subsubsection, paragraph,
subparagraph
}
{ \csgillespie_instrument_sec_cmd_ifexists:n {#1} }
}
\AtEndDocument { \iow_close:N \l_csgillespie_iow }
\ExplSyntaxOff
\endinput
次に、次のファイルをチェックするとしますtested.tex
。
\documentclass{report}
\newcommand*\Quux{Pouet}
\begin{document}
\chapter[foo]{Foo}
\chapter{Bar \emph{Baz!}}
\chapter*{\Quux !}
\section{A \emph{section}!}
\section[Short title]{Another section}
\end{document}
必要なのは、instrumenter.tex
にある場所TEXINPUTS
(おそらく と同じディレクトリtested.tex
) を入力して、次を実行することだけです。
latex '\input instrumenter \input tested'
sectioning.csv
(ここでは一重引用符はシェル用です。ご使用のシェルに合わせてください)。この例では、 と同じディレクトリにtested.tex
次のようなファイルが作成されます。
chapter;foo;Foo
chapter;Bar \emph {Baz!};Bar \emph {Baz!}
chapter;\Quux !;\Quux !
section;A \emph {section}!;A \emph {section}!
section;Short title;Another section
タイトルにセミコロン区切り文字 ( ;
) が含まれている場合は、出力に二重引用符 (または CSV 形式に必要な任意の引用符) を追加する必要があります。次の行に二重引用符を追加するだけです。
\iow_now:Nn \l_csgillespie_iow { #2 ; ##2 ; ##3 }
議論の段落
このコードを使用して他のコマンドをラップし、これらのコマンドが引数にトークン (例: 空白行) を合法的に持つことができる場合は、次のように、対応する引数の前に を\par
追加します。+
\RenewDocumentCommand #1 { s +O{##3} +m }
はO{##3}
ラップされたコマンドのオプション引数 (デフォルトは必須引数の値) に対応し、 はm
必須引数に対応します。+
は標準のセクション コマンドには役立ちませんが、このシステムを使用して他のコマンドの引数をログに記録する場合は役立つ可能性があります。
答え2
抽出パッケージを使用すると、次のことが可能になります。
https://www.ctan.org/tex-archive/macros/latex/contrib/extract
そこにある readme (extract.pdf) のドキュメントは非常に優れています。