[Tex/LaTex] How to find out where a macro is defined

macrostex-core

Using \@ifdefined (in LaTeX), we can check whether a command is defined.

Using \meaning, we can get the definition of a command.

Can we also get information about where a command was defined? For example, in terms of the source file and line number? Does TeX even keep track of this information?

We can grep through source files, but with constructs like \csname, there's no guarantee that the definition will show up.

Best Answer

Oh, I find a much better way to do this, also with help of filehook (the code is somewhat tricky):

\documentclass{article}
\usepackage{filehook,currfile}
\newwrite\finder
\immediate\openout\finder=\jobname.fnd

\def\searchmacro#1{
  \AtBeginOfFiles{%
    \ifdefined#1
      \expandafter\def\csname \currfilename:found\endcsname{}%
    \fi}
  \AtEndOfFiles{%
    \ifdefined#1
      \unless\ifcsname \currfilename:found\endcsname
        \immediate\write\finder{found in '\currfilename'}%
    \fi\fi}}

\searchmacro\url

\usepackage{hyperref}
\begin{document}
dummy
\end{document}

After compiling, we will get

found in 'url.sty'
found in 'hyperref.sty'

in \jobname.fnd. That is to say, \url is defined in url.sty, which is inputed by hyperref.sty.