保存值(如字串)以供以後使用的最佳方法是什麼?

保存值(如字串)以供以後使用的最佳方法是什麼?

我對 LaTeX 相當陌生,我正在努力解決一些看似簡單的問題,但我找不到公平的解決方案。問題(簡化)如下(請注意所使用的術語可能不具有 LaTeX 中的傳統含義):

我需要引用文件(許多)貫穿全文。例如,文件: "C:/Work/this_file1.c""C:/MoreWork/this_file1.c""D:/MoreWork/another_file2.h".

所以,現在我想為每個目錄和每個名稱檔案建立一個“別名”,以便我可以引用它們。 “偽代碼”可以是:

% Definition
\alias \c_dir = C:/Work/
\alias \d_dir = D:/MoreWork/
\alias \file1 = this_file1.c
\alias \file2 = another_file2.h

% Reference in text
\c_dir\file1    % For referencing C:/Work/this_file1.c
\d_dir\file1    % For referencing D:/MoreWork/this_file1.c
\c_dir\file2    % For referencing C:/Work/another_file2.h

我的第一個方法是使用\newcommand,但是由於命名限制,這導致了許多問題。 (我也嘗試過其他方法,例如pgfkeys,但它總是卡在某個地方!)

你能建議一個方法嗎?

答案1

對於更靈活的別名,可以這樣做。在範例中我刪除了底線;根據預期用途,您可能想要轉義它們 ( \_) 或不轉義它們 ( _)。

\documentclass{article}
\newcommand\alias[2]{\expandafter\def\csname alias:#1\endcsname{#2}}
\newcommand\A[1]{\csname alias:#1\endcsname}

\alias{c_dir}{C:/Work/}
\alias{d_dir}{D:/MoreWork/}
\alias{file1}{thisFile1.c}
\alias{file2}{anotherFile2.h}

\begin{document}
\A{c_dir}\A{file1}

\A{d_dir}\A{file1}

\A{c_dir}\A{file2}
\end{document}

正如 @MaestroGlanz 所建議的,可以使用以下套件更緊湊地定義命令\alias和:\Aetoolbox

\usepackage{etoolbox}
\newcommand\alias[2]{\csdef{alias:#1}{#2}}
\newcommand\A[1]{\csuse{alias:#1}}

因為在原始問題中提到,這裡有一個pgfkeys解決方案(儘管我不知道有任何優點):

\usepackage{pgfkeys}
\newcommand\alias[2]{\pgfkeyssetvalue{/alias/#1}{#2}}
\newcommand\A[1]{\pgfkeysvalueof{/alias/#1}}

範例文件在所有版本中的結果:

在此輸入影像描述

答案2

\newcommand只要命令名稱遵循 tex 規則(本質上由字母組成),您就可以使用。

% Definition
\newcommand\cdir{C:/Work/}
\newcommand\ddir{D:/MoreWork/}
\newcommand\fileA{this\_file1.c}
\newcommand\fileB{another\_file2.h}

% Reference in text
\cdir\fileA    % For referencing C:/Work/this_file1.c
\ddir\fileA    % For referencing D:/MoreWork/this_file1.c
\cdir\fileB    % For referencing C:/Work/another_file2.h

答案3

感謝您的回覆...非常有用...並且讓我走得更遠。

首先,最初的問題並不那麼清晰,所以一個更「真實」的例子應該可以解決問題:

在 LaTeX 文件中,我需要「包含」部分外部文件(通常是軟體原始碼)。來源檔案需要複製到臨時位置並(重要)取得臨時名稱(例如temp1.tmptemp2.tmp...等)。 [注意:如何製作副本並不重要......只是必須追蹤路徑和檔案名稱。

因此,以下是我正在使用的解決方案。只是分享...

\documentclass{article}

\usepackage{keyval}
\makeatletter
\newcounter{cntTmp}
\newcommand{\mylongS}[4]{
    % In here I pass the source and destination file parameters
    srcDir: #1; srcFile: #2; dstDir: #3; dstFile: #4    

    %I Now use the parameters to create a string to store in a just-defined key
    \define@key{}{this\arabic{cntTmp}}[]{#1:#2:#3:#4}
    \stepcounter{cntTmp}
}

\makeatother

\begin{document}
    % This should "account" as the first file copied... to temp0.tmp    
    \mylongS{S:/work}{testtxt}{t}{temp0.tmp}

    % This should "account" as the SECOND file copied... to temp1.tmp   
    \mylongS{S:/work}{testtxt}{t}{temp1.tmp}

    % Now I have access to the full string... and may use string manipulation
    \setkeys{}{this0}

    \setkeys{}{this1}
\end{document}

相關內容