diff options
Diffstat (limited to 'sandbox/dpriest/csvtable')
-rw-r--r-- | sandbox/dpriest/csvtable/csv-directive_test-external_table.txt | 5 | ||||
-rw-r--r-- | sandbox/dpriest/csvtable/csv-directive_test.txt | 31 | ||||
-rwxr-xr-x | sandbox/dpriest/csvtable/csvpublish.py | 26 | ||||
-rw-r--r-- | sandbox/dpriest/csvtable/csvtable.py | 257 | ||||
-rw-r--r-- | sandbox/dpriest/csvtable/csvtable.txt | 93 |
5 files changed, 0 insertions, 412 deletions
diff --git a/sandbox/dpriest/csvtable/csv-directive_test-external_table.txt b/sandbox/dpriest/csvtable/csv-directive_test-external_table.txt deleted file mode 100644 index 3669c4a16..000000000 --- a/sandbox/dpriest/csvtable/csv-directive_test-external_table.txt +++ /dev/null @@ -1,5 +0,0 @@ -"Header row, column 1", "Header 2", "Header 3", "Header 4" -"Body row 1, column 1", "Column 2", "Column 3", "Column 4" -"Body row 2", "Cells may span columns.", , -"Body row 3", "Cells may span rows.", "- Table cells - contain - body elements.", -"Body row 4",,, diff --git a/sandbox/dpriest/csvtable/csv-directive_test.txt b/sandbox/dpriest/csvtable/csv-directive_test.txt deleted file mode 100644 index c0077ef00..000000000 --- a/sandbox/dpriest/csvtable/csv-directive_test.txt +++ /dev/null @@ -1,31 +0,0 @@ -Headline -======== - -.. table:: Standard table - - +--------------------------+------------+----------+----------+ - | Header row, column 1 | Header 2 | Header 3 | Header 4 | - +==========================+============+==========+==========+ - | body *row* 1, column 1 | column 2 | column 3 | column 4 | - +--------------------------+------------+----------+----------+ - | body row 2 | Cells may span columns. | - +--------------------------+------------+---------------------+ - | body row 3 | Cells may | - Table cells | - +--------------------------+ span rows. | - contain | - | body row 4 | | - body elements. | - +--------------------------+------------+---------------------+ - - -.. csvtable:: Inline CSV table - :header-rows: 1 - :widths: 24, 10, 10, 12 - - "Header row, column 1", "Header 2", "Header 3", "Header 4" - "Body *row* 1, column 1", "Column 2", "Column 3", "Column 4" - "Body row 2", "Cells may span columns.",, - "Body row 3", "Cells may span rows.", "- Table cells - contain - body elements.", - "Body row 4", , , - - -.. csvtable:: Included CSV table - :file: csv-directive_test-external_table.txt diff --git a/sandbox/dpriest/csvtable/csvpublish.py b/sandbox/dpriest/csvtable/csvpublish.py deleted file mode 100755 index b101adf63..000000000 --- a/sandbox/dpriest/csvtable/csvpublish.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python - -# Author: David Goodger -# Contact: goodger@users.sourceforge.net -# Revision: $Revision$ -# Date: $Date$ -# Copyright: This module has been placed in the public domain. - -""" -A minimal front end to the Docutils Publisher, producing pseudo-XML. -""" - -try: - import locale - locale.setlocale(locale.LC_ALL, '') -except: - pass - -from docutils.core import publish_cmdline, default_description -import csvtable - - -description = ('Generates pseudo-XML from standalone reStructuredText ' - 'sources (for testing purposes). ' + default_description) - -publish_cmdline(description=description) diff --git a/sandbox/dpriest/csvtable/csvtable.py b/sandbox/dpriest/csvtable/csvtable.py deleted file mode 100644 index 7b69a9d54..000000000 --- a/sandbox/dpriest/csvtable/csvtable.py +++ /dev/null @@ -1,257 +0,0 @@ -# Author: David Priest & David Goodger -# Contact: priest@sfu.ca -# Revision: $Revision$ -# Date: $Date$ -# Copyright: This module has been placed in the public domain. - -""" -Directive for CSV (comma-separated values) Tables. -""" - -import csv -import os.path -import operator -from docutils import nodes, statemachine, utils -from docutils.utils import SystemMessagePropagation -from docutils.transforms import references -from docutils.parsers.rst import directives - -try: - import urllib2 -except ImportError: - urllib2 = None - -try: - True -except NameError: # Python 2.2 & 2.1 compatibility - True = not 0 - False = not 1 - - -class DocutilsDialect(csv.Dialect): - - delimiter = ',' - quotechar = '"' - doublequote = True - skipinitialspace = True - lineterminator = '\n' - quoting = csv.QUOTE_MINIMAL - - def __init__(self, options): - if options.has_key('delim'): - self.delimiter = str(options['delim']) - if options.has_key('quote'): - self.quotechar = str(options['quote']) - if options.has_key('escape'): - self.doublequote = False - self.escapechar = str(options['escape']) - csv.Dialect.__init__(self) - - -class HeaderDialect(csv.Dialect): - - """CSV dialect to use for the "header" option data.""" - - delimiter = ',' - quotechar = '"' - escapechar = '\\' - doublequote = False - skipinitialspace = True - lineterminator = '\n' - quoting = csv.QUOTE_MINIMAL - - -def csv_table(name, arguments, options, content, lineno, - content_offset, block_text, state, state_machine): - - title, messages = make_title(arguments, state, lineno) - try: - csv_data, source = get_csv_data( - name, options, content, lineno, block_text, state, state_machine) - table_head, max_header_cols = process_header_option( - options, state_machine, lineno) - rows, max_cols = parse_csv_data_into_rows( - csv_data, DocutilsDialect(options), source, options) - max_cols = max(max_cols, max_header_cols) - header_rows = options.get('header-rows', 0) # default 0 - table_head.extend(rows[:header_rows]) - table_body = rows[header_rows:] - if not table_body: - error = state_machine.reporter.error( - '"%s" directive requires table body content.' % name, - nodes.literal_block(block_text, block_text), line=lineno) - return [error] - col_widths = get_col_widths( - max_cols, name, options, lineno, block_text, state_machine) - extend_short_rows_with_empty_cells(max_cols, (table_head, table_body)) - except SystemMessagePropagation, detail: - return [detail.args[0]] - except csv.Error, detail: - error = state_machine.reporter.error( - 'Error with CSV data in "%s" directive:\n%s' % (name, detail), - nodes.literal_block(block_text, block_text), line=lineno) - return [error] - table = (col_widths, table_head, table_body) - table_node = state.build_table(table, content_offset) - if options.has_key('class'): - table_node.set_class(options['class']) - if title: - table_node.insert(0, title) - return [table_node] + messages - -def make_title(arguments, state, lineno): - if arguments: - title_text = arguments[0] - text_nodes, messages = state.inline_text(title_text, lineno) - title = nodes.title(title_text, '', *text_nodes) - else: - title = None - messages = [] - return title, messages - -def get_csv_data(name, options, content, lineno, block_text, - state, state_machine): - if content: # CSV data is from directive content - if options.has_key('file') or options.has_key('url'): - error = state_machine.reporter.error( - '"%s" directive may not both specify an external file and ' - 'have content.' % name, - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(error) - source = content.source(0) - csv_data = content - elif options.has_key('file'): # CSV data is from an external file - if options.has_key('url'): - error = state_machine.reporter.error( - 'The "file" and "url" options may not be simultaneously ' - 'specified for the "%s" directive.' % name, - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(error) - source_dir = os.path.dirname( - os.path.abspath(state.document.current_source)) - source = os.path.normpath(os.path.join(source_dir, options['file'])) - source = utils.relative_path(None, source) - try: - csv_file = open(source, 'rb') - try: - csv_data = csv_file.read().splitlines() - finally: - csv_file.close() - except IOError, error: - severe = state_machine.reporter.severe( - 'Problems with "%s" directive path:\n%s.' % (name, error), - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(severe) - elif options.has_key('url'): # CSV data is from a URL - if not urllib2: - severe = state_machine.reporter.severe( - 'Problems with the "%s" directive and its "url" option: ' - 'unable to access the required functionality (from the ' - '"urllib2" module).' % name, - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(severe) - source = options['url'] - try: - csv_data = urllib2.urlopen(source).read().splitlines() - except (urllib2.URLError, IOError, OSError, ValueError), error: - severe = state_machine.reporter.severe( - 'Problems with "%s" directive URL "%s":\n%s.' - % (name, options['url'], error), - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(severe) - else: - error = state_machine.reporter.warning( - 'The "%s" directive requires content; none supplied.' % (name), - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(error) - return csv_data, source - -def process_header_option(options, state_machine, lineno): - source = state_machine.get_source(lineno - 1) - table_head = [] - max_header_cols = 0 - if options.has_key('header'): # separate table header in option - rows, max_header_cols = parse_csv_data_into_rows( - options['header'].split('\n'), HeaderDialect(), source, options) - table_head.extend(rows) - return table_head, max_header_cols - -def parse_csv_data_into_rows(csv_data, dialect, source, options): - csv_reader = csv.reader(csv_data, dialect=dialect) - rows = [] - max_cols = 0 - for row in csv_reader: - row_data = [] - for cell in row: - cell_data = (0, 0, 0, statemachine.StringList(cell.splitlines(), - source=source)) - row_data.append(cell_data) - rows.append(row_data) - max_cols = max(max_cols, len(row)) - return rows, max_cols - -def get_col_widths(max_cols, name, options, lineno, block_text, - state_machine): - if options.has_key('widths'): - col_widths = options['widths'] - if len(col_widths) != max_cols: - error = state_machine.reporter.error( - '"%s" widths do not match the number of columns in table (%s).' - % (name, max_cols), - nodes.literal_block(block_text, block_text), line=lineno) - raise SystemMessagePropagation(error) - else: - col_widths = [100 / max_cols] * max_cols - return col_widths - -def extend_short_rows_with_empty_cells(columns, parts): - for part in parts: - for row in part: - if len(row) < columns: - row.extend([(0, 0, 0, [])] * (columns - len(row))) - -def single_char_or_unicode(argument): - char = directives.unicode_code(argument) - if len(char) > 1: - raise ValueError('%r invalid; must be a single character or ' - 'a Unicode code' % char) - return char - -def single_char_or_whitespace_or_unicode(argument): - if argument == 'tab': - char = '\t' - elif argument == 'space': - char = ' ' - else: - char = single_char_or_unicode(argument) - return char - -def positive_int(argument): - value = int(argument) - if value < 1: - raise ValueError('negative or zero value; must be positive') - return value - -def positive_int_list(argument): - if ',' in argument: - entries = argument.split(',') - else: - entries = argument.split() - return [positive_int(entry) for entry in entries] - -csv_table.arguments = (0, 1, 1) -csv_table.options = {'header-rows': directives.nonnegative_int, - 'header': directives.unchanged, - 'widths': positive_int_list, - 'file': directives.path, - 'url': directives.path, - 'class': directives.class_option, - # field delimiter char - 'delim': single_char_or_whitespace_or_unicode, - # text field quote/unquote char: - 'quote': single_char_or_unicode, - # char used to escape delim & quote as-needed: - 'escape': single_char_or_unicode,} -csv_table.content = 1 - -directives.register_directive('csvtable', csv_table) diff --git a/sandbox/dpriest/csvtable/csvtable.txt b/sandbox/dpriest/csvtable/csvtable.txt deleted file mode 100644 index 11c3d0f6b..000000000 --- a/sandbox/dpriest/csvtable/csvtable.txt +++ /dev/null @@ -1,93 +0,0 @@ -.. _csvtable: - -CSV Table -========= - -:Directive Type: "csvtable" -:Doctree Element: table -:Directive Arguments: 1, optional (table title). -:Directive Options: Possible. -:Directive Content: A CSV (comma-separated values) table. - -The "csvtable" directive is used to create a table from CSV -(comma-separated values) data. CSV is a common data format generated -by spreadsheet applications and commercial databases. - -Example:: - - .. csvtable:: Frozen Delights! - :headers: "Treat", "Quantity", "Description" - :widths: 15, 10, 30 - - "Albatross", 2.99, "On a stick!" - "Crunchy Frog", 1.49, "If we took the bones out, it wouldn't be - crunchy, now would it?" - "Gannet Ripple", 1.99, "On a stick!" - -Block markup and inline markup within cells is supported. Line ends -are recognized within cells. - -Working Limitations:: - -* Whitespace delimiters are supported only for external CSV files. - -* There is no support for checking that the number of columns in each - row is the same. However, this directive supports CSV generators - that do not insert "empty" entries at the end of short rows, by - automatically adding empty entries. - - .. Add "strict" option to verify input? - -* Due to limitations of the CSV parser, this directive is not Unicode - compatible. It may also have problems with ASCII NUL characters. - Accordingly, CSV tables should be ASCII-printable safe. - - .. Test with Unicode; see if that's really so. "encoding" option? - -The following options are recognized: - -``class`` : text - Set a "class" attribute value on the table element. See the - class_ directive below. - -``widths`` : integer [, integer...] - A comma-separated list of relative column widths. The default is - equal-width columns (100%/#columns). - -``header-rows`` : integer - The number of rows of CSV data to use in the table header. - Defaults to 0. - -``header`` : CSV data - Supplemental data for the table header, added independently of and - before any ``header-rows`` from the main CSV data. Must use the - same CSV format as the main CSV data. - -``file`` | ``url`` : path - Path or URL to CSV file. - -``delim`` : char | "tab" | "space" - A one-character string used to separate fields. Defaults to ``,`` - (comma). May be specified as a Unicode code point; see the - unicode_ directive for syntax details. - -``quote`` : char - A one-character string used to quote elements containing the - delimiter or which start with the quote character. Defaults to - ``"`` (quote). May be specified as a Unicode code point; see the - unicode_ directive for syntax details. - -``keepspace`` : flag - Treat whitespace immediately following the delimiter as - significant. The default is to ignore such whitespace. - -``escape`` : char - A one-character string used to escape the delimiter or quote - characters. May be specified as a Unicode code point; see the - unicode_ directive for syntax details. Used when the delimiter is - used in an unquoted field, or when quote characters are used - within a field. The default is to double-up the character, - e.g. "He said, ""Hi!""" - - .. Add another possible value, "double", to explicitly indicate - the default case? |