Source

sws2tex / sws2tex.py

  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
#! /usr/bin/env sage
###############################################################################
#   Sage: Open Source Mathematical Software
#       Copyright (C) 2009-2010 Robert Marik <marik@mendelu.cz>
#       Copyright (C) 2009-2010 Wilfried Huss <huss@finanz.math.tugraz.at>
#  Distributed under the terms of the GNU General Public License (GPL),
#  version 2 or any later version.  The full text of the GPL is available at:
#                  http://www.gnu.org/licenses/
###############################################################################

r"""
Poor man's Sage to TeX converter.

The script converts some basic html to TeX sequences

USAGE:
./sage2tex file.sws [output]

OUTPUT:
The output is in file output.pdf. If the second argument is missing, the
output is in file.pdf.

Works for limited set of commands, only.
"""
default_preamble = r"""
\documentclass[a4paper]{article}
\usepackage{xcolor,amsmath,graphicx,hyperref}
\usepackage{attachfile}
\usepackage{colortbl}
\usepackage[margin=1in]{geometry}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{amssymb}
\usepackage{fancyvrb}
\def\sagegraphics#1#2{\includegraphics{sage_worksheet/cells/#1/#2}}

\parindent=0pt
%\parsep=10pt

%\renewcommand{\arraystretch}{1.5}
%\setlength{\tabcolsep}{0.2cm}
\setlength{\minrowclearance}{1ex}
"""

import re
import string
import os
import shutil
import sys
import glob
import textwrap

from htmltable2latex import parse_table
from html2latex import Html2Latex

try:
    from pygments import highlight
    from pygments.lexers import PythonLexer, TexLexer, HtmlLexer
    from pygments.formatters import LatexFormatter
    from pygments.styles import STYLE_MAP
    from pygments.styles import get_style_by_name
    from sphinx.highlighting import SphinxStyle

    class Colorize:
        def __init__(self, style=SphinxStyle):
            self.pythonlexer = PythonLexer(encoding='utf8')
            self.texlexer = TexLexer(encoding='utf8')
            self.htmllexer = HtmlLexer(encoding='utf8')
            self.formatter = LatexFormatter(noclasses=True, style=style)

        def get_style_defs(self):
            return self.formatter.get_style_defs()

        def __call__(self, s, format = 'python'):
            if format == 'python' or format == 'sage' or format == 'sage interact' or format == 'cython':
                return highlight(s, self.pythonlexer, self.formatter)
            elif format == 'latex':
                return highlight(s, self.texlexer, self.formatter)
            elif format == 'html':
                return highlight(s, self.htmllexer, self.formatter)
            else:
                return "\\begin{Verbatim}[commandchars=@\\[\\]]\n" + s + "\n\\end{Verbatim}\n"

    colorize = Colorize()

except ImportError:
    print "Warning: Unable to load module pygments"
    print "Warning: Syntax highlighting will be disabled"

    def colorize(s, **kwds):
        return "\\begin{Verbatim}[commandchars=@\\[\\]]\n" + s + "\n\\end{Verbatim}\n"

def line_breaks(text, columns=85, options=None):
    r"""
    Split the string into lines of length columns.
    
    - options.word_wrap = 0 : no wrapping
    - options.word_wrap = 1 : wrapping using textwrap module
    - options.word_wrap = 2 : fixed line length
    

    """
    newlines = ""
    for line in text.splitlines():
        if options.word_wrap == 0:
            newlines += line + '\n'
        elif options.word_wrap == 1:
            newlines += textwrap.fill(line,columns) + "\n"
        else:
            while len(line) >= columns:
                newlines += line[0:columns] + '\\\n'
                #if line[0:columns].find(' ') == -1:
                #    newlines += '\n'
                line = line[columns:]
            newlines += line + '\n'
    return newlines


