1

I am following the solution in this answer to add captions and cross-references to code chunks in an .Rmd file.

I would like to use cleveref to refer to these code chunks. However, currently my \cref's are being prefixed by ??. How can I fix my code to prevent this?


Don't look at me. I'm hideous.


MWE

\documentclass{report}

\usepackage{color}
\usepackage{cleveref}
\usepackage{floatrow}
\usepackage{caption}
\usepackage{framed}
\usepackage{fancyvrb}


% Extra bits for context
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
\definecolor{shadecolor}{RGB}{248,248,248}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}


% Make a new chunk float to attach label and caption to
\DeclareNewFloatType{chunk}{placement=H, fileext=chk, name=}
\captionsetup{options=chunk}
\renewcommand{\thechunk}{Chunk~\thesection.\arabic{chunk}}
\makeatletter
\@addtoreset{chunk}{chapter}
\makeatother


\begin{document}

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{## Assign the value 5 to x}
\NormalTok{x =}\StringTok{ }\DecValTok{5}
\NormalTok{x}
\end{Highlighting}
\end{Shaded}

\captionof{chunk}{This is an example of a code caption.}\label{chk:example}

In \cref{chk:example} we do computering.

\end{document}
2

You have to declare \crefname & \Crefname. I took the opportunity to simplify a bit your code.

 \documentclass{report}

\usepackage{color}
\usepackage{cleveref}
\usepackage{floatrow}
\usepackage{caption}
\usepackage{framed}
\usepackage{fancyvrb}


% Extra bits for context
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
\definecolor{shadecolor}{RGB}{248,248,248}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{#1}}
\newcommand{\NormalTok}[1]{#1}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{#1}}

% Make a new chunk float to attach label and caption to
\DeclareNewFloatType{chunk}{placement=H, fileext=chk, within=section, name=Chunk}
\crefname{chunk}{chunk}{chunks}
\Crefname{chunk}{Chunk}{Chunks}

\begin{document}

\begin{Shaded}
\begin{Highlighting}[]
\NormalTok{## Assign the value 5 to x}
\NormalTok{x =}\StringTok{ }\DecValTok{5}
\NormalTok{x}
\end{Highlighting}
\end{Shaded}

\captionof{chunk}{This is an example of a code caption.}\label{chk:example}

In \cref{chk:example} we do computering.

\end{document}

enter image description here

1
  • Thank you! This solved my problem. – jwalton Oct 13 '20 at 9:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.