Using sagetex for large blocks of code

188 views
Skip to first unread message

javier

unread,
Oct 25, 2011, 11:10:02 AM10/25/11
to sage-devel
Hi all,

I am trying to add some Sage examples to my lecture notes for a course
in Commutative Algebra. In particular want to include an example on
how to define the power set ring in sage. I would like to list some
big chunks of sage code with nice colorization and all, so I was
trying to use the `sagecommandline` environment. While this works for
simple one-liners, I get some problems using it for classes. Here is
some minimal example that goes wrong:

\begin{sagecommandline}
class PowerSetRingElement(RingElement):
"""
Class for defining elements of a power set ring
"""
def __init__(self, Y, parent=None):
try:
YY = Set(Y)
if YY.issubset(parent._set):
self._subset = YY
self._parent = parent
RingElement.__init__(self, parent)
else:
raise TypeError, "\percent{}s must be a subset of
\percent{}s"(Y, parent._set)
except:
raise NotImplementedError

def _repr_(self):
return "\percent{}s"\percent{}self._subset

def _add_(self, other):
return
self._parent(self._subset.symmetric_difference(other._subset))

def _mul_(self, other):
return self._parent(self._subset.intersection(other._subset))
\end{sagecommandline}

Now here I face several problems. First of all, sagetex seems to raise
syntax errors whenever the code inside a sagecommandline environment
contains strings with triple quotes """

Now, if I remove the docstring, then sage runs just fine on the
sagetex file, but (after re-running latex) nothing shows up on the
final pdf.

If I try to include the "sage" words at the beginning, as if I typed
it in the command line

\begin{sagecommandline}
sage: class PowerSetRingElement(RingElement):
def __init__(self, Y, parent=None):
try:
YY = Set(Y)
if YY.issubset(parent._set):
self._subset = YY
self._parent = parent
RingElement.__init__(self, parent)
else:
raise TypeError, "%s must be a subset of %s"(Y,
parent._set)
except:
raise NotImplementedError
\end{sagecommandline}

then I get

**** Error in Sage code on line 312 of 3201-sage.tex! Traceback
follows.
Traceback (most recent call last):
File "3201-sage.sagetex.py", line 104, in <module>
""", globals(), locals(), True)
File "/Applications/sage/local/lib/python2.6/site-packages/
sagetex.py", line 203, in commandline
exec current_statement in globals, locals
File "<string>", line 1
class PowerSetRingElement(RingElement):
^
SyntaxError: unexpected EOF while parsing


Any ideas?

Cheers,
Javier

Andrey Novoseltsev

unread,
Oct 26, 2011, 1:06:58 AM10/26/11
to sage-devel
I think you should put "sage:" in front of all complete commands and
"..." in front of continuation lines. I was making multi-line cycles
this way. Triple quotes may conflict with the way how SageTeX produces
its files. Did you try triple single quotes? ( ' + ' + ' instead of "
+ " + ")

Andrey

Dan Drake

unread,
Oct 26, 2011, 1:48:04 AM10/26/11
to sage-...@googlegroups.com
On Tue, 25 Oct 2011 at 08:10AM -0700, javier wrote:
> I am trying to add some Sage examples to my lecture notes for a course
> in Commutative Algebra. In particular want to include an example on
> how to define the power set ring in sage. I would like to list some
> big chunks of sage code with nice colorization and all, so I was
> trying to use the `sagecommandline` environment. While this works for
> simple one-liners, I get some problems using it for classes. Here is
> some minimal example that goes wrong:
>
> \begin{sagecommandline}
[snip]

> \end{sagecommandline}
>
> Now here I face several problems. First of all, sagetex seems to raise
> syntax errors whenever the code inside a sagecommandline environment
> contains strings with triple quotes """

You can't use """ triple quotes because in the generated .sage file,
SageTeX uses """ to bundle up everything you put into the
sagecommandline environment. You can use ''' triple quotes with no
trouble.

By the way, why aren't you using the sageblock environment? That
typesets the output and allows you to use """ triple quotes. Nothing
will get written to the doctest file, and you don't get "sage:" prompts
prepended -- but who actually types in real class definitions at a
prompt?

