3

My question goes in the same direction as this related one. I have already achieved some syntax highlighting in algorithm2e by redefining \KwSty, here is a MWE:

\documentclass{article}
% Math
\usepackage{amsmath}
\usepackage{amsfonts}
% Colors
\usepackage{xcolor}
\definecolor{mycolor}{RGB}{153, 0, 0}
% Algorithms
\usepackage{algorithm2e}
\renewcommand{\KwSty}[1]{\textnormal{\textcolor{mycolor}{\bfseries #1}}\unskip}

\begin{document}

\begin{algorithm}
  \SetAlgoLined\DontPrintSemicolon

  \ForEach{\(n \in \mathbb{K}\)}{
    \If{\(n < \tau\)}{
      \(print(\text{``Lower than''})\)\;
    }
    \Else{
      \(print(\text{``Greater than equal''})\)\;
    }
  }
  
\end{algorithm}

\end{document}

which generates:

enter image description here

But I wonder if a more fine-grained control is possible, i.e., having different colors for, say, the if and foreach blocks. I could not find this information on the manual.

2
  • 2
    Please make a compilable minimal working example which shows us which packages etc. you use. Commented Dec 16, 2022 at 14:31
  • @samcarter_is_at_topanswers.xyz thanks for the comment. I have edited the question.
    – rpanades
    Commented Dec 16, 2022 at 14:54

1 Answer 1

3

If you need more fine control, you could make your changes via the \SetKw... macros. You can find their default definitions in algorithm2e.sty, l. 2908ff.

\documentclass{article}
% Math
\usepackage{amsmath}
\usepackage{amsfonts}
% Colors
\usepackage{xcolor}
\definecolor{mycolor}{RGB}{153, 0, 0}
% Algorithms
\usepackage{algorithm2e}
%\renewcommand{\KwSty}[1]{\textnormal{\textcolor{mycolor}{\bfseries #1}}\unskip}

\SetKwFor{ForEach}{\textcolor{mycolor}{foreach}}{\textcolor{mycolor}{do}}{\textcolor{mycolor}{end}}%

\SetKwIF{If}{ElseIf}{Else}{\textcolor{teal}{if}}{\textcolor{teal}{then}}{\textcolor{teal}{else if}}{\textcolor{teal}{else}}{\textcolor{teal}{end if}}%

\begin{document}

\begin{algorithm}
  \SetAlgoLined\DontPrintSemicolon

  \ForEach{\(n \in \mathbb{K}\)}{
    \If{\(n < \tau\)}{
      \(print(\text{"Lower"})\)\;
    }
    \Else{
      \(print(\text{"Greather equal"})\)\;
    }
  }
  
\end{algorithm}

\end{document}

enter image description here

2
  • Thanks a lot. I should have look directly at the class definition. Maybe you want to remove the horrible typo I had on my original MWE :)
    – rpanades
    Commented Dec 16, 2022 at 15:05
  • @rpanades Your welcome. I edited the answer :) Commented Dec 16, 2022 at 15:07

You must log in to answer this question.

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