siefkenj / unified-latex

Utilities for parsing and manipulating LaTeX ASTs with the Unified.js framework
MIT License
85 stars 20 forks source link

Macro default argument support #24

Open theseanl opened 1 year ago

theseanl commented 1 year ago

I'm trying to write some custom plugins for transforming latex, and so far, I really liked your work, especially in how you provide every required toolsets via modular package structure. While experimenting with it, I noticed that currently there's no support for macros with default arguments.

% input.tex
\documentclass{article}
% \newcommand\foo[2][bar]{#1,#2}
\begin{document}
    \foo[bar]{baz}
    \foo{baz}
\end{document}
unified-latex input.tex -e "\\newcommand\\foo[2][bar]{#1,#2}"

Then the result will be

\documentclass{article}

%\newcommand\foo[2][bar]{#1,#2}

\begin{document}
        bar,baz

        ,baz
\end{document}

where the expected output would have two identical lines of bar,baz.

In unified-latex-util-macros, an xpase-style signature is computed, but it produces o irrespective of the presence of a default argument. I've also noticed that manually passing O{bar} m via \NewDocumentCommand still produces unexpected results, so there should be another issue regarding macro expanders.

It'd be nice if this support can be added. I'm wondering to know if there's any blocker for implementing it, I'm interested in sending a PR.

siefkenj commented 1 year ago

That would be a welcome PR :-).

It looks like, after you figure out how to grab the default arg when parsing the macro string, a little modification to

https://github.com/siefkenj/unified-latex/blob/c0d8a9bcbf65222a3245c383c1e9e314f8c4bf7c/packages/unified-latex-util-macros/libs/newcommand.ts#L189

should be most of what is needed.

Please include some tests with your PR :-D