> Now, if I remove the docstring, then sage runs just fine on the
> sagetex file, but (after re-running latex) nothing shows up on the
> final pdf.

This is somehow related to the way that sagecommandline is piecing
together the string it gets from LaTeX into chunks that it can hand to
Sage for processing. The class definition gets evaluated, but because
it's a compound statement, nothing is handed back to LaTeX to typeset.


> If I try to include the "sage" words at the beginning, as if I typed
> it in the command line
>
> \begin{sagecommandline}
> sage: class PowerSetRingElement(RingElement):

[snip]


> \end{sagecommandline}
>
> then I get
>

[snip]


> File "<string>", line 1
> class PowerSetRingElement(RingElement):
> ^
> SyntaxError: unexpected EOF while parsing

This is also related to the class definition -- it's a compound
statement, but only the first line gets handed to Python.

This stuff really should get sorted out, and I've been meaning to do it
for a while -- but for now, if sageblock isn't enough, the sageexample
environment seems to work better for what you want. Try something like
this:

\begin{sageexample}
sage: class PowerSetRingElement(RingElement):
... def __init__(self, Y, parent=None):
... blah
... blah
\end{sageexample}

That typesets the definition correctly.

Regards,

Dan

--
--- Dan Drake
----- http://mathsci.kaist.ac.kr/~drake
-------

signature.asc

javier

unread,
Oct 26, 2011, 5:03:25 AM10/26/11
to sage-devel
Hi Andrey and Dan,

thanks for the replies! I don't actually care for the "sage:" prompts,
just want to show the code.
sageblock typesets the text just fine, but id doesn't add
colorization.
Basically what I want is to add "syntax highlight" to the code
listing. I thought that worked out of the box with sagecommandline but
now I realize it is only the sage prompt that gets colorized, so I
will probably make my own environment based on minted for code
listing.

Cheers,
Javier
>  signature.asc
> < 1KViewDownload

Dan Drake

unread,
Oct 26, 2011, 8:21:36 AM10/26/11
to sage-...@googlegroups.com
On Wed, 26 Oct 2011 at 02:03AM -0700, javier wrote:
> Basically what I want is to add "syntax highlight" to the code
> listing. I thought that worked out of the box with sagecommandline but
> now I realize it is only the sage prompt that gets colorized, so I
> will probably make my own environment based on minted for code
> listing.

In that case, take a look at the lstlistings stuff in SageTeX for the
sagecommandline environment. There's some nice stuff there based on the
Python syntax highlighting. (Or just use the "listings" package and set
the syntax to Python.)

signature.asc

javier

unread,
Oct 26, 2011, 11:06:09 AM10/26/11
to sage-devel
Hi Dan,

I found a solution using listings indeed. I set up my own "sagecode"
environment by adding to my preamble the following

\usepackage{listings} % Used for code listing
\usepackage{textcomp} % Used for syntax highlighting.
\usepackage{setspace} % Used for changing linespace

