Following up on @Roman Starkov's \mybox definition for a tight \fbox (How to put a framed box around text + math environment), I'd like to add an optional parameter to adjust the pt allowance around the text inside the \fbox. I tried the following MWE, and it runs as a standalone command, but the \mybox command will not run when included within my larger project:
\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\pagestyle{empty}
\usepackage{collectbox}
\makeatletter
\def\mybox{@ifnextchar[{@with}{@without}}
\def@with[#1]{%
\collectbox{%
\setlength{\fboxsep}{#1pt}%
\fbox{\BOXCONTENT}%
}%
}
\def@without{%
\collectbox{%
\setlength{\fboxsep}{1pt}%
\fbox{\BOXCONTENT}%
}%
}
\makeatother
\begin{document}
\mybox{A rolling stone gathers no moss.} \par
. \par
\mybox[2]{A rolling stone gathers no moss.} \par
. \par
\mybox[3]{A rolling stone gathers no moss.} \par
\end{document}
The above MWE will run just fine as a standalone command. However, when included within my larger project (>20k lines of code), the same code results in the following error at the line of code: \mybox[2]{A rolling stone gathers no moss.} \par
Any thoughts as to what I can do to debug would be greatly appreciated.
Apologies for not including a version of the above code that results in the above error.
FYI, I checked that there are NO other \mybox commands within my larger project.
UPDATE:
@user202729 and @Simon Dispa:
I garnished your solution with a few tweaks to take care of characters being overwritten at the end of the box. I did not recognize this at first, so I added a ~ just after the \fbox which seems to have corrected the issue. I also set the default pt allowance to 2pt as it seems to give me more of what I was looking for initially, while still allowing me to adjust the pt allowance to suit the boxed text and the surrounding paragraph.
Thanks for your solution. The following is the final code for \myNewBox:
\newcommand{\myNewBox}[2][]{\ifthenelse{\isempty{#1}}%
{\collectbox{\setlength{\fboxsep}{2pt}\fbox{#2}}~}%
{\collectbox{\setlength{\fboxsep}{#1pt}\fbox{#2}}~}%
}
The above code now works perfectly in my larger project!


\defwith\long\def. – user202729 Jun 18 '22 at 06:45@withlooks dangerous. Might conflict with something existing. – user202729 Jun 18 '22 at 06:46\longdoes from the book) – user202729 Jun 18 '22 at 06:49