![如何使用 xparse argspec 實作類似 \verb 的行為?](https://rvso.com/image/281594/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20xparse%20argspec%20%E5%AF%A6%E4%BD%9C%E9%A1%9E%E4%BC%BC%20%5Cverb%20%E7%9A%84%E8%A1%8C%E7%82%BA%EF%BC%9F.png)
如何使用先前掃描的標記作為argspecu{}
中的參數xparse
?
\documentclass{article}
\usepackage{xparse}
\NewDocumentEnvironment {some-cool-env} {D<>{\stopscan} u{#1}} {%
Here is the text up until the stopping token: ``#2'' \newline
Here's the rest of the environment: \par
} {}
\begin{document}
\begin{some-cool-env}
I am a\stopscan teapot
\end{some-cool-env}
(some inner text)
\begin{some-cool-env}<|>
A custom built|teapot.
\end{some-cool-env}
\end{document}
這會給
Here is the text up until the stopping token: "I am a"
Here's the rest of the environment:
teapot
(some inner text)
Here is the text up until the stopping token: "A custom built"
Here's the rest of the environment:
teapot.
我怎樣才能實現我想要的語法? (希望不會侵入xparse
的內部......)
上面的簡單方法會產生以下錯誤:
ERROR: Illegal parameter number in definition of \__xparse_grab_arg:w. --- TeX said --- <to be read again> 1 l.9 \DumbVerb <|>test| --- HELP --- This is probably caused by a \newcommand, \renewcommand, \newenvironment, or \renewenvironment command in which a # is used incorrectly. A # character, except as part of the command name \#, can be used only to indicate an argument parameter, as in #2, which denotes the second argument. This error is also caused by nesting one of the above four commands inside another, or by putting a parameter like #2 in the last argument of a \newenvironment or \renewenvironment command.
自從 @egreg 回答以來,我已經對問題正文進行了相當多的編輯,但問題標題保持不變。應該注意的是,@egreg 回答的問題是針對用xparse
.在這種情況下,他的答案是可行的,但不幸的是,它不能立即推廣到定義類似的環境。 (嗯,這不是真的;你仍然可以定義一個輔助環境,但這仍然感覺像作弊...)
答案1
這可能拉伸太多xparse
,但由於mu{#1}
似乎有效,您可以分兩個階段進行:
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand\DumbVerb{D<>{|}}{\DumbVerbAux{#1}}
\NewDocumentCommand\DumbVerbAux{mu{#1}}{Here's #2}
\begin{document}
\DumbVerb test|
\DumbVerb<x>testx
\DumbVerb<\xyz>test\xyz
\end{document}
答案2
這來自egreg的回答可能是目前最好的方法,但我想從為什麼期望的方法失敗的角度來看這個問題。這基本上有兩個部分。
在技術層面上,使參數能夠使用先前獲取的資訊(可能)是可行的,但通常完全做到這一點會變得非常煩人:想像一個具有九個參數的函數,在這裡你必須允許八個可能的先前獲取的參數。使用專用輔助設備(如egreg的答案)可以避免這種複雜性,但必須在特別指定基礎。
在概念層面上,xparse
旨在創建「類似 LaTeX2e」但也是「一致」的文檔級介面。這裡請求的問題在於接口不是一致:每次使用該指令時,都必須掃描不同的標記。理想情況下,此類方法不應該出現在文件中,當然也不應該有任何規律性,因此支持這一點的必要性xparse
還很不明確。