將“section”轉換為“\section”以傳遞給 titleformat 指令

將“section”轉換為“\section”以傳遞給 titleformat 指令

\titleformat包的命令調用titlesec方式如下:

\titleformat{\section}{<a few formatting options>}
\titleformat{\subsection}{<a few formatting options>}

我正在編寫一個小包來自動執行某些格式設置,包括節標題的格式設置,並且titlesec是我“環繞”的包之一。問題是我希望我的程式碼以以下形式編寫

\sectionfamily{section}{uppercase}
\sectionfamily{subsection}{italic}

\sectionfamily是我的自訂命令,作為其執行的一部分,最終將調用\titleformat.為了解決這個問題,假設它的定義如下:

\newcommand{\sectionfamily}[2]{   
    \titleformat{\#1}{\itshape}{\thesection}{0pt}{}[]
}

如您所見,我正在嘗試轉換\sectionfamily{section}{...}\titleformat{\section}{...},但我在這裡定義它的方式不起作用。我已經嘗試了許多組合\expandafter\csname等等,但也無法讓這些組合中的任何一個發揮作用。建立別名命令並傳遞別名也失敗。

section有人知道可以轉換\section並使其發揮作用的方法嗎?


注意:該命令\titleformat{\section}{\itshape}{\thesection}{0pt}{}[]有效,並且可用於測試。完整的 MWE(或最小的不工作範例!!)是

\documentclass[11pt,oneside,a4paper]{article}
\usepackage{titlesec} 

\begin{document}

\section{How does this look?}

\newcommand{\sectionfamily}[2]{   
   \titleformat{\#1}{\itshape}{\thesection}{0pt}{}[]
}
\sectionfamily{section}{italic}
%What I want to run:
%\titleformat{\section}{\itshape}{\thesection}{0pt}{}[]
\section{How does this look?}
\end{document}

答案1

必須有兩種\expandafter說法。首先生成命令序列,然後\titleformat在內部設定中擴展(但是,我沒有查看該包)

\documentclass[11pt,oneside,a4paper]{article}
\usepackage{titlesec} 


\newcommand{\sectionfamily}[2]{%   
  \expandafter\titleformat\expandafter{\csname #1\endcsname}{\itshape}{\csname the#1\endcsname~}{0pt}{}[]
}


\sectionfamily{section}{italic}


\sectionfamily{subsection}{italic}


\begin{document}

\section{How does this look?}

%\newcommand{\sectionfamily}[2]{   
%   \titleformat{\#1}{\itshape}{\thesection}{0pt}{}[]
%}

%What I want to run:
%\titleformat{\section}{\itshape}{\thesection~}{0pt}{}[]
\section{How does this look?}

\subsection{Happy?}
\end{document}

在此輸入影像描述

答案2

使用expl3(由 加載xparse):

\documentclass[11pt,oneside,a4paper]{article}
\usepackage{titlesec}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\sectionfamily}{mm}
 {
  \fennell_section_family:nn { #1 } { #2 }
 }

\cs_new_protected:Npn \fennell_section_family:nn #1 #2
 {
  \tl_clear:N \l_fennell_section_font_tl
  \tl_clear:N \l_fennell_section_format_tl
  \str_case:nn { #2 }
   {
    { italic } { \tl_set:Nn \l_fennell_section_font_tl { \itshape } }
    { uppercase } { \tl_set:Nn \l_fennell_section_format_tl { \MakeUppercase } }
   }
  \use:x
   {
    \exp_not:N \titleformat
     { \exp_not:c { #1 } }
     { \exp_not:V \l_fennell_section_font_tl }
     { \exp_not:c { the#1 } }
     { 1em }
     { \exp_not:V \l_fennell_section_format_tl }
   }
 }
\ExplSyntaxOff

\sectionfamily{section}{uppercase}
\sectionfamily{subsection}{italic}

\begin{document}

\section{How does this look?}

\subsection{How does this look?}

\end{document}

您可以根據給定的範例添加其他關鍵字。不過,我認為這種「自動化」並不會帶來太多好處。

在此輸入影像描述

相關內容