class Cell:
    text = ""
    cell_type = "generic"
    cell_id = -1

    def __init__(self, text, cell_id, options = None):
        self.text = text
        self.cell_id = cell_id
        self.options = options

    def __str__(self):
        string = 'Type: %s (id = %d)\n' % (self.cell_type, self.cell_id)
        string += '=====================================================\n'
        string += self.text #self.latex()
        string += '=====================================================\n'
        return string

    def latex(self):
        return self.text

class TextCell(Cell):
    r"""
    Cells which contains strings from TinyMCE editor
    """
    cell_type = "text"

    def __init__(self, text, cell_id, options=None):
        Cell.__init__(self, text, cell_id, options)
        self.language=""
        self.html2latex = Html2Latex(options)

    def latex(self):
        latex_str = self.text

        latex_str = self.html2latex.parse_html(latex_str, temp_dir = temp_dir)

        return latex_str

class InputCell(Cell):
    r"""
    The input cell. Could be coded in more languages specified usually
    on the first line.
    """
    cell_type = 'input'
    language = 'sage'

    def __init__(self, text, cell_id, options = None):
        Cell.__init__(self, text, cell_id, options)
        self._detect_language()

    def _detect_language(self):
        first_line = self.text.splitlines()[0]
        if first_line == '%latex':
            self.language = 'latex'
        elif first_line == '%html':
            self.language = 'html'
        elif first_line == '%python':
            self.language = 'python'
        elif first_line == '%cython':
            self.language = 'cython'
        elif first_line == '%maxima':
            self.language = 'maxima'
        elif self.text.find('@interact') != -1:
            self.language = 'sage interact'
        else:
            self.language = 'sage'

    def latex(self):
        if options.hide:
            first_line = self.text.splitlines()[0]
            if first_line == '%hide':
                return ""
        latex_str = colorize(self.text, format=self.language)
        verb_before = r"\begin{Verbatim}[commandchars=@\[\]]"
        verb_after  = r"\begin{Verbatim}[frame=single,label={" + self.language.capitalize() + " code},commandchars=@\[\]]"
        return latex_str.replace(verb_before, verb_after)

class OutputCell(Cell):
    r"""
    Cell containning Sage output.

    The content of this cell depends on the fact whether the Typeset
    button in Sage notebook is checked or not. Could contains raw text
    as well as html tags.
    """
    cell_type = "output"
    language = 'sage'

    def __init__(self, text, cell_id, options = None, language = 'sage'):
        Cell.__init__(self, text, cell_id, options)
        self.language = language
        self.html2latex = Html2Latex()

    def latex(self):
        if self.language == 'latex':
            return self.text

        # We don't try to parse the output of interacts
        if self.language == 'sage interact':
            return "\n\n"

        if self.text.find('<div class="docstring">') != -1:
            return "\n\n"

        #if self.text.strip() == "":
        #    return "\n\n"

        output_list = self.parse_output()
        
        if not options.full_errors and re.match('(Traceback.*:)',output_list[0]) is not None:
            temp_output = output_list[0].split("\n")
            temp_output = [temp_output[0], '...', temp_output[-2]]
            output_list = ["\n".join(temp_output)]

        verbatim = True
        latex_str = ""
        for output in output_list:
            if verbatim == True:
                if output.strip() != "":
                    latex_str += "\\begin{Verbatim}[formatcom=\color{blue}]\n"
                    latex_str += line_breaks(output, options=self.options)
                    latex_str += "\\end{Verbatim}\n"
                verbatim = False
            else:
                if output.strip() != "":
                    if output.find('<div class="notruncate">') != -1: # output is a table
                        latex_str += parse_table(output, cell_id=self.cell_id)
                    else:
                        latex_str += "{\\color{blue}\n"
                        latex_str += self.html2latex.parse_html(output, OutputCell = True, cell_id = self.cell_id)
                        latex_str += "\n}\n"
                verbatim = True
            latex_str += "\n\n" # paragraph between <html>...</html> blocks

        # the 3d pictures are simply unused pictures in corresponding directory
        pictures = glob.glob("%s/sage_worksheet/cells/%s/*" % (temp_dir, self.cell_id) )
        if pictures != []:
            for i in pictures:
                i = os.path.basename(i)
                if (i[-3:] == "png" or i[-3:] == "pdf") and latex_str.find("includegraphics{sage_worksheet/cells/%s/%s}" % (self.cell_id, i)) == -1:
                    latex_str += "\n\n\\includegraphics{sage_worksheet/cells/%s/%s}\n\n" % (self.cell_id, i)
                elif i[-4:] == "jmol":
                    latex_str += "\n\n\\centerline{\\color{gray}\\fbox{\\textsc{3D picture skipped}}}\n\n"

        return latex_str

    def parse_output(self):
        text_list = self.text.split('<html>')

        temp = []
        for line in text_list:
            temp += line.split('</html>')

        return temp

