Skip to content

Commit

Permalink
fix: \providecommand does not overwrite existing macro (#4000)
Browse files Browse the repository at this point in the history
Fixes #3928
  • Loading branch information
edemaine authored Jan 12, 2025
1 parent 8f47dba commit 6d30fe4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
25 changes: 16 additions & 9 deletions src/macros.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,9 @@ defineMacro("\\char", function(context) {
// \newcommand{\macro}[args]{definition}
// \renewcommand{\macro}[args]{definition}
// TODO: Optional arguments: \newcommand{\macro}[args][default]{definition}
const newcommand = (context, existsOK: boolean, nonexistsOK: boolean) => {
const newcommand = (
context, existsOK: boolean, nonexistsOK: boolean, skipIfExists: boolean
) => {
let arg = context.consumeArg().tokens;
if (arg.length !== 1) {
throw new ParseError(
Expand Down Expand Up @@ -181,16 +183,21 @@ const newcommand = (context, existsOK: boolean, nonexistsOK: boolean) => {
arg = context.consumeArg().tokens;
}

// Final arg is the expansion of the macro
context.macros.set(name, {
tokens: arg,
numArgs,
});
if (!(exists && skipIfExists)) {
// Final arg is the expansion of the macro
context.macros.set(name, {
tokens: arg,
numArgs,
});
}
return '';
};
defineMacro("\\newcommand", (context) => newcommand(context, false, true));
defineMacro("\\renewcommand", (context) => newcommand(context, true, false));
defineMacro("\\providecommand", (context) => newcommand(context, true, true));
defineMacro("\\newcommand",
(context) => newcommand(context, false, true, false));
defineMacro("\\renewcommand",
(context) => newcommand(context, true, false, false));
defineMacro("\\providecommand",
(context) => newcommand(context, true, true, true));

// terminal (console) tools
defineMacro("\\message", (context) => {
Expand Down
8 changes: 3 additions & 5 deletions test/katex-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3659,17 +3659,15 @@ describe("A macro expander", function() {
expect`\newcommand{\foo}{1}\foo\renewcommand{\foo}{2}\foo`.toParseLike`12`;
});

it("\\providecommand (re)defines macros", () => {
it("\\providecommand defines but does not redefine macros", () => {
expect`\providecommand\foo{x^2}\foo+\foo`.toParseLike`x^2+x^2`;
expect`\providecommand{\foo}{x^2}\foo+\foo`.toParseLike`x^2+x^2`;
expect`\providecommand\bar{x^2}\bar+\bar`.toParseLike`x^2+x^2`;
expect`\providecommand{\bar}{x^2}\bar+\bar`.toParseLike`x^2+x^2`;
expect`\newcommand{\foo}{1}\foo\providecommand{\foo}{2}\foo`
.toParseLike`12`;
.toParseLike`11`;
expect`\providecommand{\foo}{1}\foo\renewcommand{\foo}{2}\foo`
.toParseLike`12`;
expect`\providecommand{\foo}{1}\foo\providecommand{\foo}{2}\foo`
.toParseLike`12`;
.toParseLike`11`;
});

it("\\newcommand is local", () => {
Expand Down

0 comments on commit 6d30fe4

Please # to comment.