SageTeX / sagetexpackage.dtx

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
% \iffalse meta-comment
%
% Copyright (C) 2008 by Dan Drake <ddrake@member.ams.org>
% -------------------------------------------------------
% 
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 2 of the License, or (at
% your option) any later version.
% 
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%         
% You should have received a copy of the GNU General Public License
% along with this program.  If not, see <http://www.gnu.org/licenses/>
% 
% \fi
%
% \iffalse
%<*driver>
\ProvidesFile{sagetexpackage.dtx}
%</driver>
%<latex>\NeedsTeXFormat{LaTeX2e}
%<latex>\ProvidesPackage{sagetex}
%<*latex>
    [2008/03/07 v1.2 embedding Sage into LaTeX documents]
%</latex>
%
%<*driver>
\documentclass{ltxdoc}
\usepackage{sagetex}
\usepackage{hyperref}
\usepackage{xspace}
\EnableCrossrefs         
\CodelineIndex
\RecordChanges
\begin{document}
  \DocInput{sagetexpackage.dtx}
  \PrintChanges
  \PrintIndex
\end{document}
%</driver>
% \fi
%
% \CheckSum{0}
%
% \CharacterTable
%  {Upper-case    \A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z
%   Lower-case    \a\b\c\d\e\f\g\h\i\j\k\l\m\n\o\p\q\r\s\t\u\v\w\x\y\z
%   Digits        \0\1\2\3\4\5\6\7\8\9
%   Exclamation   \!     Double quote  \"     Hash (number) \#
%   Dollar        \$     Percent       \%     Ampersand     \&
%   Acute accent  \'     Left paren    \(     Right paren   \)
%   Asterisk      \*     Plus          \+     Comma         \,
%   Minus         \-     Point         \.     Solidus       \/
%   Colon         \:     Semicolon     \;     Less than     \<
%   Equals        \=     Greater than  \>     Question mark \?
%   Commercial at \@     Left bracket  \[     Backslash     \\
%   Right bracket \]     Circumflex    \^     Underscore    \_
%   Grave accent  \`     Left brace    \{     Vertical bar  \|
%   Right brace   \}     Tilde         \~}
%
%
% \changes{v1.0}{2008/03/03}{Initial version}
% \changes{v1.1}{2008/03/05}{Wrapped user-provided Sage code in
% try/except clauses; plotting now has optional format argument.}
% \changes{v1.2}{2008/03/07}{Imagemagick option; better documentation}
%
% \GetFileInfo{sagetexpackage.dtx}
%
% \DoNotIndex{\newcommand,\newenvironment,\the}
% 
% \newcommand{\ST}{\textsf{sagetex}\xspace}
% \iffalse
% so I don't have to put \ or {} after \LaTeX:
% \fi
% \newcommand{\LTX}{\LaTeX\xspace}
%
% \iffalse
% For some reason, getting a blackslash in a typewriter font to print
% inside an fbox is really hard. This code works; it's copied out of
% Scott Pakin's dtxtut.tex. Verbatim stuff doesn't work because it's
% fragile.
% \fi
% {\catcode`\|=0 \catcode`\\=12
% |gdef|bslash{\}}
%
% \title{The \ST{} package\thanks{This document
%   corresponds to \textsf{sagetex}~\fileversion, dated \filedate.}}
% \author{Dan Drake (\texttt{ddrake@member.ams.org}) and others}
%
% \maketitle
%
% \section{Introduction}
%
% Why should the Haskell folks have all the fun? 
%
% \href{http://www.haskell.org/haskellwiki/Literate_programming}{Literate
% Haskell} is a popular way to mix Haskell source code and \LTX
% documents. (Well, actually any kind of text or document, but here
% we're concerned only with \LTX.) You can even embed Haskell code in
% your document that writes part of your document for you. 
%
% The \ST{} package allows you to do (roughly) the same with Sage and
% \LTX. (If you know how to write literate Haskell: the |\eval|
% command corresponds to |\sage|, and the |code| environment
% to the |sageblock| environment.) As a simple example, imagine in
% your document you are writing about how to count license plates with
% three letters and three digits. With this package, you can write
% something like this:
% \begin{quote}
%  \texttt{There are \$26\$ choices for each letter, and \$10\$ choices
%  for each digit, for a total of } \verb+$26^3*10^3 = \sage{26^3*10^3}$+
%  \texttt{license plates.}
% \end{quote}
% and it will produce
% \begin{quote}
%   There are $26$ choices for each letter, and $10$ choices for each
%   digit, for a total of $\sage{26^3 * 10^3}$ license plates.
% \end{quote}
% The great thing is, you don't have to do the multiplication. Sage does
% it for you. This process mirrors one of the great aspects of
% \LTX: when writing a \LTX document, you can concentrate on the
% logical structure of the document and trust \LTX and its army of
% packages to deal with the presentation and typesetting. Similarly,
% with \ST, you can concentrate on the mathematical
% structure (``I need the product of $26^3$ and $10^3$'') and let Sage
% deal with the base-$10$ presentation of the number.
%
% A less trivial, and perhaps more useful example is plotting. You can
% include a plot of the sine curve without manually producing a plot,
% saving an eps or pdf file, and doing the \verb+\includegraphics+
% business with the correct filename yourself. If you write this:
% \begin{quote}
% \texttt{Here is a lovely graph of the sine curve:}
%
% \verb+\sageplot{plot(sin(x), x, 0, 2*pi)}+
% \end{quote}
% in your \LTX file, it produces
% \begin{quote}
% Here is a lovely graph of the sine curve:
%
% \sageplot{plot(sin(x), x, 0, 2*pi)}
% \end{quote}
% Again, you need only worry about the logical/mathematical structure of
% your document (``I need a plot of the sine curve over the interval
% $[0, 2\pi]$ here''), while \ST{} takes care of the gritty details of
% producing the file and sourcing it into your document.
%
% \paragraph{But \texttt{\bslash sageplot} isn't magic} I just tried to
% convince you that \ST{} makes putting nice graphics into your document
% very easy; let me turn around and warn you that using graphics
% \emph{well} is not easy, and no \LTX package or Python script will
% ever make it easy. What \ST{} does is make it easy to \emph{use Sage}
% to create graphics; it doesn't magically make your graphics good,
% appropriate, or useful. (For instance, look at the sine plot above---I
% would say that a truly lovely plot of the sine curve would not mark
% integer points on the $x$-axis, but rather $\pi/2$, $\pi$, $3\pi/2$,
% and $2\pi$.)
%
% Till Tantau has some good commentary on the use of graphics in
% \href{http://www.ctan.org/tex-archive/graphics/pgf/}{section 6 of the
% \textsf{pgf} manual}. You should always give careful thought and
% attention to creating graphics for your document; I have in mind that
% a good workflow for using \ST{} for plotting is something like this:
%
% \begin{enumerate}
%   \item Figure out what sort of graphic you need to communicate your
%   ideas or information.
%   \item Fiddle around in Sage until you get a graphics object and set
%   of options that produce the graphic you need.
%   \item Copy those commands and options into \ST{} commands in your
%   \LTX document.
% \end{enumerate}
%
% The \ST{} package's plotting capabilities don't help you find those
% Sage commands to make your lovely plot, but they do eliminate the need
% to muck around with saving the result to a file, remembering the
% filename, including it into your document, and so on. In the next
% section, we will see what what we can do with \ST.
%
% \section{Usage}
% 
% Let's begin with a rough description of how \ST{} works.
% When you use macros from this package and run \LTX on your file,
% along with the usual zoo of auxiliary files, a |.sage| file is
% written. This is a Sage source file that uses the Python module from
% this package and when you run Sage on that file, it will produce a
% |.sout| file. That file contains \LTX code which, when you run
% \LTX on your source file again, will pull in all the results of
% Sage's computation.
%
% All you really need to know is that to typeset your document, you need
% to run \LTX, then run Sage, then run \LTX again. 
%
% Also keep in mind that everything you send to Sage is done within one
% Sage session. This means you can define variables and reuse them
% throughout your \LTX document; if you tell Sage that |foo| is
% $12$, then anytime afterwards you can use |foo| in your Sage code and
% Sage will remember that it's $12$---just like in a regular Sage
% session.
%
% Now that you know that, let's describe what macros \ST{} provides and
% how to use them. If you are the sort of person who can't be bothered
% to read documentation until something goes wrong, you can also just
% look through the \texttt{example.tex} file included with this package.
%
% \subsection{Inline Sage}
%
% \DescribeMacro{\sage}
% \fbox{\texttt{\bslash sage}\marg{Sage code}}
%
% \noindent takes whatever Sage code you give it, runs Sage's |latex|
% function on it, and puts the result into your document. 
%
% For example, if you do |\sage{matrix([[1, 2], [3,4]])^2}|, then that
% macro will get replaced by
% \begin{quote}
% |\left(\begin{array}{rr}|\\
% |7 & 10 \\|\\
% |15 & 22|\\
% |\end{array}\right)|
% \end{quote}
% in your document---that \LTX code is exactly exactly what you get
% from doing
% \begin{quote}
% |latex(matrix([[1, 2], [3,4]])^2)|
% \end{quote}
% in Sage.
%
% Note that since \LTX will do macro expansion on whatever you give
% to \verb|\sage|, you can mix \LTX variables and Sage variables! If
% you have defined the Sage variable |foo| to be $12$ (using, say, the
% |sageblock| environment), then you can do something like this:
% \begin{quote}
% |The prime factorization of the current page plus foo is|\\
% |$\sage{factor(foo + \thepage)}$|.
% \end{quote}
% Here, I'll do just that right now: the prime factorization of the
% current page plus $12$ is $\sage{factor(\thepage + 12)}$.\\
%
% \subsection{Graphics and plotting}
%
% \noindent \DescribeMacro{\sageplot}
% \fbox{\texttt{\bslash sageplot}\oarg{ltx opts}\oarg{fmt}\{\meta{graphics
% obj}, \meta{keyword args}\}}
%
% \noindent plots the given Sage graphics object and runs an
% |\includegraphics| command to put it into your document. It does not
% have to actually be a plot of a function; it can be any Sage graphics
% object. The options work as follows:
%
% \begin{table}[h]
%   \centering
%   \begin{tabular}{l p{8cm}}
%   Option & Description \\
%   \hline
%   \meta{ltx options} & Any text here is passed directly into the
%   optional arguments (between the square brackets) of an
%   |\includegraphics| command. If not specified,
%   ``|width=.75\textwidth|'' will be used.\\
%   \meta{fmt} & You can optionally specify a file extension here; Sage
%   will then try to save the graphics object to a file with extension
%   \emph{fmt}. If not specified, \ST\ will save to EPS and PDF files.\\
%   \meta{graphics obj} & A Sage object on which you can call |.save()|
%   with a graphics filename.\\
%   \meta{keyword args} & Any keyword arguments you put here will
%   all be put into the call to |.save()|.
%   \end{tabular}
%   \end{table}
% This setup allows you to control both the Sage side of things, and the
% \LTX side. For instance, the command
% \begin{quote}
% |\sageplot[angle=30, width=5cm]{plot(sin(x), 0, pi), axes=False,|\\
% |chocolate=True}|
% \end{quote}
% will run the following command in Sage:
% \begin{quote}
% \texttt{sage: plot(sin(x), 0, pi).save(filename=autogen, axes=False,\\
% chocolate=True)}
% \end{quote}
% Then, in your \LTX file, the following command will be issued
% automatically:
% \begin{quote}
% |\includegraphics[angle=30, width=5cm]{autogen}|
% \end{quote}
% You can specify a file format if you like. This must be the
% \emph{second} optional argument, so you must use empty brackets if
% you're not passing anything to \verb|\includegraphics|:
% \begin{quote}
% |\sageplot[][png]{plot(sin(x), x, 0, pi)}|
% \end{quote}
% The filename is automatically generated, and unless you specify a
% format, both EPS and PDF files will be generated. This allows you to
% freely switch between using, say, a DVI viewer (many of which have
% support for automatic reloading, source specials and make the writing
% process easier) and creating PDFs for posting on the web or emailing
% to colleagues.
%
% If you ask for, say, a PNG file, keep in mind that ordinary
% |latex| and DVI files have no support for DVI files; \ST{} detects
% this and will warn you that it cannot find a suitable file if using
% |latex|; if you use |pdflatex|, there will be no problems because PDF
% files can include PNG graphics.
%
% When \ST{} cannot find a graphics file, it inserts this into your
% file:
%
% \begin{center}
%   \framebox[2cm]{\rule[-1cm]{0cm}{2cm}\textbf{??}}
% \end{center}
% 
% \noindent That's supposed to resemble the traditional ``\textbf{??}''
% that \LTX uses to indicate missing references, and also the
% image-not-found graphics used by web browsers.
%
% You needn't worry about the filenames; they are automatically
% generated and will be put into the directory
% \texttt{sage-plots-for-filename.tex}. You can safely delete that
% directory anytime; if \ST\ can't find the files, it will warn you to
% run Sage to regenerate them.\\
%
% \noindent\fbox{\parbox{\textwidth}{\textbf{WARNING!} When you run Sage
% on your |.sage| file, all files in the
% \texttt{sage-plots-for-filename.tex} directory \emph{will be deleted!}
% Do not put any files into that directory that you do not want to get
% automatically deleted.}}
%
% \subsubsection{3D plotting}
%
% Right now there is, to put it nicely, a bit of tension between the
% sort of graphics formats supported by |latex| and
% |pdflatex|\footnote{We use a typewriter font here to indicate the
% binaries which produce DVI and PDF files, respectively, as opposed to
% ``\LTX'' which refers to the entire typesetting system.}, and the
% graphics formats supported by Sage's 3D plotting systems. \LTX is
% happiest, and produces the best output, with EPS and PDF files, which
% are vector formats. Tachyon, Sage's 3D plotting system, produces
% bitmap formats like BMP and PNG.
%
% Because of this, when producing 3D plots with \verb|\sageplot|,
% \emph{you must specify a file format}. The PNG format is compressed
% and lossless and is by far the best choice, so use that whenever
% possible. If you do not specify a file format, or specify one that
% Tachyon does not understand, it will produce files in the Targa format
% with an incorrect extension and \LTX (both \texttt{latex} and
% \texttt{pdflatex}) will be profoundly confused. Don't do that.
% 
% Since \texttt{latex} does not support PNGs, when using 3D plotting,
% \ST will \emph{always} issue a warning about missing graphics if you
% use \texttt{latex}, even though the plotting worked fine and the PNG
% file exists. (Running \texttt{pdflatex} on the same file will work,
% since PDF files can include PNG files.) 
%
% \paragraph{The imagemagick option} As a response to the above issue,
% the \ST package has one option: \texttt{imagemagick}. If you specify
% this option in the preamble of your document with the usual
% ``\verb|\usepackage[imagemagick]{sagetex}|'', then when you are
% compiling your document using \texttt{latex}, any \verb|\sageplot|
% command which requests a non-default format will cause the \ST Python
% script to convert the resulting file to EPS using the Imagemagick
% \texttt{convert} utility. It does this by executing ``\texttt{convert
% filename.EXT filename.eps}'' in a subshell. It doesn't add any
% options, check to see if the \texttt{convert} exists or belongs to
% Imagemagick---it just runs the command.
%
% The resulting EPS files are not very high quality, but they will work.
% This option is not intended to produce good graphics, but to allow you
% to use \texttt{latex} and DVI files while writing your document.
%
% \paragraph{But that's not good enough!} The \verb|\sageplot| command
% tries to be both flexible and easy to use, but if you are just not
% happy with it, you can always do things manually: inside a
% \texttt{sagesilent} environment (see the next section) you could do
% \begin{quote}
%   \texttt{your special commands}\\
%   \texttt{x = your graphics object}\\
%   \texttt{x.save(filename=myspecialfile.ext, options, etc)}
% \end{quote}
% and then, in your source file, do your own \verb|\includegraphics|
% command. The \ST package gives you full access to Sage and Python and
% doesn't turn off anything in \LTX, so you can always do things
% manually.
%
% \subsection{Verbatim-like environments}
%
% The \ST\ package provides several environments for typesetting and
% executing Sage code.\\
%
% \DescribeEnv{sageblock} Any text between |\begin{sageblock}| and
% |\end{sageblock}| will be typset into your file, and also written into
% the |.sage| file for execution. This means you can do something like
% this:
% \begin{quote}
% |\begin{sageblock}|\\
% |   var('x')|\\
% |   f = sin(x) - 1|\\
% |   g = log(x)|\\
% |   h = diff(f(x) * g(x), x)|\\
% |\end{sageblock}|
% \end{quote}
% and then anytime later write in your source file
% \begin{quote}
%   \texttt{We have \$h(2) = }|\sage{h(2)}|\texttt{\$, where \$h\$ is
%   the derivative of the product of \$f\$ and \$g\$.}
% \end{quote}
% and the |\sage| call will get correctly replaced by $\sage{
% diff((sin(x) - 1)*log(x), x)(1)}$. You can use any Sage or Python
% commands inside a |sageblock|; all the commands get sent directly to
% Sage.
%
% \iffalse meta-comment
%   Sadly, we can't use sageblock or similar environments in this file!
%   If you prefix the lines inside the environment with percent signs,
%   then those percent signs get written to your .sage file. If you
%   *don't* prefix the lines with percent signs, those lines get written
%   into the .sty or .py file. It's just too tricky to get docstrip and
%   the verbatim stuff to play nicely together. I'd have to redefine how
%   those environments work, and get them to strip off initial percents. 
% \fi
% 
% \DescribeEnv{sagesilent} This environment is like |sageblock|, but it
% does not typeset any of the code; it just writes it to the |.sage|
% file. This is useful if you have to do some setup in Sage that is not
% interesting or relevant to the document you are writing.
%
% \DescribeEnv{sageverbatim} This environment is the opposite of the one
% above: whatever you type will be typeset, but not written into the
% |.sage| file. This allows you to typeset psuedocode, code that will
% fail, or take too much time to execute, or whatever.
%
% \DescribeEnv{comment} Logically, we now need an environment that
% neither typesets nor executes your Sage code\ldots but the |verbatim|
% package, which is always loaded when using \ST, provides such an
% environment: |comment|. Another way to do this is to put stuff between
% |\iffalse| and |\fi|.\\
%
% \DescribeMacro{\sagetexindent} There is one final bit to our
% verbatim-like environments: the indentation. The \ST\ package defines a
% length |\sagetexindent|, which controls how much the Sage code is
% indented when typeset. You can change this length however you like
% with |\setlength|: do |\setlength{\sagetexindent}{6ex}| or whatever.
% 
% \section{Other notes}
%
% Here are some other notes on using \ST.
%
% \paragraph{Using Beamer} The \textsc{beamer} package does not play
% nicely with verbatim-like environments. To use code block environments
% in a \textsc{beamer} presentation, do:
% \begin{quote}
%  |\begin{frame}[fragile]|\\
%  |\begin{sageblock}|\\
%  |# sage stuff|\\
%  |# more stuff \end{sageblock}|\\
%  |\end{frame}|\\
% \end{quote}
% For some reason, \textsc{beamer} inserts an extra line break at the
% end of the environment; if you put the |\end{sageblock}| on the same
% line as the last line of your code, it works properly.
%
% Thanks to Franco Saliola for reporting this.
% 
%
% \StopEventually{}
%
% \section{Implementation}
%
% There are two pieces to this package: a \LTX style file, and a
% Python module. They are mutually interdependent, so it makes sense to
% document them both here.
%
% \subsection{The style file}
%
% \iffalse
% tell docstrip to put code into the .sty file
%<*latex>
% \fi
%
% Let's begin by loading some packages. The key bits of |sageblock| and
% friends are stol---um, adapted from the |verbatim| package manual.
%    \begin{macrocode}
\RequirePackage{verbatim}
%    \end{macrocode}
% Unsurprisingly, the |\sageplot| command works poorly without graphics
% support.
%    \begin{macrocode}
\RequirePackage{graphicx}
%    \end{macrocode}
% The |makecmds| package gives us a |\provideenvironment| which we need,
% and we use |ifpdf| and |ifthen| in |\sageplot| so we know what kind of
% files to look for.
%    \begin{macrocode}
\RequirePackage{makecmds}
\RequirePackage{ifpdf}
\RequirePackage{ifthen}
%    \end{macrocode}
% 
% Next set up the counters and the default indent.
%    \begin{macrocode}
\newcounter{@sage}
\newcounter{@sageplot}
\setcounter{@sage}{0}
\setcounter{@sageplot}{0}
\newlength{\sagetexindent}
\setlength{\sagetexindent}{5ex}
%    \end{macrocode}
%
% \begin{macro}{\@epsmagick}
% By default, we don't use ImageMagick to create EPS files:
%    \begin{macrocode}
\newcommand{\@epsmagick}{False}
%    \end{macrocode}
% That macro gets put into a Python function call, so it works to have
% it be one of the strings ``|True|'' or ``|False|''.
% \end{macro}
% 
% Declare the |imagemagick| option and process it:
%    \begin{macrocode}
\DeclareOption{imagemagick}{\renewcommand{\@epsmagick}{True}}
\ProcessOptions\relax
%    \end{macrocode}
% The |\relax| is a little incantation suggested by the ``\LaTeXe{} for
% class and package writers'' manual, section 4.7.
%
% It's time to deal with files. Open the |.sage| file:
%    \begin{macrocode}
\newwrite\@sagefile
\immediate\openout\@sagefile=\jobname.sage
%    \end{macrocode}
% We will write a lot of stuff to that file, so make a convenient
% abbreviation, then use it to put the initial commands into the |.sage|
% file.
%    \begin{macrocode}
\newcommand{\@wsf}[1]{\immediate\write\@sagefile{#1}}
\@wsf{import sagetex}
\@wsf{sagetex.openout('\jobname')}
%    \end{macrocode}
% Pull in the |.sout| file if it exists, or do nothing if it doesn't. I
% suppose we could do this inside an |AtBeginDocument| but I don't see
% any particular reason to do that. It will work whenever we load it.
%    \begin{macrocode}
\InputIfFileExists{\jobname.sout}{}{}
%    \end{macrocode}
%
% Now let's define the cool stuff.
%
% \begin{macro}{\sage}
% This macro combines |\ref|, |\label|, and Sage all at once. First, we
% use Sage to get a \LTX representation of whatever you give this
% function. The Sage script writes a |\newlabel| line into the |.sout|
% file, and we read the output using the |\ref| command. Usually, |\ref|
% pulls in a section or theorem number, but it will pull in arbitrary
% text just as well.
%
% The first thing it does it write its argument into the |.sage| file,
% along with a counter so we can produce a unique label, and the line
% number in the input file so we can give helpful error messages to the
% user. We wrap a try/except around the function call so that we can
% provide a more helpful error message in case something goes wrong. (In
% particular, we can tell the user which line of the |.tex| file
% contains the offending code.)
%    \begin{macrocode}
\newcommand{\sage}[1]{%
\@wsf{try:}%
\@wsf{  sagetex.inline(\the@sage, \the\inputlineno, #1)}%
\@wsf{except:}%
\@wsf{  sagetex.goboom(\the\inputlineno)}%
%    \end{macrocode}
% Our use of |\newlabel| and |\ref| seems awfully clever until you load
% the |hyperref| package, which gleefully tries to hyperlink the hell
% out of everything. This is great until it hits one of our special
% |\newlabel|s and gets deeply confused. Fortunately the |hyperref|
% folks are willing to accomodate people like us, and give us a
% |NoHyper| environment.
%    \begin{macrocode}
\begin{NoHyper}\ref{@sagelabel\the@sage}\end{NoHyper}%
%    \end{macrocode}
% Now check to see if the label has already been defined. (The
% deep internal implementation of labels in \LTX involves defining a
% function ``|r@labelname|''.) If it hasn't, we set a flag so that we
% can tell the user to run Sage on the |.sage| file at the end of the
% run. Finally, step the counter.
%    \begin{macrocode}
\@ifundefined{r@@sagelabel\the@sage}{\gdef\@rerunsage{x}}{}%
\stepcounter{@sage}}
%    \end{macrocode}
% \end{macro}
% The user might load the |hyperref| package after this one (indeed, the
% |hyperref| documentation insists that it be loaded last) or not at
% all---so when we hit the beginning of the document, provide a dummy
% |NoHyper| environment if one hasn't been defined by the |hyperref|
% package.
%    \begin{macrocode}
\AtBeginDocument{\provideenvironment{NoHyper}{}{}}
%    \end{macrocode}
%
% \begin{macro}{\@plotdir}
% A little abbreviation for the plot directory. We don't use
% |\graphicspath| because it's
% \href{http://www.tex.ac.uk/cgi-bin/texfaq2html?label=graphicspath}{
% apparently slow}---also, since we know right where our plots are
% going, no need to have \LTX looking for them.
%    \begin{macrocode}
\newcommand{\@plotdir}{sage-plots-for-\jobname.tex}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\sageplot}
% This function is similar to |\sage|. The neat thing that we take
% advantage of is that commas aren't special for arguments to \LTX
% commands, so it's easy to capture a bunch of keyword arguments that
% get passed right into a Python function.
%
% This macro has two optional arguments, which can't be defined using
% \LTX's |\newcommand|; we use Scott Pakin's brilliant
% \href{http://tug.ctan.org/tex-archive/support/newcommand/}{\texttt{newcommand}}
% package to create this macro; the options I fed to his script were
% similar to this:
%\begin{quote}
% |MACRO sageplot OPT[#1={width}] OPT[#2={notprovided}] #3|
%\end{quote}
% Observe that we are using a Python script to write \LTX code which
% writes Python code which writes \LTX code. Crazy!
% 
% Here's the ``shell'' command which does whatever magic we need to get
% two optional arguments.
%    \begin{macrocode}
\newcommand{\sageplot}[1][width=.75\textwidth]{%
  \@ifnextchar[{\sageplot@ii[#1]}{\sageplot@ii[#1][notprovided]}%]
}
%    \end{macrocode}
% That percent sign followed by a square bracket seems necessary; I have
% no idea why.
%
% The first optional argument |#1| will get shoved right into the
% optional argument for |\includegraphics|, so the user has easy control
% over both the Sage and \LTX aspects of the plotting. We define a
% default size of $3/4$ the textwidth, which seems reasonable. The
% second optional argument |#2| is the file format and allows us to tell
% what files to look for. It defaults to ``notprovided'', which tells
% the Python module to create EPS and PDF files. Everything in |#3| gets
% put into the Python function call, so the user can put in keyword
% arguments there which get interpreted correctly by Python.
%
% Let's see the real code here. We write a couple lines to the
% |.sage| file, including a counter, input line number, and all of the
% mandatory argument; all this is wrapped in another try/except. 
%    \begin{macrocode}
\def\sageplot@ii[#1][#2]#3{%
\@wsf{try:}%
\@wsf{  sagetex.initplot('\jobname')}%
\@wsf{  sagetex.sageplot(\the@sageplot, \the\inputlineno, #3,
    format='#2', epsmagick=\@epsmagick)}%
\@wsf{except:}%
\@wsf{  sagetex.goboom(\the\inputlineno)}%
%    \end{macrocode}
% Now we include the appropriate graphics file. We use our own function
% for this; it checks to see if the file exists before running the
% appropriate |\includegraphics| command, and issues some warnings it
% the file doesn't exist. If we are creating a PDF, we check to see if
% the user asked for a different format, and use that if necessary.
%    \begin{macrocode}
\ifpdf
  \ifthenelse{\equal{#2}{notprovided}}%
    {\@sagetexincludegraphics{#1}{pdf}}%
    {\@sagetexincludegraphics{#1}{#2}}%
%    \end{macrocode}
% Otherwise, we are creating a DVI file, which only supports EPS. If the
% user provided a format anyway, don't include the file (since it won't
% work) and warn the user about this. (Unless the file doesn't exist, in
% which case we do the same thing that |\@sagetexincludegraphics| does.)
%    \begin{macrocode}
\else
  \ifthenelse{\equal{#2}{notprovided}}%
    {\@sagetexincludegraphics{#1}{eps}}%
%    \end{macrocode}
% If a format is provided, we check to see if we're using the
% imagemagick option. If so, try to include an EPS file anyway.
%    \begin{macrocode}
    {\ifthenelse{\equal{\@epsmagick}{True}}
      {\@sagetexincludegraphics{#1}{eps}}%
%    \end{macrocode}
% If we're not using the imagemagick option, we're going to issue some
% sort of warning, depending on whether the file exists yet or not.
%    \begin{macrocode}
      {\IfFileExists{\@plotdir/plot-\the@sageplot.#2}%
        {\framebox[2cm]{\rule[-1cm]{0cm}{2cm}\textbf{??}}%
         \PackageWarning{sagetex}{Graphics file
         \@plotdir/plot-\the@sageplot.#2\space on page \thepage\space cannot
         be used with DVI output. Use pdflatex or create an EPS file. Plot
         command is}}%
        {\framebox[2cm]{\rule[-1cm]{0cm}{2cm}\textbf{??}}%
         \PackageWarning{sagetex}{Graphics file
         \@plotdir/plot-\the@sageplot.#2\space on page \thepage\space does
         not exist}%
         \gdef\@rerunsage{x}}}}%
\fi
%    \end{macrocode}
% Finally, step the counter and we're done.
%    \begin{macrocode}
\stepcounter{@sageplot}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@sagetexincludegraphics}
% This command includes the requested graphics file (|#2| is the
% extension) with the requested options (|#1|) if the file exists. Note
% that it just needs to know the extension, since we use a counter for
% the filename.
%    \begin{macrocode}
\newcommand{\@sagetexincludegraphics}[2]{%
  \IfFileExists{\@plotdir/plot-\the@sageplot.#2}%
    {\includegraphics[#1]{\@plotdir/plot-\the@sageplot.#2}}%
%    \end{macrocode}
% If the file doesn't exist, we insert a little box to indicate it
% wasn't found, issue a warning that we didn't find a graphics file,
% then set a flag that, at the end of the run, tells the user to run
% Sage again.
%    \begin{macrocode}
    {\framebox[2cm]{\rule[-1cm]{0cm}{2cm}\textbf{??}}%
     \PackageWarning{sagetex}{Graphics file
     \@plotdir/plot-\the@sageplot.#2\space on page \thepage\space does not
     exist}%
     \gdef\@rerunsage{x}}}
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{\@beginsagefileblock}
% This is an internal-use abbreviation that sets things up when we start
% writing a chunk of Sage code to the |.sage| file. It begins with some
% \TeX{} magic that fixes spacing, then puts the start of a try/except
% block in the |.sage| file---this not only allows the user to indent
% code without Sage/Python complaining about indentation, but lets us
% tell the user where things went wrong. The last bit is some magic from
% the |verbatim| package manual that makes \LTX respect line breaks.
%    \begin{macrocode}
\newcommand{\@beginsagefileblock}{%
  \@bsphack%
  \@wsf{sagetex.blockbegin(\the\inputlineno)}%
  \@wsf{try:}%
  \let\do\@makeother\dospecials\catcode`\^^M\active}
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{\@endsagefileblock}
% The companion to |\@beginsagefileblock|. 
%    \begin{macrocode}
\newcommand{\@endsagefileblock}{%
\@wsf{except:}%
\@wsf{  sagetex.goboom(\the\inputlineno)}%
\@wsf{sagetex.blockend()}}
%    \end{macrocode}
% \end{macro}
%
% Now let's define the ``verbatim-like'' environments. There are four
% possibilities, corresponding to two independent choices of
% typesetting the code or not, and writing to the |.sage| file or not.
%
% \begin{environment}{sageblock}
% This environment does both: it typesets your code and puts it into the
% |.sage| file for execution by Sage.
%    \begin{macrocode}
\newenvironment{sageblock}{\@beginsagefileblock%
%    \end{macrocode}
% The space between |\@wsf{| and |\the| is crucial! It, along with the
% ``|try:|'', is what allows the user to indent code if they like.
% This line sends stuff to the |.sage| file.
%    \begin{macrocode}
\def\verbatim@processline{\@wsf{ \the\verbatim@line}%
%    \end{macrocode}
% Next, we typeset your code and start the verbatim environment.
%    \begin{macrocode}
\hspace{\sagetexindent}\the\verbatim@line\par}%
\verbatim}%
%    \end{macrocode}
% At the end of the environment, we put a chunk into the |.sage| file
% and stop the verbatim environment.
%    \begin{macrocode}
{\@endsagefileblock\endverbatim}
%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{sagesilent}
% This is from the |verbatim| package manual. It's just like the above,
% except we don't typeset anything.
%    \begin{macrocode}
\newenvironment{sagesilent}{\@beginsagefileblock%
\def\verbatim@processline{\@wsf{ \the\verbatim@line}}%
\verbatim@start}%
{\@endsagefileblock\@esphack}
%    \end{macrocode}
% \end{environment}
%
% \begin{environment}{sageverbatim}
% The opposite of |sagesilent|. This is exactly the same as the verbatim
% environment, except that we include some indentation to be consistent
% with other typeset Sage code.
%    \begin{macrocode}
\newenvironment{sageverbatim}{%
\def\verbatim@processline{\hspace{\sagetexindent}\the\verbatim@line\par}%
\verbatim}%
{\endverbatim}
%    \end{macrocode}
% \end{environment}
%
% Logically, we now need an environment which neither typesets
% \emph{nor} writes code to the |.sage| file. The verbatim package's
% |comment| environment does that.\\
%
% Now we deal with some end-of-file cleanup.
%
% We tell the Sage script to write some information to the |.sout| file,
% then check to see if |@rerunsage| ever got defined. If not, all the
% inline formulas and plots worked, so do nothing.
%    \begin{macrocode}
\AtEndDocument{\@wsf{sagetex.endofdocument()}%
\@ifundefined{@rerunsage}{}%
%    \end{macrocode}
% Otherwise, we issue a warning to tell the user to run Sage on the
% |.sage| file. Part of the reason we do this is that, by using |\ref|
% to pull in the inlines, \LTX will complain about undefined
% references if you haven't run the Sage script---and for many \LTX
% users, myself included, the warning ``there were undefined
% references'' is a signal to run \LTX again. But to fix these
% particular undefined references, you need to run \emph{Sage}. We also
% suppressed file-not-found errors for graphics files, and need to tell
% the user what to do about that.
%
% At any rate, we tell the user to run Sage if it's necessary.
%    \begin{macrocode}
{\PackageWarningNoLine{sagetex}{There were undefined Sage formulas
and/or plots}%
\PackageWarningNoLine{sagetex}{Run Sage on \jobname.sage, and then run
LaTeX on \jobname.tex again}}}
%    \end{macrocode}
%
%
% \subsection{The Python module}
%
% \iffalse
% Hey, docstrip! Stop putting code into the .sty file, and start
% putting it into the .py file.
%</latex>
%<*python>
% Thanks.
% \fi
%
% The style file writes things to the |.sage| file and reads them from
% the |.sout| file. The Python module provides functions that help
% produce the |.sout| file from the |.sage| file.
%
% We start with some imports and definitions of our global variables.
% This is a relatively specialized use of Sage, so using global variables
% isn't a bad idea.
%    \begin{macrocode}
from sage.misc.latex import latex
import sys
import os
import os.path
import hashlib
import traceback
import subprocess
initplot_done  = False
dirname        = None
filename       = ""
%    \end{macrocode}
%
% \begin{macro}{progress}
% This is just a cute little function for printing stuff. It allows us
% to not print a linebreak, so you can get ``|start...|'' (little time
% spent processing) ``|end|'' on one line.
%    \begin{macrocode}
def progress(t,linebreak=True):
  if linebreak:
    print(t)
  else:
    sys.stdout.write(t)
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{openout}
% This function opens a |.sout.tmp| file and writes all our output to
% that. Then, when we're done, we move that to |.sout|. The
% ``autogenerated'' line is basically the same as the lines that get put
% at the top of preparsed Sage files; we are automatically generating a
% file with Sage, so it seems reasonable to add it.
%    \begin{macrocode}
def openout(f):
  global filename
  filename = f
  global _file_
  _file_ = open(f + '.sout.tmp', 'w')
  s = '% This file was *autogenerated* from the file ' + \
        os.path.splitext(filename)[0] + '.sage.\n'
  _file_.write(s)
  progress('Processing Sage code for %s.tex...' % filename)
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{deltree}
% When we start plotting, we delete the entire plots directory if it
% exists. This function does that for us.
%    \begin{macrocode}
def deltree(root):
  for name in os.listdir(root):
    path = os.path.join(root, name)
    if os.path.isdir(path):
      deltree(path)
    else:
      os.remove(path)
  os.rmdir(root) 
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{initplot}
% We only want to create the plots directory if the user actually plots
% something. This function creates the directory and sets the
% |initplot_done| flag after doing so. We make a directory based on the
% \LTX file being processed so that if there are multiple |.tex|
% files in a directory, we don't overwrite plots from another file.
%    \begin{macrocode}
def initplot(f):
  global initplot_done
  if not initplot_done:
    progress('Initializing plots directory')
    global dirname
    dirname = 'sage-plots-for-' + f + '.tex'
    if os.path.isdir(dirname):
      deltree(dirname)
    os.mkdir(dirname)
    initplot_done = True
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{inline}
% This function works with |\sage| from the style file to put Sage
% output into your \LTX file. Usually, when you use |\label|, it
% writes a line such as
% \begin{quote}
%   |\newlabel{labelname}{{section number}{page number}}|
% \end{quote}
% to the |.aux| file. When you use the |hyperref| package, there are
% more fields in the second argument, but the first two are the same.
% The |\ref| command just pulls in what's in the first field, so we can
% hijack this mechanism for our own nefarious purposes. The function
% writes a |\newlabel| line with a label made from a counter and the
% text from running Sage on |s|. 
%
% We print out the line number so if something goes wrong, the user can
% more easily track down the offending |\sage| command in the source
% file.
%
% That's a lot of explanation for a very short function:
%    \begin{macrocode}
def inline(counter, line, s):
  progress('Inline formula %s, line %s' % (counter, line))
  _file_.write('\\newlabel{@sagelabel' + str(counter) + '}{{' + \
               latex(s) + '}{}{}{}{}}\n')
%    \end{macrocode}
% We are using five fields, just like |hyperref| does, because that
% works whether or not |hyperref| is loaded. Using two fields, as in plain
% \LTX, doesn't work if |hyperref| is loaded.
% \end{macro}
%
% \begin{macro}{blockbegin}
% \begin{macro}{blockend}
% This function and its companion used to write stuff to the |.sout|
% file, but now they just update the user on our progress evaluating a
% code block.
%    \begin{macrocode}
def blockbegin(line):
  progress('Code block on line %s begin...' % line, False)
def blockend():
  progress('end')
%    \end{macrocode}
% \end{macro} 
% \end{macro} 
%
% \begin{macro}{sageplot}
% Here we do plotting. As mentioned in the |\sageplot| code (note the
% backslash), we're taking advantage of two things: first, that
% \LTX doesn't treat commas and spaces in macro arguments specially,
% and second, that Python (and Sage plotting functions) has nice support
% for keyword arguments. The |#3| argument to |\sageplot| becomes
% |p| and |**kwargs| below.
%    \begin{macrocode}
def sageplot(counter, line, p, format='notprovided', epsmagick=False, **kwargs):
  global dirname
  progress('Plot %s, line %s' % (counter, line))
%    \end{macrocode}
% If the user says nothing about file formats, we default to producing
% PDF and EPS. This allows the user to transparently switch between
% using a DVI previewer (which usually automatically updates when the
% DVI changes, and has support for source specials, which makes the
% writing process easier) and making PDFs. 
%    \begin{macrocode}
  if format == 'notprovided':
    formats = ['eps', 'pdf']
  else:
    formats = [format]
  for fmt in formats:
    plotfilename = os.path.join(dirname, 'plot-%s.%s' % (counter, fmt))
    #print('  plotting %s with args %s' % (plotfilename, kwargs))
    p.save(filename=plotfilename, **kwargs)
%    \end{macrocode}
% If the user provides a format \emph{and} specifies the |imagemagick|
% option, we try to convert the newly-created file into EPS format.
%    \begin{macrocode}
    if format != 'notprovided' and epsmagick is True:
      print('calling toeps(%s, %s)...' % (counter, format))
      toeps(counter, format)
%    \end{macrocode}
% \end{macro}
%
% \begin{macro}{toeps}
% This function calls the Imagmagick utility |convert| to, well, convert
% something into EPS format. This gets called when the user has
% requested the ``|imagemagick|'' option to the \ST\ style file and is
% making a graphic file with a nondefault extension.
%    \begin{macrocode}
def toeps(counter, ext):
  global dirname
  subprocess.check_call(['convert',\
    '%s/plot-%s.%s' % (dirname, counter, ext), \
    '%s/plot-%s.eps' % (dirname, counter)])
%    \end{macrocode}
% We are blindly assuming that the |convert| command exists and will do
% the conversion for us; the |check_call| function raises an exception
% which, since all these calls get wrapped in try/excepts in the |.sage|
% file, should result in a reasonable error message if something strange
% happens.
% \end{macro}
%
% \begin{macro}{goboom}
% When a chunk of Sage code blows up, this function bears the bad news
% to the user. Normally in Python the traceback is good enough for this,
% but in this case, we start with a |.sage| file (which is
% autogenerated) which autogenerates a |.py| file---and the tracebacks
% the user sees refer to that file, whose line numbers are basically
% useless. We want to tell them where in the \LTX file things went
% bad, so we do that, give them the traceback, and exit after removing
% the |.sout.tmp| file.
%    \begin{macrocode}
def goboom(line):
  global filename
  print('\n**** Error in Sage code on line %s of %s.tex! Traceback follows.' % (line, filename))
  traceback.print_exc()
  print('\n**** Running Sage on %s.sage failed! Fix %s.tex and try again.' % (filename, filename))
  os.remove(filename + '.sout.tmp')
  sys.exit(1)
%    \end{macrocode}
% \end{macro}
% 
% \begin{macro}{endofdocument}
% When we're done processing, we have a couple little cleanup tasks. We
% find the MD5 sum of the |.sage| file that produced the |.sout| file
% we're about to write, and put that sum into the |.sout| file. This
% allows external programs that build \LTX documents to tell if they
% need to call Sage to update the |.sout| file. We do issue warnings to
% run Sage on the |.sage| file, but those warnings do not quite capture
% all situations, and anyway I think it's easier to grab the md5sum out
% of the end of the file than parse the output from running |latex| on
% your file. (The regular expression \verb|^%[0-9a-f]{32}%| will find
% the MD5 sum.)
%    \begin{macrocode}
def endofdocument():
  global filename
  dotsagesum = hashlib.md5(open(filename + '.sage', 'rb').read()).hexdigest()
  s = '%' + dotsagesum + '% md5sum of .sage file that produced this\n'
  _file_.write(s)
%    \end{macrocode}
% Now we are done with the |.sout| file. Close it, rename it, and tell
% the user we're done.
%    \begin{macrocode}
  _file_.close()
  os.rename(filename + '.sout.tmp', filename + '.sout')
  progress('Sage processing complete. Run LaTeX on %s.tex again.' % filename)
%    \end{macrocode}
% \end{macro}
%
% \section{Credits and acknowledgements}
%
% According to the original README file, this system was originally
% done by Gonzalo Tornaria and Joe Wetherell. Later Harald Schilly made
% some improvements and modifications. Almost all the examples in the
% |example.tex| file are from Harald.
%
% Dan Drake rewrote the style file (there is almost zero original code
% there), made significant changes to the Python module, put both
% files into \textsf{Docstrip} format, and wrote all the documentation.
%
% Many thanks to Jason Grout for comments, suggestions, and feedback.
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.