Ticket #11459: trac_11459-scripts.patch

File trac_11459-scripts.patch, 9.9 KB (added by kini, 10 years ago)

apply to $SAGE_LOCAL/bin

  • new file sage-rst2sws

    # HG changeset patch
    # User Sebastien Labbe <slabqc at gmail.com>
    # Date 1337178035 -28800
    # Node ID 125fafd7be623cc7274c74cbf8c5805b74a61b69
    # Parent  9a82a7ebfb54b8eb7d28a2f98babba1754312230
    #11459: adding rst2txt and rst2sws to local bin scripts
    
    diff --git a/sage-rst2sws b/sage-rst2sws
    new file mode 100755
    - +  
     1#!/usr/bin/env python
     2r"""
     3sage-rst2sws
     4
     5Translate a rst file into a Sage worksheet file (.sws).
     6
     7Usage::
     8
     9    sage -rst2sws [options] <source> <destination>
     10
     11Print the help message::
     12
     13    sage -rst2sws -h
     14
     15EXAMPLES::
     16
     17    sage -rst2sws file.rst file.sws
     18
     19In RestructuredText, "an escaped character represents the character itself,
     20and is prevented from playing a role in any markup interpretation. The
     21backslash is removed from the output" [1,2]. So, if the backslashes of your
     22ReST file are not escaped, they will get lost in the process. This is not
     23practical for Sage since most of the documentation and examples are Python
     24raw string where backslashes are not escaped. Use the following command to
     25escape every backslashes of the input file::
     26
     27    sage -rst2sws --escape-backslashes input.rst output.sws
     28
     29AUTHOR:
     30
     31    - Sebastien Labbe (2011, June 14th, at Sage Days 31): Initial version
     32
     33REFERENCES:
     34
     35    - [1] Escaping Mechanism, reStructuredText Markup Specification,
     36      http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#escaping-mechanism
     37    - [2] Espcaping with backslashes, Quick reStructuredText Reference,
     38      http://docutils.sourceforge.net/docs/user/rst/quickref.html#escaping
     39
     40"""
     41#############################################################################
     42#       Copyright (C) 2011 Sebastien Labbe <slabqc at gmail.com>
     43#  Distributed under the terms of the GNU General Public License (GPL)
     44#  The full text of the GPL is available at:
     45#                  http://www.gnu.org/licenses/
     46#############################################################################
     47import os, sys
     48from optparse import OptionParser
     49
     50# Set the parser
     51usage = r"""
     52
     53    sage -rst2sws [options] <source> <destination>
     54
     55Generates Sage worksheet (.sws) from standalone reStructuredText source.
     56
     57Example:
     58
     59    sage -rst2sws file.rst file.sws
     60
     61Remarks:
     62
     63    About LaTeX:
     64
     65        You can put LaTeX expression between backticks "`", dollars sign
     66        "$" or double dollar signs "$$". Math role is not supported yet
     67        (get involved!).
     68
     69        Examples: `\\alpha`, $\\beta$ or $$\\gamma$$.
     70
     71    About backslashes:
     72
     73        In ReStructuredText, backslashes must be escaped or otherwise they
     74        are ignored. This is not quite practical for Sage purposes since
     75        backslashes are never escaped in the docstrings. If you write
     76        `\alpha`, $\beta$ or $$\gamma$$, add the line
     77
     78            "..  escape-backslashes"
     79
     80        to the file and this script will consider every backslashes as
     81        escaped. Alternatively, you may use the available options."""
     82parser = OptionParser(usage=usage)
     83parser.add_option("--escape-backslashes",
     84                  action="store_true", dest="escape_backslashes",
     85                  help="Escape every backslashes in the input file before execution. Default: disabled.")
     86parser.add_option("--no-escape-backslashes",
     87                  action="store_true", dest="no_escape_backslashes",
     88                  help="Disable escaping every backslashes in the input file before execution. This overwrites the presence of the line '.. escape-backslashes' in the file which also enable escaping every backslashes in the file.")
     89(options, args) = parser.parse_args()
     90
     91# Parse arguments
     92if len(args) != 2:
     93    parser.print_usage()
     94    sys.exit(1)
     95input = args[0]
     96output = args[1]
     97
     98# Read the ReST input
     99try:
     100    with open(input, 'r') as f:
     101        rst = f.read()
     102except IOError as e:
     103    print "IOError: %s" % e
     104    print "Unable to open source file for reading ('%s').  Exiting." % input
     105    sys.exit(1)
     106
     107# docutils loses the alone backslashes, so we precede them with escapes
     108# A better solution would be to escape baskslashes only in the math sections
     109import re
     110if options.escape_backslashes:
     111    rst = rst.replace('\\','\\\\')
     112elif options.no_escape_backslashes:
     113    pass
     114elif re.search(r'^\.\.[ \t]+escape-backslashes', rst, re.MULTILINE) is not None:
     115    rst = rst.replace('\\','\\\\')
     116
     117# Do the translation rst -> html (using docutils)
     118from docutils.core import publish_parts
     119D = publish_parts(rst, writer_name='html')
     120title = D['title']
     121html = D['whole']
     122
     123# Do the translation html -> worksheet txt
     124from sagenb.notebook.docHTMLProcessor import docutilsHTMLProcessor
     125translator = docutilsHTMLProcessor()
     126worksheet_txt = translator.process_doc_html(html)
     127
     128# create a Notebook
     129from sagenb.notebook.notebook import Notebook
     130from sage.misc.misc import tmp_dir
     131nb = Notebook(tmp_dir()+'.sagenb')
     132
     133# create a worksheet
     134W = nb.create_new_worksheet(title, 'admin')
     135W.edit_save(worksheet_txt)
     136
     137# export the worksheet as sws
     138nb.export_worksheet(W.filename(), output, title=title)
     139
     140# delete the Notebook
     141nb.delete()
     142
  • new file sage-rst2txt

    diff --git a/sage-rst2txt b/sage-rst2txt
    new file mode 100755
    - +  
     1#!/usr/bin/env python
     2r"""
     3sage-rst2txt
     4
     5Translate a rst file into a worksheet txt file.
     6
     7A worksheet txt file is a plain text file (no graphics) with html code and
     8sage cells surrounded by {{{'s.
     9
     10Usage::
     11
     12    sage -rst2txt [options] <source> [<destination>]
     13
     14Print the help message::
     15
     16    sage -rst2txt -h
     17
     18EXAMPLES::
     19
     20    sage -rst2txt input.rst output.txt
     21
     22::
     23
     24    sage -rst2txt input.rst | less
     25
     26In RestructuredText, "an escaped character represents the character itself,
     27and is prevented from playing a role in any markup interpretation. The
     28backslash is removed from the output" [1,2]. So, if the backslashes of your
     29ReST file are not escaped, they will get lost in the process. This is not
     30practical for Sage since most of the documentation and examples are Python
     31raw string where backslashes are not escaped. Use the following command to
     32escape every backslashes of the input file::
     33
     34    sage -rst2txt --escape-backslashes input.rst output.txt
     35
     36AUTHOR:
     37
     38    - Sebastien Labbe (2011, January 15th): Initial version
     39    - Sebastien Labbe (2011, June 14th, at Sage Days 31): Make it ready for
     40      inclusion into Sage.
     41
     42REFERENCES:
     43
     44    - [1] Escaping Mechanism, reStructuredText Markup Specification,
     45      http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#escaping-mechanism
     46    - [2] Espcaping with backslashes, Quick reStructuredText Reference,
     47      http://docutils.sourceforge.net/docs/user/rst/quickref.html#escaping
     48"""
     49#############################################################################
     50#       Copyright (C) 2011 Sebastien Labbe <slabqc at gmail.com>
     51#  Distributed under the terms of the GNU General Public License (GPL)
     52#  The full text of the GPL is available at:
     53#                  http://www.gnu.org/licenses/
     54#############################################################################
     55import os, sys
     56from optparse import OptionParser
     57
     58# Set the parser
     59usage = r"""
     60
     61    sage -rst2txt [options] <source> [<destination>]
     62
     63Generates Sage worksheet text file from standalone reStructuredText source.
     64
     65Example:
     66
     67    sage -rst2txt file.rst file.txt
     68
     69Remarks:
     70
     71    About LaTeX:
     72
     73        You can put LaTeX expression between backticks "`", dollars sign
     74        "$" or double dollar signs "$$". Math role is not supported yet
     75        (get involved!).
     76
     77        Examples: `\\alpha`, $\\beta$ or $$\\gamma$$.
     78
     79    About backslashes:
     80
     81        In ReStructuredText, backslashes must be escaped or otherwise they
     82        are ignored. This is not quite practical for Sage purposes since
     83        backslashes are never escaped in the docstrings. If you write
     84        `\alpha`, $\beta$ or $$\gamma$$, add the line
     85
     86            "..  escape-backslashes"
     87
     88        to the file and this script will consider every backslashes as
     89        escaped. Alternatively, you may use the available options."""
     90
     91parser = OptionParser(usage=usage)
     92parser.add_option("--escape-backslashes",
     93                  action="store_true", dest="escape_backslashes",
     94                  help="Escape every backslashes in the input file before execution. Default: disabled.")
     95parser.add_option("--no-escape-backslashes",
     96                  action="store_true", dest="no_escape_backslashes",
     97                  help="Disable escaping every backslashes in the input file before execution. This overwrites the presence of the line '.. escape-backslashes' in the file which also enable escaping every backslashes in the file.")
     98
     99(options, args) = parser.parse_args()
     100
     101# Parse arguments
     102if not 1 <= len(args) <= 2:
     103    parser.print_usage()
     104    sys.exit(1)
     105input = args[0]
     106output = args[1] if len(args) == 2 else ''
     107
     108# Read the ReST input
     109try:
     110    with open(input, 'r') as f:
     111        rst = f.read()
     112except IOError as e:
     113    print "IOError: %s" % e
     114    print "Unable to open source file for reading ('%s').  Exiting." % input
     115    sys.exit(1)
     116
     117# docutils loses the alone backslashes, so we precede them with escapes
     118# A better solution would be to escape baskslashes only in the math sections
     119import re
     120if options.escape_backslashes:
     121    rst = rst.replace('\\','\\\\')
     122elif options.no_escape_backslashes:
     123    pass
     124elif re.search(r'^\.\.[ \t]+escape-backslashes', rst, re.MULTILINE) is not None:
     125    rst = rst.replace('\\','\\\\')
     126
     127# Do the translation rst -> html (using docutils)
     128from docutils.core import publish_string
     129html = publish_string(rst, writer_name='html')
     130
     131# Do the translation html -> worksheet txt
     132from sagenb.notebook.docHTMLProcessor import docutilsHTMLProcessor
     133translator = docutilsHTMLProcessor()
     134worksheet_txt = translator.process_doc_html(html)
     135
     136# Write the output
     137if output:
     138    with open(output, "w") as f:
     139        f.write(worksheet_txt)
     140else:
     141    print worksheet_txt
     142