45

I wanted to know how to change the comment style in the algorithm2e package. I want to make my comments of a smaller font and a different color:

\documentclass{article}

\usepackage{color}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}

\begin{document}

\begin{algorithm}[H]
\DontPrintSemicolon
\CommentSty{\color{blue}}
  \KwData{Training set $x$}
  $\Delta_{ji}^l := 0$ \tcp*{will be used to compute $\partial x$}
  \tcc{iterate over all training examples}
\caption{Example code}
\end{algorithm}

\end{document}

2 Answers 2

58

You need to define a command with an argument giving the font specification and then use the name of this command in the argument for \SetCommentSty:

\documentclass{article}
\usepackage{xcolor}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\newcommand\mycommfont[1]{\footnotesize\ttfamily\textcolor{blue}{#1}}
\SetCommentSty{mycommfont}

\begin{document}

\begin{algorithm}[H]
\DontPrintSemicolon
  \KwData{Training set $x$}
  $\Delta_{ji}^l := 0$ \tcp*{will be used to compute $\partial x$}
  \tcc{iterate over all training examples}
\caption{Example code}
\end{algorithm}

\end{document}

enter image description here

3
  • 4
    Hi @GonzaloMedina, when I try \tcp it adds a new line after the code comment, so my code skips a line. Why is this? I am using algorithm2e and the line looks like: set $cost\_vector \; \vv{c_{p,v}} = \left\lbrace \right\rbrace$\tcp*{will be used to compute $\partial x$}\; Commented Sep 9, 2016 at 16:20
  • 2
    How to reduce space between examples and */?
    – Dr.PB
    Commented Jul 1, 2017 at 10:16
  • (for reference: The commenter above ask a follow-up question on how to reduce space before */)
    – user202729
    Commented Jun 14, 2022 at 11:33
7

This answer is similar to the one provided by @GonzaloMedina with space adjusted within comments.

\documentclass{article}
\usepackage{xcolor}
\usepackage[linesnumbered,ruled,vlined]{algorithm2e}
\newcommand\mycommfont[1]{\footnotesize\ttfamily\textcolor{blue}{#1}}
\SetCommentSty{mycommfont}

\begin{document}

\begin{algorithm}[h]
\DontPrintSemicolon
\SetAlgoLined
\SetNoFillComment
\LinesNotNumbered 
%\SetSideCommentLeft
\tcc{iterate over all training examples}
 \KwData{this text}
 \KwResult{how to write algorithm with \LaTeX2e }
 initialization\;
 \While{not at end of this document}{
  read current \tcp*[l]{will be used to compute $\partial x$}
  \eIf{understand}{
   go to next section \tcp*{will be used to compute $\partial x$}
   current section becomes this one\;
   }{
   go back to the beginning of current section\;
  }
 }
 \caption{How to write algorithms}
\end{algorithm}

\end{document}

enter image description here

You must log in to answer this question.

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