I am using xparse.sty to define a command that takes an optional argument in square brackets, and another one curly braces.
Problematically, it is not uncommon that the user will often want to begin the text after the command with square brackets. Since LaTex ignores spaces before the first optional argument, naively typing \myitem [not an argument] won't work, since "[not an argument]" will be considered an argument. MWE:
\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewDocumentCommand{\myitem}{ o g }{
\IfValueTF{#1}{%
[]-argument:~#1
}{
\IfValueTF{#2}{
\{\}-argument:~#2
}{
no~argument:~
}
}
}
\ExplSyntaxOff
\begin{document}
\myitem [Not intended as argument]
% Will output: []-argument: Not intended as argument
\end{document}
What's worse, because \myitem also takes a g argument, the standard technique for avoiding this issue (inserting a pair of braces before or around the text in square brackets) won't work eiter:
\myitem {}[Not intended as argument]
% Will output {}-argument: [Not intended as argument]
\myitem {[Not intended as argument]}
% Will output {}-argument: [Not intended as argument]
The only workaround right now is to use \relax before the square brackets, which I would like to avoid.
Is it possible to make LaTeX treat the spaces as terminating the argument list in this case? I.e., \myitem [foo] should output no argument: foo, while \myitem[foo] should (still) output []-argument: foo?
gis provided, but it's not really recommended. Anyway, there is no space in\myitem [...], because of how TeX reads its input. – egreg Aug 27 '17 at 09:37{}in this case. What's the purpose of this? – Aug 27 '17 at 09:48gargument). So I might have to simply give up on using that argument. – Sven Lauer Aug 27 '17 at 10:08\itemlike command, and agargument seemed like the natural choice for one them. Given this problem, I'll have to take that argument in another way (since I could live with users having to do the "standard technique" of using curly braces for avoiding that the part in square brackets is parsed as an argument). – Sven Lauer Aug 27 '17 at 10:12-argumentwith an empty argument, you can test the content of#2and ignore if empty. Then you can write\mymacro{} [not an argument]. But using{}for optional arguments is not a good idea unless there's very strong reason to do it. – cfr Aug 27 '17 at 12:26I was unsure whether I should do it in the first place, though more because going against established conventions usually is a bad idea. I did not consider that it would also lead to problems on the implementation side.
– Sven Lauer Aug 27 '17 at 12:49\verbcan appear) then it's possible, see https://tex.stackexchange.com/a/472250/250119 and the linked question from below it. – user202729 Dec 30 '22 at 03:02