def print_cells(cell_list):
    for cell in cell_list:
        print cell

def parse_worksheet(worksheet_text, options = None):
    r"""
    Parses worksheet and splits the content into cells.
    """
    cell_type = 'text'

    cell_list = []
    current_cell = ""
    current_cell_id = -1

    input_cell = re.compile(r'{{{id=(\d*)|\Z')
    output_cell = re.compile('///\n')
    output_cell_end = re.compile('}}}$')

    for line in worksheet_text:
        is_start_of_input_cell = input_cell.match(line)
        is_start_of_output_cell = output_cell.match(line)
        is_end_of_output_cell = output_cell_end.match(line)

        if is_start_of_input_cell is not None:
            current_cell_id = int(is_start_of_input_cell.group(1))
            if current_cell.strip() != "":
                cell_list.append(TextCell(current_cell, current_cell_id, options=options))
            current_cell = ""
            continue

        if is_start_of_output_cell is not None:
            if current_cell.strip() != "":
                cell_list.append(InputCell(current_cell, current_cell_id))
            current_cell = ""
            continue

        if is_end_of_output_cell is not None:
            language = cell_list[-1].language
            if language == 'latex':
                current_cell = cell_list[-1].text
            #if current_cell.strip() != "":
            cell_list.append(OutputCell(current_cell, current_cell_id, options=options, language = language))
            current_cell = ""
            continue

        current_cell += line

    return cell_list

def write_latex_file(cell_list, input_filename, title, options):
    r"""
    Returns the content of LaTeX file.
    """
    author = options.author
    toc = options.toc

    latex_src = preamble
    try:
        # If pygments is loaded add color definitions to the preamble
        latex_src += colorize.get_style_defs() + "\n"
    except:
        pass

    if title is not None:
        latex_src += "\\title{%s}" % title + "\n"
    if author is not None:
        latex_src += "\\author{%s}" % author + "\n"
    latex_src += "\\begin{document}\n"

    if title is not None or author is not None:
        latex_src += "\\maketitle\n"

    latex_src += "\\attachfile[description=You can get the Sage worksheet by clicking this icon.]{%s}\n" % input_filename
    if toc:
        latex_src += "\\tableofcontents\n"

    for cell in cell_list:
        latex_src += cell.latex()

    latex_src += "\\end{document}"
    return latex_src


from optparse import OptionParser
usage = r"""
usage: %prog [options] input [output]

You may want to set your default LaTeX preamble, author, language and
word_wrap in .sws2tex config file in current directory or in your home
directory (see .sws2tex_example). Command line options override this
settings.
"""
opt_parser = OptionParser(usage = usage)
opt_parser.add_option("-q", "--quiet",
                      action = "store_true", dest = "quiet", default = False,
                      help = "don't print status messages to stdout")

opt_parser.add_option("-w", "--working_directory",
                      action = "store", dest = "working_dir", default = "automatic",
                      help = "the working directory")

opt_parser.add_option("-a", "--author",
                      action = "store", dest = "author", default = None,
                      help = "the name of the author")

opt_parser.add_option("-t", "--toc",
                      action = "store_true", dest = "toc", default = False,
                      help = "include a table of contents")

