I need some latex help for my thesis. So I have the following command:


which allows me to write references to chapters of my document with:

\refChap{first_work} % the 'chap:' part is added by the function

for example. I have many references of this kind in my thesis. However, with autocomplete in VSCode which I am now using for writing, it is more convenient to write:

\refChap{chap:first_work} % the 'chap:' part is added by me in the args

I could do a find and replace to fix the whole thesis to add chap: to these references. But the same thing also applies to fig, eqn, etc.

I would prefer if I can fix the refChap function to work with or without the 'chap:' part. To do this, I tried the following:


This preprends 'chap:' if not there already.



However, this breaks the pdf rendering, and chap: is repeated a lot where I tried to use this.

What am I doing wrong? Apologies if its a basic error, Im new to writing my own latex commands. BTW, I'm aware that as an additional complication, chapter labels contain underscores. However, I also tested this on a chapter name without underscores, which didn't help.

1 Answer 1


LaTeX has a rather complex way of expanding arguments which is very different from other programming languages where an expression can occur at almost any position and be evaluated with the result being used as a part of another expression. Therefore it's usually better to keep the arguments to macros 'clean' and do the processing outside of the argument.

In this case you can check if the argument starts with the prefix using \IfBeginWith and use a \ref statement with the original argument in the True case and another \ref statement with an added prefix in the False case.


\chapter{First work}
This is \refChap{first_work}, which is the same as \refChap{chap:first_work}.


enter image description here

  • Thanks so much!
    – EBartrum
    Aug 12, 2022 at 13:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .