I want to write a macro that expands differently depending on the pattern following it. Specifically I want to use it to allow a more readable notation for quantum mechanical states, e.g.
% Non-working example
\def \m<#1| { \left\langle #1 \right|}
\def \m|#1> { \left| #1 \right\rangle }
\def \m<#1> { \left\langle #1 \right\rangle }
\def \m<#1|#2> { \left\langle #1 \middle| #2 \right\rangle }
The way LaTeX works, it can expand only one of the definitions. If I skipped the last one, a possible fix would be to change the catcode of <
,|
,>
to 11, but that brings issues of its own (e.g. by breaking \ifnum .. < ..
forms).
Is there some facility in latex, maybe through a package, that allows matching a single macro to multiple patterns of subsequent tokens?
Clarification Because it came up: I don not want to define commands \bra
, ket
, etc, or rather this is what I did so far. I am trying to move to a solution that results in more readable code and while writing \bra <\psi_i| \Operator \ket |\psi_j>
would be a step towards that target, I'd prefer a form as close as possible to <\psi_i|\Operator|\psi_j>
; Pattern matching would be the closest solution I could think of that could work without preprocessing outside of latex.
Furthermore writing complex macros, that analyze the token stream, isn't something I want to do on a per-document level. I'd prefer if there was a package that abstracts such things away, such that even the definition of the pattern remains well-readable for the sake of avoiding unexpected behaviour. If TeX's \def
natively supported pattern-matching, the example code above would suit that requirement.
\m<#1|
different from\m<#1|#2>
? (We can look after a|
for 'something' but will need a clue, for example is the first case always followed by a space?)>
?>
. You have to have some restriction on what can be present in#2
to allow us to know when to stop!<
is always ultimately followed by>
we can grab everything up to>
then use a variety of approaches to process the text.\m*...*
where...
can have the various forms<#1>
,<#1|
,|#1>
,<#1|#2>
or<#1|#2|#3>
, then it's doable. But without a fixed terminator it would be very hard and fragile.