# format sagetex code like console or notebook

I'd like to put sage code in my LaTeX document that looks mostly like how an interactive session would appear, except that I want LaTeX formatted output.

So, I'd like to write something like this in my LaTeX file:

\begin{sageblock}
gcd(x^2 + 2*x + 1, x + 1)
\end{sageblock}


and the result is first a Courier-typeset box containing

sage: gcd(x^2 + 2*x + 1, x + 1)


and then a box after that containing the LaTeX formatted result.

$$x+1$$


Any idea how to do this, without assigning the result to an auxiliary variable and then printing the variable?

## The sageexample environment

The sageexample environment does exactly that (except the sage: prompt needs to be added by hand).

Create a latex file gcd.tex containing

\documentclass{article}
\usepackage{sagetex}
\begin{document}
\begin{sageexample}
sage: gcd(x^2 + 2*x + 1, x + 1)
\end{sageexample}
\end{document}​


then in a terminal run

pdflatex gcd && sage gcd.sagetex.sage && pdflatex gcd


and a pdf will be produced containing

sage : gcd(x^2 + 2*x + 1, x + 1)


x + 1

(where x + 1 is typeset).

## The sagecommandline environment

Note the related sagecommandline environment which leaves the output in non-typeset form, and is good for running doctests.

Create a latex file gcd.tex containing

\documentclass{article}
\usepackage{sagetex}
\begin{document}
\begin{sagecommandline}
sage: gcd(x^2 + 2*x + 1, x + 1)
\end{sagecommandline}
\end{document}​


then in a terminal run

pdflatex gcd && sage gcd.sagetex.sage && pdflatex gcd


and a pdf will be produced containing

sage : gcd(x^2 + 2*x + 1, x + 1)
x + 1


with additional line numbering. To remove the line numbering, add the line

\lstdefinestyle{SageInput}{style=DefaultSageInput,numbers=none}


somewhere before \begin{sagecommandline}.

• Nah,instead of getting a PDF with the desired output,I get one with ?? Instead of sage code. What should I do? – Shreya Apr 13 '20 at 16:56
• @Shreya what output do you get for sage --version, and have you installed SageTeX? See doc.sagemath.org/html/en/tutorial/sagetex.html – Samuel Lelièvre Apr 13 '20 at 21:46
• its version 8.8 and yes I have sagetex installed. – Shreya Apr 13 '20 at 23:58
• @Shreya what happens whey you run sage on the .sagetex.sage file? – Samuel Lelièvre Apr 14 '20 at 22:50