Show More
@@ -30,6 +30,10 b' except ImportError:' | |||||
30 | from docutils.error_reporting import SafeString |
|
30 | from docutils.error_reporting import SafeString | |
31 |
|
31 | |||
32 | from IPython.nbformat import current as nbformat |
|
32 | from IPython.nbformat import current as nbformat | |
|
33 | import pypandoc | |||
|
34 | ||||
|
35 | # the ipython prompt regular expression | |||
|
36 | IPYPROMPT = re.compile(r"(?P<prompt>In \[[0-9]+\]:)(?P<code>.*)") | |||
33 |
|
37 | |||
34 |
|
38 | |||
35 | class Writer(writers.Writer): |
|
39 | class Writer(writers.Writer): | |
@@ -81,15 +85,28 b' class IPYNBTranslator(nodes.GenericNodeVisitor):' | |||||
81 | def add_cell(self, cell): |
|
85 | def add_cell(self, cell): | |
82 | self.nb.worksheets[0].cells.append(cell) |
|
86 | self.nb.worksheets[0].cells.append(cell) | |
83 |
|
87 | |||
|
88 | def add_code_cell(self, lines): | |||
|
89 | c = nbformat.new_code_cell(input='\n'.join(lines)) | |||
|
90 | self.add_cell(c) | |||
|
91 | ||||
84 | def visit_literal_block(self, node): |
|
92 | def visit_literal_block(self, node): | |
85 | raw_text = node.astext() |
|
93 | raw_text = node.astext() | |
86 | #only include lines that begin with >>> |
|
94 | current_cell = [] | |
87 | #we want the example code and not the example output |
|
95 | for line in raw_text.split('\n'): | |
88 | processed_text = '\n'.join([line.split('>>>')[1][1:] |
|
96 | ipyprompt = IPYPROMPT.match(line) | |
89 | for line in raw_text.split('\n') |
|
97 | # try matching the >>> prompt | |
90 |
|
|
98 | if line.startswith('>>>'): | |
91 | c = nbformat.new_code_cell(input=processed_text) |
|
99 | current_cell.append(line.split('>>>')[1][1:]) | |
92 | self.add_cell(c) |
|
100 | # try matching ipypromt | |
|
101 | elif ipyprompt is not None: | |||
|
102 | current_cell.append(ipyprompt.groupdict()['code'].strip()) | |||
|
103 | # some kind of output | |||
|
104 | elif current_cell: | |||
|
105 | self.add_code_cell(current_cell) | |||
|
106 | current_cell = [] | |||
|
107 | # if the last line was not output | |||
|
108 | if current_cell: | |||
|
109 | self.add_code_cell(current_cell) | |||
93 |
|
110 | |||
94 | def visit_paragraph(self, node): |
|
111 | def visit_paragraph(self, node): | |
95 | text = node.astext() |
|
112 | text = node.astext() |
General Comments 0
You need to be logged in to leave comments.
Login now