我想提取各種乳膠命令的內容,例如
- 部分
- 章節
- 標題
- 旁注等
從一個.tex
文件。這些元素最終會出現在 CSV 檔案中
chapter, chapter 1 title text
chapter, chapter 2 title text
figure, figure text
這是否需要正規表示式或這是重新發明輪子?
該.tex
文件是透過 pandoc 從 Markdown 文件產生的。
實施例A
\documentclass{report}
\usepackage{hyperref}
\newcommand*\Quux{Pouet}
\begin{document}
\chapter[foo]{Foo}
\url{http://www.tex.org}
\end{document}
我想擷取章節和網址。
實施例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'
(這裡單引號是針對 shell 的,請適應您的 shell)。您將獲得一個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
在其參數中合法地包含標記(例如空白行),則+
在相應的參數前面添加 a ,如下所示:
\RenewDocumentCommand #1 { s +O{##3} +m }
對應O{##3}
於包裝指令的可選參數(預設為強制參數的值), 對應其m
強制參數。對於標準切片命令應該+
沒有用,但如果您使用此系統來記錄其他命令的參數,則可能有用。
答案2
提取包將允許您執行此操作:
https://www.ctan.org/tex-archive/macros/latex/contrib/extract
自述文件(extract.pdf)中的文件非常好。