% This gives syntax highlighting in the sagecode environment
\definecolor{gray}{gray}{0.3}
\definecolor{key}{rgb}{0,0.5,0}
\lstnewenvironment{sagecode}[1][]
{
\lstset
{
language=python,
basicstyle=\ttfamily\small\setstretch{0.8},
stringstyle=\color{red},
showstringspaces=false,
alsoletter={1234567890},
otherkeywords={\ , \}, \{},
keywordstyle=\color{blue},
emph={access,and,break,class,continue,def,del,elif ,else,%
except,exec,finally,for,from,global,if,import,in,is,%
lambda,not,or,pass,print,raise,return,try,while,cached_method},
emphstyle=\color{black}\bfseries,
emph={[2]True, False, None, self},
emphstyle=[2]\color{key},
emph={[3]from, import, as},
emphstyle=[3]\color{blue},
upquote=true,
morecomment=[s]{"""}{"""},
commentstyle=\color{gray}\slshape,
emph={[4]1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
emphstyle=[4]\color{blue},
literate=*{:}{{\textcolor{blue}:}}{1}%
{=}{{\textcolor{blue}=}}{1}%
{-}{{\textcolor{blue}-}}{1}%
{+}{{\textcolor{blue}+}}{1}%
{*}{{\textcolor{blue}*}}{1}%
{!}{{\textcolor{blue}!}}{1}%
{(}{{\textcolor{blue}(}}{1}%
{)}{{\textcolor{blue})}}{1}%
{[}{{\textcolor{blue}[}}{1}%
{]}{{\textcolor{blue}]}}{1}%
{<}{{\textcolor{blue}<}}{1}%
{>}{{\textcolor{blue}>}}{1}%
{@}{{\textcolor{blue}@}}{1},%
rulesepcolor=\color{blue},
% numbers=right, % For adding line numbers
% numberstyle=\footnotesize, % Line numbers size
% stepnumber=1, % Line numbers step
% breaklines=true,
#1
}
}{}

Then I use \begin{sagecode} ...whatever... \end{sagecode} and works
beautifully, apart from one funny quirk. If I try to add line breaking
to the environment (by uncommenting the line "breakline=true") then
the closing parenthesis ")" stop getting colorized in blue (?)
I have no idea why this happens, but for now this suits my needs (with
the added advantage of not having to install pygments in a place where
my latex can find it).

If you think than any of this code or any variation would make an
useful addition to sagetex, feel free to rip it off!

Cheers,
Javier
>  signature.asc
> < 1KViewDownload

leif

unread,
Oct 26, 2011, 1:29:28 PM10/26/11
to sage-devel
On 26 Okt., 17:06, javier <vengor...@gmail.com> wrote:
>                 emph={access,and,break,class,continue,def,del,elif ,else,%
>                 except,exec,finally,for,from,global,if,import,in,is,%
>                 lambda,not,or,pass,print,raise,return,try,while,cached_method},

OTOH + with, local, yield

(Perhaps also 'eval' since you have 'exec' there.)


-leif

Andrey Novoseltsev

unread,
Oct 27, 2011, 10:21:43 AM10/27/11
to sage-devel
Hi Javier,

One of the main points of sagecommandline is to create examples with
*automatic* output, similar to doctests in modules. This is also the
reason why stuff without "sage:" or "..." in the beginning does not
show up: it is interpreted as output that should NOT be inserted into
the final result, but rather compared with the output of the above
code if you run doctests. It does use custom-tuned lstlistings inside
and it is not made extremely colorful on purpose, as I understand it.
This can be changed quite easily (although you need to know
lstlistings parameters as in your code). For example, the file here
http://hdl.handle.net/10048/2142 (don't mean to be unmodest, but
that's the example I know best ;-)) uses sagecommandline intensively
and contains in the preambule

% SageTeX tuning
\usepackage[dvipsnames]{xcolor}
\usepackage[scaled]{luximono}
\usepackage{sagetex}
\lstdefinestyle{SageTEXAdjustment}{numbers=none, xleftmargin=1ex,
xrightmargin=1ex, framesep=1ex, frame=rl, breakatwhitespace=True,
basicstyle={\ttfamily\small}, backgroundcolor=\color{Goldenrod!25},
framerule=0pt}
\lstdefinestyle{SageInput}{style=DefaultSageInput,
style=SageTEXAdjustment}
\lstdefinestyle{SageOutput}{style=DefaultSageOutput,
style=SageTEXAdjustment, basicstyle={\ttfamily\small\bfseries}}
\lstset{style=SageInput}
\newcommand{\sagecommand}[1]{\lstinline!#1!}

Code coloring is still quite conservative, but for example
sagecommandline allows you to make input plain and output bold - I
don't think it is easy to achieve with lstlistings directly
(sagecommandline sets up different environments for each line - who
would do that by hand?!). Of course, it only matters if you actually
have output in your examples.

Best regards,
Andrey
Reply all
Reply to author
Forward
0 new messages