7

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)

2
  • 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. Commented Sep 26, 2018 at 6:23
  • 3
    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). Commented Sep 26, 2018 at 7:17

1 Answer 1

8

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

1
  • 1
    Hi monti I use jupyter-lab, Could you put full code, I misunderstand how to use it Commented Jul 1, 2022 at 18:42

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.