I was able to use my scalerel package to hopefully give you what you want (scalerel was just sent to CTAN today, so until it propagates, you can find the style listing at How to horizontally merge two symbols?).
Using that package's features, my first cut was to create a command \myabs, which places abs bars around anything. It will stretch the size of the bars exactly to the argument. The downside of this first attempt is that you may have preferred the bars to extend a bit above and below the object being surrounded (addressed later in this answer). Here's the code for the first approach:
\documentclass{article}
\usepackage{scalerel}
\usepackage{mathtools}
\begin{document}
% [METHOD USED IN ORIGINAL QUESTION CODE HERE, REMOVED FROM THIS LISTING]
\newcommand\myabs[1]{%
\setbox1\hbox{$#1$}%
\stretchrel{\lvert}{\usebox1}\stretchrel*{\lvert}{\usebox1}%
}
\[ \myabs{\vec{k}}~~\myabs{\vec{x}}~~\myabs{\vec{A}}~~\myabs{\vec{q}} \]
\end{document}
and here's the output, as compared to your original
However, to answer ralfix's request to extend the vertical line a bit above and below the surrounding object, I just used the \addvbuffer routine from the verbatimbox package, setting the top and bottom add-on to 2pt:
\documentclass{article}
\usepackage{scalerel}
\usepackage{mathtools}
\usepackage{verbatimbox}
\setlength\boxtopsep{2pt}
\setlength\boxbottomsep{2pt}
\newcommand\myabs[1]{%
\setbox1\hbox{$#1$}%
\setbox2\hbox{\addvbuffer{\usebox1}}%
\stretchrel{\lvert}{\usebox2}\stretchrel*{\lvert}{\usebox2}%
}
\begin{document}
\[ \myabs{\vec{k}}~~\myabs{\vec{x}}~~\myabs{\vec{A}}~~\myabs{\vec{q}} \]
\end{document}
But egreg commented that the height of the abs bar should not change with the argument. If that is the preferred embodiment of abs, then scalerel can fix that too:
\documentclass{article}
\usepackage{scalerel}
\def\lvert{|}
\begin{document}
METHOD 2: FIXED EXTENT
\newsavebox\mybox
\savebox{\mybox}{$\stretchrel*{|}{\rule[-.6ex]{0ex}{3ex}}$}
\def\myabs#1{\usebox\mybox#1\usebox\mybox}
\[ \myabs{\vec{k}}~~\myabs{\vec{x}}~~\myabs{\vec{A}}~~\myabs{\vec{q}} \]
\end{document}
Make sure the \abs
macro is defined.
\documentclass{article}
\usepackage{mathtools} % for '\DeclarePairedDelimiter' macro
\DeclarePairedDelimiter{\abs}{\lvert}{\rvert} % define '\abs' macro
\begin{document}
$\frac{\abs{\lambda_f}}{8\pi^2}$\quad $\dfrac{\abs{\lambda_f}}{8\pi^2}$
\end{document}
Best Answer
I have been using the code below using
\DeclarePairedDelimiter
from themathtools
package.Since I don't think I have a case where I don't want this to scale based on the parameter, I make use of Swap definition of starred and non-starred command so that the normal use will automatically scale, and the starred version won't:
If you want it the other way around comment out the code between
\makeatother...\makeatletter
.