0

Suppose I have a custom macro defined with \newcommand (no fancy parsing going on). For simplicity assume

\newcommand{\mymacro}[1]{#1}

Is there a way to redefine the macro so that, every time the macro is expanded we add a line to an auxiliary file with the sourcecode coordinates of the occurrence of the macro?

Example

  • main.tex

    \documentclass{article}
    \begin{document}
    \newcommand{\mymacro}[1]{#1} % redefine appropriately
    \input{bla}
    \end{document}
    
  • bla.tex

    Lorem Ipsum
    dolor \mymacro{sit amet} consectetur
    \mymacro{adi\emph{pisci}ng} elit
    

With desired output in some auxiliary file, say main.mymacro:

bla.tex:2:7-24
bla.tex:3:1-27

That is, records of the form file:line:start-end. If outputing the end position is too difficult, a verbatim dump of the argument would also be acceptable (e.g. bla.tex:3:1 adi\emph{pisci}ng)

Note that I am looking for a TeX based solution. I know one could try to parse these occurrences, but I would like to have a way to locate them that was consistent with TeX' expansion mechanism, without having to reimplement it or half-simulate it with hackish regexes.

My use case

suppose I write comments in my sourcecode with \mycomment{bla}. Now I want to remove those comments programmatically. If I start doing it with regexes I get into a lot of trouble (and will not get anything close to a general solution, even if simply because of finding matching brackets). Parsing is similarly problematic if one has anything slightly fancy in the sourcecode. A solution to this question would allow to safely remove the substrings with a postprocessing pass using the offsets in the auxiliary file.

  • that depends where the macro is used, you can print the current line number if you can write anything at all, but writing to the log is a necessarily non-expandable macro so if the macro is used where expansion is required (as a number, at the start of table cells, in \typeout` , ... then the command will not work at all if you add non expandable logging. – David Carlisle Nov 8 at 18:49
  • you can assume the macro is used to add format to the argument, so it is not going to be used in fancy contexts. Think an interim commenting macro – Bordaigorl Nov 8 at 19:30
  • so just add \wlog{used on line \the\inputlineno} to the macro. – David Carlisle Nov 8 at 19:34
  • @DavidCarlisle would that output the filename as well? how can one output where the macro ends as well? – Bordaigorl Nov 8 at 19:38
  • it is the line where the macro ends (or more particularly the line tex has got up to so far) if you have input files using latex conventions \@curr@file usually has the current filename and \jobname the main top level document. – David Carlisle Nov 8 at 19:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.