opt_parser.add_option("-i", "--ignore",
                      action = "store_true", dest = "ignore_unknown_tags", default = False,
                      help = "ignore unknown HTML-tags")

opt_parser.add_option("-l", "--lang",
                      action = "store", dest = "lang", default = None,
                      help = "input language settings (babel)")

opt_parser.add_option("-H", "--hide",
                      action = "store_true", dest = "hide", default = False,
                      help = "do not print cell with %hide token")

opt_parser.add_option("-W", "--word_wrap",
                      action = "store", type = 'int', dest = "word_wrap", default = None,
                      help = "select method for word wrap: 0 (no wrapping), 1 (textwraper, default), 2 (fixed line length)")

opt_parser.add_option("-e", "--full_errors",
                      action = "store_true", dest = "full_errors", default = False,
                      help = "do not shorten error messages")

(options, args) = opt_parser.parse_args()

if len(args) < 2:
    if len(args) == 1:
        input_filename = args[0]
        output_filename = input_filename[0:-4]
    else:
        opt_parser.print_help()
        exit(1)
else:
    input_filename = args[0]
    output_filename = args[1]

# create a temporary directory
if options.working_dir == 'automatic':
    import tempfile
    temp_dir = tempfile.mkdtemp()
else:
    temp_dir = os.getcwd() + os.sep + options.working_dir
    os.mkdir(temp_dir)

if not options.quiet:
    print "Temp directory: "+temp_dir
    print "Input filename: "+input_filename

# extract sage worksheet
import tarfile
tar = tarfile.open(input_filename)
tar.extractall(path = temp_dir)
tar.close()

worksheet = open(temp_dir + os.sep + "sage_worksheet" + os.sep + "worksheet.html", 'r')
try:
    worksheet_txt = open(temp_dir + os.sep + "sage_worksheet" + os.sep + "worksheet.txt", 'r')
    title = worksheet_txt.readlines()[0]
except:
    title = None

cell_list = parse_worksheet(worksheet.readlines(), options = options)
worksheet.close()

try:
    from IPython.external.configobj import ConfigObj

    if os.path.exists('.sws2tex'):
        filename = '.sws2tex'
    elif os.path.exists(os.path.expanduser("~/.sws2tex")):
        filename = os.path.expanduser("~/.sws2tex")
    if not options.quiet:
        print "Config file: %s" %filename
    config = ConfigObj(filename)
except ImportError:
    print "Warning: Unable to load module configobj"
    print "Warning: Support for .sws2tex config file disabled"
    config = {}
except:
    config = {}

if config.has_key('preamble'):
    preamble = config['preamble']
else:
    preamble = default_preamble

if options.author is None:
    if config.has_key('author'):
        options.author = config['author']

if options.word_wrap is None:
    if config.has_key('word_wrap'):
        options.word_wrap = int(config['word_wrap'])
    else:
        options.word_wrap = 1

if options.lang is not None:
    preamble += "\usepackage[%s]{babel}" % options.lang
elif config.has_key('lang'):
    preamble += "\usepackage[%s]{babel}" % config['lang']


#print print_cells(cell_list)
latex_src = write_latex_file(cell_list, input_filename, title, options)

TeX_file = open(temp_dir + os.sep + output_filename + ".tex",'w')
TeX_file.write(latex_src)
TeX_file.close()

shutil.copyfile(input_filename, temp_dir + os.sep + input_filename)

command = "cd %s; pdflatex -interaction=nonstopmode %s.tex" % (temp_dir,output_filename)

for i in range(3):
    pdflatex_output = os.popen(command)
    if options.quiet:
        pdflatex_output.read()
    else:
        for line in pdflatex_output.readlines():
            print line,

shutil.copyfile(temp_dir + os.sep + output_filename + ".pdf", output_filename + ".pdf")

if options.working_dir == 'automatic':
    shutil.rmtree(temp_dir)