2

I am writing a book using a sans serif font, and I have a need for typesetting pseudocode. The pseudocode, however, is typeset with sans serif font as well, yet I need the Times New Roman for that task. How can I force LaTeX/algorithm2e to use Times New Roman?

2 Answers 2

1

I don't know how you set up your fonts, but this should be a starting point.

\documentclass{book}
\usepackage{newtxtext,newtxmath}
\usepackage{algorithm2e}
\usepackage{algpseudocode}
\usepackage{etoolbox}
\usepackage{lipsum}

\renewcommand{\familydefault}{\sfdefault}
\AtBeginEnvironment{algorithmic}{%
  \renewcommand{\familydefault}{\rmdefault}%
  \fontfamily{\familydefault}\selectfont
}

\begin{document}

\lipsum[1]

\begin{algorithm}
\centering
\begin{algorithmic}
\Function{foo}{x}
\State $x \gets 1$
\EndFunction
\end{algorithmic}
\end{algorithm}

\lipsum[2]

\end{document}

enter image description here

1

Here are some example adjustments using the standard mechanisms provided by the algorithme2e package.

Firstly setting \SetAlFnt{\rmfamily} will change much of the text to roman. However, you will find things such as keywords, arguments etc. still using sans serif fonts. There are a number commands to adjust these too, see the documentation. The commands are of the form \Set...Sty{...} where the argument is a command without the backslash. A simple switch such as \ttfamily can be passed as ttfamily, but for changing multiple attributes you will have to define your own command and pass that. I have provided an example for arguments below.

Sample output

\documentclass{article}

\usepackage{algorithm2e}
\renewcommand{\familydefault}{\sfdefault}
\SetAlFnt{\rmfamily}
\SetKwSty{ttfamily}
\newcommand{\myargfont}{\rmfamily\slshape}
\SetArgSty{myargfont}

\begin{document}

Sample main text.

\begin{algorithm}
  \SetAlgoLined
  \KwData{this text}
  \KwResult{how to write algorithm with \LaTeX2e }
  initialization\;
  \While{not at end of this document}{
    read current\;
    \eIf{understand}{
      go to next section\;
      current section becomes this one\;
      }{
      go back to the beginning of current section\;
      }
    }
  \caption{How to write algorithms}
\end{algorithm}

Sample main text.

\end{document}

You must log in to answer this question.

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