[Tex/LaTex] Algorithm pseudocode in markdown

pandocpdfpseudocode

I am writing a project report in markdown. Use LaTeX inside the markdown to write formulas. Then I convert the markdown file to PDF with pandoc. All works like a charm.

But, I would like to include the pseudocode of an algorithm in this format: algorithm formatted

I have seen in this post Write pseudo code in latex how to do the same in pure LaTeX, but the code provided fails miserably while pandoc tries to interpret to render the PDF. This is the error code:

$ pandoc a.md -o a.pdf
! LaTeX Error: Can be used only in preamble.
See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
 ...                                                                             
l.60 \documentclass
pandoc: Error producing PDF

Anybody knows if this can be done? I can always write the pseucode in Overleaf.com and export it as image, but I would prefer to maintain all in the markdown file. THANKS!

BTW: The workflow is based in OSX (mactex 2018 + pandoc)

Best Answer

Thanks to TeXnician for pointing in the right direction: I was including the preamble inside the markdown.

After searching I figured out the solution. It seems that the only thing that needs to be in the preamble section is the \usepackage and that can be done inside the markdown following this syntax:

---
header-includes:
  - \usepackage{algorithm2e}
---

Here is a complete example of a .markdown document:

---
header-includes:
  - \usepackage[ruled,vlined,linesnumbered]{algorithm2e}
---
# Algorithm 1
Just a sample algorithmn
\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwResult{Write here the result}
\SetKwInOut{Input}{Input}\SetKwInOut{Output}{Output}
\Input{Write here the input}
\Output{Write here the output}
\BlankLine
\While{While condition}{
    instructions\;
    \eIf{condition}{
        instructions1\;
        instructions2\;
    }{
        instructions3\;
    }
}
\caption{While loop with If/Else condition}
\end{algorithm} 

It nicely renders this: enter image description here

Related Question