[Tex/LaTex] Problem with underscores in \newcommand


I am currently writing my thesis and I have each chapter as a separate project- I've been told I should join them up but I don't want to for now as I would find it overwhelming. I'd like to be able to reference labels of figures, tables, equations etc that are in other Chapters, i.e other projects, so that when I do eventually link up the chapters as a single project, the cross-referencing all works fine. If I add in the references as this stage, I obviously get warnings because the reference doesn't exist. What I would like to do is have a command that I can switch on and off which turns on and off these external references. I call this command \refext for 'external reference'.
Initially, I had code that looked like:

Option 1: Do nothing, I'm not ready, output the reference as words

\newcommand{\refext}[1]{Ref. #1}

Option 2: Yes, go ahead and reference up- I'm ready to compile all these things together as a single document:


I would comment out the command I wasn't using, and in this way it was 'switchable' It would either print out the name of the label, or treat it as an ordinary reference.

This works, if the label is a single word. However this does not work if the label contains an underscore in the title- which all of my labels do.

After some reading, I have come across this answer which is similar to what I want to do:
How can I pass underscore to \newcommand properly?

However, I have tried this and it doesn't work for me:

\newcommand{\refext}{\begingroup\catcode`\_=11 \dorefext}


I get the error 'missing begin document' however of course I want to define my rules before I begin my document. The document compiles fine with all my other \newcommands being in the same place.

Catcode 12 also doesn't work. I switched it out for 11 because I thought it might be better if it treated the underscore as text.

I don't really know what I'm doing here! I am not very adept with latex and I've entered into this new commands area a bit blind! Help would be much appreciated- thank you!

Best Answer

Underscores can be part of a label, but printing them is normally disallowed, because the underscore is used in running text for denoting subscripts in math formulas.

Option 2 should give no problem: you're just replacing \ref with \refext. For option 1, when you want to see the keys rather than the reference, you can do


The \detokenize command will, besides other things, make _ printable. I added also \texttt in order to make the key more evident in the text.

Small example (I'll use option 2):




Here's some text where we cite \refext{some_thing} and go on


enter image description here

Related Question