2

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)

  • 1
    Welcome to TeX.SX! You cannot copy the whole thing into the body of your markdown document. You must separate the preamble (which has to go to the Pandoc specific section) and the content which you may use in the document. – TeXnician Sep 26 '18 at 6:23
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See minimal working example (MWE). – Henri Menke Sep 26 '18 at 7:17
3

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

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.