##// END OF EJS Templates
Allow validator to be called from reads_json and writes_json
Jessica B. Hamrick -
Show More
@@ -1,213 +1,223 b''
1 """The official API for working with notebooks in the current format version.
1 """The official API for working with notebooks in the current format version.
2
2
3 Authors:
3 Authors:
4
4
5 * Brian Granger
5 * Brian Granger
6 * Jonathan Frederic
6 * Jonathan Frederic
7 """
7 """
8
8
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2008-2011 The IPython Development Team
10 # Copyright (C) 2008-2011 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 from __future__ import print_function
20 from __future__ import print_function
21
21
22 from xml.etree import ElementTree as ET
22 from xml.etree import ElementTree as ET
23 import re
23 import re
24
24
25 from IPython.utils.py3compat import unicode_type
25 from IPython.utils.py3compat import unicode_type
26
26
27 from IPython.nbformat.v3 import (
27 from IPython.nbformat.v3 import (
28 NotebookNode,
28 NotebookNode,
29 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
29 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
30 parse_filename, new_metadata, new_author, new_heading_cell, nbformat,
30 parse_filename, new_metadata, new_author, new_heading_cell, nbformat,
31 nbformat_minor, to_notebook_json
31 nbformat_minor, nbformat_schema, to_notebook_json
32 )
32 )
33 from IPython.nbformat import v3 as _v_latest
33 from IPython.nbformat import v3 as _v_latest
34
34
35 from .reader import reads as reader_reads
35 from .reader import reads as reader_reads
36 from .reader import versions
36 from .reader import versions
37 from .convert import convert
37 from .convert import convert
38 from .validator import nbvalidate
38
39
39 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
40 # Code
41 # Code
41 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
42
43
43 current_nbformat = nbformat
44 current_nbformat = nbformat
44 current_nbformat_minor = nbformat_minor
45 current_nbformat_minor = nbformat_minor
45 current_nbformat_module = _v_latest.__name__
46 current_nbformat_module = _v_latest.__name__
46
47
48
47 def docstring_nbformat_mod(func):
49 def docstring_nbformat_mod(func):
48 """Decorator for docstrings referring to classes/functions accessed through
50 """Decorator for docstrings referring to classes/functions accessed through
49 nbformat.current.
51 nbformat.current.
50
52
51 Put {nbformat_mod} in the docstring in place of 'IPython.nbformat.v3'.
53 Put {nbformat_mod} in the docstring in place of 'IPython.nbformat.v3'.
52 """
54 """
53 func.__doc__ = func.__doc__.format(nbformat_mod=current_nbformat_module)
55 func.__doc__ = func.__doc__.format(nbformat_mod=current_nbformat_module)
54 return func
56 return func
55
57
56
58
57 class NBFormatError(ValueError):
59 class NBFormatError(ValueError):
58 pass
60 pass
59
61
60
62
61 def parse_py(s, **kwargs):
63 def parse_py(s, **kwargs):
62 """Parse a string into a (nbformat, string) tuple."""
64 """Parse a string into a (nbformat, string) tuple."""
63 nbf = current_nbformat
65 nbf = current_nbformat
64 nbm = current_nbformat_minor
66 nbm = current_nbformat_minor
65
67
66 pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>'
68 pattern = r'# <nbformat>(?P<nbformat>\d+[\.\d+]*)</nbformat>'
67 m = re.search(pattern,s)
69 m = re.search(pattern,s)
68 if m is not None:
70 if m is not None:
69 digits = m.group('nbformat').split('.')
71 digits = m.group('nbformat').split('.')
70 nbf = int(digits[0])
72 nbf = int(digits[0])
71 if len(digits) > 1:
73 if len(digits) > 1:
72 nbm = int(digits[1])
74 nbm = int(digits[1])
73
75
74 return nbf, nbm, s
76 return nbf, nbm, s
75
77
76
78
77 def reads_json(s, **kwargs):
79 def reads_json(s, **kwargs):
78 """Read a JSON notebook from a string and return the NotebookNode object."""
80 """Read a JSON notebook from a string and return the NotebookNode object."""
79 return convert(reader_reads(s), current_nbformat)
81 nbjson = reader_reads(s)
82 num_errors = nbvalidate(nbjson)
83 if num_errors > 0:
84 print("Num errors: %d" % num_errors)
85 return convert(nbjson, current_nbformat)
80
86
81
87
82 def writes_json(nb, **kwargs):
88 def writes_json(nb, **kwargs):
83 return versions[current_nbformat].writes_json(nb, **kwargs)
89 nbjson = versions[current_nbformat].writes_json(nb, **kwargs)
90 num_errors = nbvalidate(nbjson)
91 if num_errors > 0:
92 print("Num errors: %d" % num_errors)
93 return nbjson
84
94
85
95
86 def reads_py(s, **kwargs):
96 def reads_py(s, **kwargs):
87 """Read a .py notebook from a string and return the NotebookNode object."""
97 """Read a .py notebook from a string and return the NotebookNode object."""
88 nbf, nbm, s = parse_py(s, **kwargs)
98 nbf, nbm, s = parse_py(s, **kwargs)
89 if nbf in (2, 3):
99 if nbf in (2, 3):
90 nb = versions[nbf].to_notebook_py(s, **kwargs)
100 nb = versions[nbf].to_notebook_py(s, **kwargs)
91 else:
101 else:
92 raise NBFormatError('Unsupported PY nbformat version: %i' % nbf)
102 raise NBFormatError('Unsupported PY nbformat version: %i' % nbf)
93 return nb
103 return nb
94
104
95
105
96 def writes_py(nb, **kwargs):
106 def writes_py(nb, **kwargs):
97 # nbformat 3 is the latest format that supports py
107 # nbformat 3 is the latest format that supports py
98 return versions[3].writes_py(nb, **kwargs)
108 return versions[3].writes_py(nb, **kwargs)
99
109
100
110
101 # High level API
111 # High level API
102
112
103
113
104 def reads(s, format, **kwargs):
114 def reads(s, format, **kwargs):
105 """Read a notebook from a string and return the NotebookNode object.
115 """Read a notebook from a string and return the NotebookNode object.
106
116
107 This function properly handles notebooks of any version. The notebook
117 This function properly handles notebooks of any version. The notebook
108 returned will always be in the current version's format.
118 returned will always be in the current version's format.
109
119
110 Parameters
120 Parameters
111 ----------
121 ----------
112 s : unicode
122 s : unicode
113 The raw unicode string to read the notebook from.
123 The raw unicode string to read the notebook from.
114 format : (u'json', u'ipynb', u'py')
124 format : (u'json', u'ipynb', u'py')
115 The format that the string is in.
125 The format that the string is in.
116
126
117 Returns
127 Returns
118 -------
128 -------
119 nb : NotebookNode
129 nb : NotebookNode
120 The notebook that was read.
130 The notebook that was read.
121 """
131 """
122 format = unicode_type(format)
132 format = unicode_type(format)
123 if format == u'json' or format == u'ipynb':
133 if format == u'json' or format == u'ipynb':
124 return reads_json(s, **kwargs)
134 return reads_json(s, **kwargs)
125 elif format == u'py':
135 elif format == u'py':
126 return reads_py(s, **kwargs)
136 return reads_py(s, **kwargs)
127 else:
137 else:
128 raise NBFormatError('Unsupported format: %s' % format)
138 raise NBFormatError('Unsupported format: %s' % format)
129
139
130
140
131 def writes(nb, format, **kwargs):
141 def writes(nb, format, **kwargs):
132 """Write a notebook to a string in a given format in the current nbformat version.
142 """Write a notebook to a string in a given format in the current nbformat version.
133
143
134 This function always writes the notebook in the current nbformat version.
144 This function always writes the notebook in the current nbformat version.
135
145
136 Parameters
146 Parameters
137 ----------
147 ----------
138 nb : NotebookNode
148 nb : NotebookNode
139 The notebook to write.
149 The notebook to write.
140 format : (u'json', u'ipynb', u'py')
150 format : (u'json', u'ipynb', u'py')
141 The format to write the notebook in.
151 The format to write the notebook in.
142
152
143 Returns
153 Returns
144 -------
154 -------
145 s : unicode
155 s : unicode
146 The notebook string.
156 The notebook string.
147 """
157 """
148 format = unicode_type(format)
158 format = unicode_type(format)
149 if format == u'json' or format == u'ipynb':
159 if format == u'json' or format == u'ipynb':
150 return writes_json(nb, **kwargs)
160 return writes_json(nb, **kwargs)
151 elif format == u'py':
161 elif format == u'py':
152 return writes_py(nb, **kwargs)
162 return writes_py(nb, **kwargs)
153 else:
163 else:
154 raise NBFormatError('Unsupported format: %s' % format)
164 raise NBFormatError('Unsupported format: %s' % format)
155
165
156
166
157 def read(fp, format, **kwargs):
167 def read(fp, format, **kwargs):
158 """Read a notebook from a file and return the NotebookNode object.
168 """Read a notebook from a file and return the NotebookNode object.
159
169
160 This function properly handles notebooks of any version. The notebook
170 This function properly handles notebooks of any version. The notebook
161 returned will always be in the current version's format.
171 returned will always be in the current version's format.
162
172
163 Parameters
173 Parameters
164 ----------
174 ----------
165 fp : file
175 fp : file
166 Any file-like object with a read method.
176 Any file-like object with a read method.
167 format : (u'json', u'ipynb', u'py')
177 format : (u'json', u'ipynb', u'py')
168 The format that the string is in.
178 The format that the string is in.
169
179
170 Returns
180 Returns
171 -------
181 -------
172 nb : NotebookNode
182 nb : NotebookNode
173 The notebook that was read.
183 The notebook that was read.
174 """
184 """
175 return reads(fp.read(), format, **kwargs)
185 return reads(fp.read(), format, **kwargs)
176
186
177
187
178 def write(nb, fp, format, **kwargs):
188 def write(nb, fp, format, **kwargs):
179 """Write a notebook to a file in a given format in the current nbformat version.
189 """Write a notebook to a file in a given format in the current nbformat version.
180
190
181 This function always writes the notebook in the current nbformat version.
191 This function always writes the notebook in the current nbformat version.
182
192
183 Parameters
193 Parameters
184 ----------
194 ----------
185 nb : NotebookNode
195 nb : NotebookNode
186 The notebook to write.
196 The notebook to write.
187 fp : file
197 fp : file
188 Any file-like object with a write method.
198 Any file-like object with a write method.
189 format : (u'json', u'ipynb', u'py')
199 format : (u'json', u'ipynb', u'py')
190 The format to write the notebook in.
200 The format to write the notebook in.
191
201
192 Returns
202 Returns
193 -------
203 -------
194 s : unicode
204 s : unicode
195 The notebook string.
205 The notebook string.
196 """
206 """
197 return fp.write(writes(nb, format, **kwargs))
207 return fp.write(writes(nb, format, **kwargs))
198
208
199 def _convert_to_metadata():
209 def _convert_to_metadata():
200 """Convert to a notebook having notebook metadata."""
210 """Convert to a notebook having notebook metadata."""
201 import glob
211 import glob
202 for fname in glob.glob('*.ipynb'):
212 for fname in glob.glob('*.ipynb'):
203 print('Converting file:',fname)
213 print('Converting file:',fname)
204 with open(fname,'r') as f:
214 with open(fname,'r') as f:
205 nb = read(f,u'json')
215 nb = read(f,u'json')
206 md = new_metadata()
216 md = new_metadata()
207 if u'name' in nb:
217 if u'name' in nb:
208 md.name = nb.name
218 md.name = nb.name
209 del nb[u'name']
219 del nb[u'name']
210 nb.metadata = md
220 nb.metadata = md
211 with open(fname,'w') as f:
221 with open(fname,'w') as f:
212 write(nb, f, u'json')
222 write(nb, f, u'json')
213
223
@@ -1,74 +1,75 b''
1 """The main API for the v3 notebook format.
1 """The main API for the v3 notebook format.
2
2
3 Authors:
3 Authors:
4
4
5 * Brian Granger
5 * Brian Granger
6 """
6 """
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008-2011 The IPython Development Team
9 # Copyright (C) 2008-2011 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from .nbbase import (
19 from .nbbase import (
20 NotebookNode,
20 NotebookNode,
21 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
21 new_code_cell, new_text_cell, new_notebook, new_output, new_worksheet,
22 new_metadata, new_author, new_heading_cell, nbformat, nbformat_minor
22 new_metadata, new_author, new_heading_cell, nbformat, nbformat_minor,
23 nbformat_schema
23 )
24 )
24
25
25 from .nbjson import reads as reads_json, writes as writes_json
26 from .nbjson import reads as reads_json, writes as writes_json
26 from .nbjson import reads as read_json, writes as write_json
27 from .nbjson import reads as read_json, writes as write_json
27 from .nbjson import to_notebook as to_notebook_json
28 from .nbjson import to_notebook as to_notebook_json
28
29
29 from .nbpy import reads as reads_py, writes as writes_py
30 from .nbpy import reads as reads_py, writes as writes_py
30 from .nbpy import reads as read_py, writes as write_py
31 from .nbpy import reads as read_py, writes as write_py
31 from .nbpy import to_notebook as to_notebook_py
32 from .nbpy import to_notebook as to_notebook_py
32
33
33 from .convert import downgrade, upgrade
34 from .convert import downgrade, upgrade
34
35
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36 # Code
37 # Code
37 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
38
39
39 def parse_filename(fname):
40 def parse_filename(fname):
40 """Parse a notebook filename.
41 """Parse a notebook filename.
41
42
42 This function takes a notebook filename and returns the notebook
43 This function takes a notebook filename and returns the notebook
43 format (json/py) and the notebook name. This logic can be
44 format (json/py) and the notebook name. This logic can be
44 summarized as follows:
45 summarized as follows:
45
46
46 * notebook.ipynb -> (notebook.ipynb, notebook, json)
47 * notebook.ipynb -> (notebook.ipynb, notebook, json)
47 * notebook.json -> (notebook.json, notebook, json)
48 * notebook.json -> (notebook.json, notebook, json)
48 * notebook.py -> (notebook.py, notebook, py)
49 * notebook.py -> (notebook.py, notebook, py)
49 * notebook -> (notebook.ipynb, notebook, json)
50 * notebook -> (notebook.ipynb, notebook, json)
50
51
51 Parameters
52 Parameters
52 ----------
53 ----------
53 fname : unicode
54 fname : unicode
54 The notebook filename. The filename can use a specific filename
55 The notebook filename. The filename can use a specific filename
55 extention (.ipynb, .json, .py) or none, in which case .ipynb will
56 extention (.ipynb, .json, .py) or none, in which case .ipynb will
56 be assumed.
57 be assumed.
57
58
58 Returns
59 Returns
59 -------
60 -------
60 (fname, name, format) : (unicode, unicode, unicode)
61 (fname, name, format) : (unicode, unicode, unicode)
61 The filename, notebook name and format.
62 The filename, notebook name and format.
62 """
63 """
63 if fname.endswith(u'.ipynb'):
64 if fname.endswith(u'.ipynb'):
64 format = u'json'
65 format = u'json'
65 elif fname.endswith(u'.json'):
66 elif fname.endswith(u'.json'):
66 format = u'json'
67 format = u'json'
67 elif fname.endswith(u'.py'):
68 elif fname.endswith(u'.py'):
68 format = u'py'
69 format = u'py'
69 else:
70 else:
70 fname = fname + u'.ipynb'
71 fname = fname + u'.ipynb'
71 format = u'json'
72 format = u'json'
72 name = fname.split('.')[0]
73 name = fname.split('.')[0]
73 return fname, name, format
74 return fname, name, format
74
75
@@ -1,204 +1,206 b''
1 """The basic dict based notebook format.
1 """The basic dict based notebook format.
2
2
3 The Python representation of a notebook is a nested structure of
3 The Python representation of a notebook is a nested structure of
4 dictionary subclasses that support attribute access
4 dictionary subclasses that support attribute access
5 (IPython.utils.ipstruct.Struct). The functions in this module are merely
5 (IPython.utils.ipstruct.Struct). The functions in this module are merely
6 helpers to build the structs in the right form.
6 helpers to build the structs in the right form.
7 """
7 """
8
8
9 # Copyright (c) IPython Development Team.
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11
11
12 import pprint
12 import pprint
13 import uuid
13 import uuid
14 import os
14
15
15 from IPython.utils.ipstruct import Struct
16 from IPython.utils.ipstruct import Struct
16 from IPython.utils.py3compat import cast_unicode, unicode_type
17 from IPython.utils.py3compat import cast_unicode, unicode_type
17
18
18 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
19 # Code
20 # Code
20 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
21
22
22 # Change this when incrementing the nbformat version
23 # Change this when incrementing the nbformat version
23 nbformat = 3
24 nbformat = 3
24 nbformat_minor = 0
25 nbformat_minor = 0
26 nbformat_schema = 'v3.withref.json'
25
27
26 class NotebookNode(Struct):
28 class NotebookNode(Struct):
27 pass
29 pass
28
30
29
31
30 def from_dict(d):
32 def from_dict(d):
31 if isinstance(d, dict):
33 if isinstance(d, dict):
32 newd = NotebookNode()
34 newd = NotebookNode()
33 for k,v in d.items():
35 for k,v in d.items():
34 newd[k] = from_dict(v)
36 newd[k] = from_dict(v)
35 return newd
37 return newd
36 elif isinstance(d, (tuple, list)):
38 elif isinstance(d, (tuple, list)):
37 return [from_dict(i) for i in d]
39 return [from_dict(i) for i in d]
38 else:
40 else:
39 return d
41 return d
40
42
41
43
42 def new_output(output_type, output_text=None, output_png=None,
44 def new_output(output_type, output_text=None, output_png=None,
43 output_html=None, output_svg=None, output_latex=None, output_json=None,
45 output_html=None, output_svg=None, output_latex=None, output_json=None,
44 output_javascript=None, output_jpeg=None, prompt_number=None,
46 output_javascript=None, output_jpeg=None, prompt_number=None,
45 ename=None, evalue=None, traceback=None, stream=None, metadata=None):
47 ename=None, evalue=None, traceback=None, stream=None, metadata=None):
46 """Create a new output, to go in the ``cell.outputs`` list of a code cell.
48 """Create a new output, to go in the ``cell.outputs`` list of a code cell.
47 """
49 """
48 output = NotebookNode()
50 output = NotebookNode()
49 output.output_type = unicode_type(output_type)
51 output.output_type = unicode_type(output_type)
50
52
51 if metadata is None:
53 if metadata is None:
52 metadata = {}
54 metadata = {}
53 if not isinstance(metadata, dict):
55 if not isinstance(metadata, dict):
54 raise TypeError("metadata must be dict")
56 raise TypeError("metadata must be dict")
55 output.metadata = metadata
57 output.metadata = metadata
56
58
57 if output_type != 'pyerr':
59 if output_type != 'pyerr':
58 if output_text is not None:
60 if output_text is not None:
59 output.text = cast_unicode(output_text)
61 output.text = cast_unicode(output_text)
60 if output_png is not None:
62 if output_png is not None:
61 output.png = cast_unicode(output_png)
63 output.png = cast_unicode(output_png)
62 if output_jpeg is not None:
64 if output_jpeg is not None:
63 output.jpeg = cast_unicode(output_jpeg)
65 output.jpeg = cast_unicode(output_jpeg)
64 if output_html is not None:
66 if output_html is not None:
65 output.html = cast_unicode(output_html)
67 output.html = cast_unicode(output_html)
66 if output_svg is not None:
68 if output_svg is not None:
67 output.svg = cast_unicode(output_svg)
69 output.svg = cast_unicode(output_svg)
68 if output_latex is not None:
70 if output_latex is not None:
69 output.latex = cast_unicode(output_latex)
71 output.latex = cast_unicode(output_latex)
70 if output_json is not None:
72 if output_json is not None:
71 output.json = cast_unicode(output_json)
73 output.json = cast_unicode(output_json)
72 if output_javascript is not None:
74 if output_javascript is not None:
73 output.javascript = cast_unicode(output_javascript)
75 output.javascript = cast_unicode(output_javascript)
74
76
75 if output_type == u'pyout':
77 if output_type == u'pyout':
76 if prompt_number is not None:
78 if prompt_number is not None:
77 output.prompt_number = int(prompt_number)
79 output.prompt_number = int(prompt_number)
78
80
79 if output_type == u'pyerr':
81 if output_type == u'pyerr':
80 if ename is not None:
82 if ename is not None:
81 output.ename = cast_unicode(ename)
83 output.ename = cast_unicode(ename)
82 if evalue is not None:
84 if evalue is not None:
83 output.evalue = cast_unicode(evalue)
85 output.evalue = cast_unicode(evalue)
84 if traceback is not None:
86 if traceback is not None:
85 output.traceback = [cast_unicode(frame) for frame in list(traceback)]
87 output.traceback = [cast_unicode(frame) for frame in list(traceback)]
86
88
87 if output_type == u'stream':
89 if output_type == u'stream':
88 output.stream = 'stdout' if stream is None else cast_unicode(stream)
90 output.stream = 'stdout' if stream is None else cast_unicode(stream)
89
91
90 return output
92 return output
91
93
92
94
93 def new_code_cell(input=None, prompt_number=None, outputs=None,
95 def new_code_cell(input=None, prompt_number=None, outputs=None,
94 language=u'python', collapsed=False, metadata=None):
96 language=u'python', collapsed=False, metadata=None):
95 """Create a new code cell with input and output"""
97 """Create a new code cell with input and output"""
96 cell = NotebookNode()
98 cell = NotebookNode()
97 cell.cell_type = u'code'
99 cell.cell_type = u'code'
98 if language is not None:
100 if language is not None:
99 cell.language = cast_unicode(language)
101 cell.language = cast_unicode(language)
100 if input is not None:
102 if input is not None:
101 cell.input = cast_unicode(input)
103 cell.input = cast_unicode(input)
102 if prompt_number is not None:
104 if prompt_number is not None:
103 cell.prompt_number = int(prompt_number)
105 cell.prompt_number = int(prompt_number)
104 if outputs is None:
106 if outputs is None:
105 cell.outputs = []
107 cell.outputs = []
106 else:
108 else:
107 cell.outputs = outputs
109 cell.outputs = outputs
108 if collapsed is not None:
110 if collapsed is not None:
109 cell.collapsed = bool(collapsed)
111 cell.collapsed = bool(collapsed)
110 cell.metadata = NotebookNode(metadata or {})
112 cell.metadata = NotebookNode(metadata or {})
111
113
112 return cell
114 return cell
113
115
114 def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
116 def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
115 """Create a new text cell."""
117 """Create a new text cell."""
116 cell = NotebookNode()
118 cell = NotebookNode()
117 # VERSIONHACK: plaintext -> raw
119 # VERSIONHACK: plaintext -> raw
118 # handle never-released plaintext name for raw cells
120 # handle never-released plaintext name for raw cells
119 if cell_type == 'plaintext':
121 if cell_type == 'plaintext':
120 cell_type = 'raw'
122 cell_type = 'raw'
121 if source is not None:
123 if source is not None:
122 cell.source = cast_unicode(source)
124 cell.source = cast_unicode(source)
123 if rendered is not None:
125 if rendered is not None:
124 cell.rendered = cast_unicode(rendered)
126 cell.rendered = cast_unicode(rendered)
125 cell.metadata = NotebookNode(metadata or {})
127 cell.metadata = NotebookNode(metadata or {})
126 cell.cell_type = cell_type
128 cell.cell_type = cell_type
127 return cell
129 return cell
128
130
129
131
130 def new_heading_cell(source=None, rendered=None, level=1, metadata=None):
132 def new_heading_cell(source=None, rendered=None, level=1, metadata=None):
131 """Create a new section cell with a given integer level."""
133 """Create a new section cell with a given integer level."""
132 cell = NotebookNode()
134 cell = NotebookNode()
133 cell.cell_type = u'heading'
135 cell.cell_type = u'heading'
134 if source is not None:
136 if source is not None:
135 cell.source = cast_unicode(source)
137 cell.source = cast_unicode(source)
136 if rendered is not None:
138 if rendered is not None:
137 cell.rendered = cast_unicode(rendered)
139 cell.rendered = cast_unicode(rendered)
138 cell.level = int(level)
140 cell.level = int(level)
139 cell.metadata = NotebookNode(metadata or {})
141 cell.metadata = NotebookNode(metadata or {})
140 return cell
142 return cell
141
143
142
144
143 def new_worksheet(name=None, cells=None, metadata=None):
145 def new_worksheet(name=None, cells=None, metadata=None):
144 """Create a worksheet by name with with a list of cells."""
146 """Create a worksheet by name with with a list of cells."""
145 ws = NotebookNode()
147 ws = NotebookNode()
146 if name is not None:
148 if name is not None:
147 ws.name = cast_unicode(name)
149 ws.name = cast_unicode(name)
148 if cells is None:
150 if cells is None:
149 ws.cells = []
151 ws.cells = []
150 else:
152 else:
151 ws.cells = list(cells)
153 ws.cells = list(cells)
152 ws.metadata = NotebookNode(metadata or {})
154 ws.metadata = NotebookNode(metadata or {})
153 return ws
155 return ws
154
156
155
157
156 def new_notebook(name=None, metadata=None, worksheets=None):
158 def new_notebook(name=None, metadata=None, worksheets=None):
157 """Create a notebook by name, id and a list of worksheets."""
159 """Create a notebook by name, id and a list of worksheets."""
158 nb = NotebookNode()
160 nb = NotebookNode()
159 nb.nbformat = nbformat
161 nb.nbformat = nbformat
160 nb.nbformat_minor = nbformat_minor
162 nb.nbformat_minor = nbformat_minor
161 if worksheets is None:
163 if worksheets is None:
162 nb.worksheets = []
164 nb.worksheets = []
163 else:
165 else:
164 nb.worksheets = list(worksheets)
166 nb.worksheets = list(worksheets)
165 if metadata is None:
167 if metadata is None:
166 nb.metadata = new_metadata()
168 nb.metadata = new_metadata()
167 else:
169 else:
168 nb.metadata = NotebookNode(metadata)
170 nb.metadata = NotebookNode(metadata)
169 if name is not None:
171 if name is not None:
170 nb.metadata.name = cast_unicode(name)
172 nb.metadata.name = cast_unicode(name)
171 return nb
173 return nb
172
174
173
175
174 def new_metadata(name=None, authors=None, license=None, created=None,
176 def new_metadata(name=None, authors=None, license=None, created=None,
175 modified=None, gistid=None):
177 modified=None, gistid=None):
176 """Create a new metadata node."""
178 """Create a new metadata node."""
177 metadata = NotebookNode()
179 metadata = NotebookNode()
178 if name is not None:
180 if name is not None:
179 metadata.name = cast_unicode(name)
181 metadata.name = cast_unicode(name)
180 if authors is not None:
182 if authors is not None:
181 metadata.authors = list(authors)
183 metadata.authors = list(authors)
182 if created is not None:
184 if created is not None:
183 metadata.created = cast_unicode(created)
185 metadata.created = cast_unicode(created)
184 if modified is not None:
186 if modified is not None:
185 metadata.modified = cast_unicode(modified)
187 metadata.modified = cast_unicode(modified)
186 if license is not None:
188 if license is not None:
187 metadata.license = cast_unicode(license)
189 metadata.license = cast_unicode(license)
188 if gistid is not None:
190 if gistid is not None:
189 metadata.gistid = cast_unicode(gistid)
191 metadata.gistid = cast_unicode(gistid)
190 return metadata
192 return metadata
191
193
192 def new_author(name=None, email=None, affiliation=None, url=None):
194 def new_author(name=None, email=None, affiliation=None, url=None):
193 """Create a new author."""
195 """Create a new author."""
194 author = NotebookNode()
196 author = NotebookNode()
195 if name is not None:
197 if name is not None:
196 author.name = cast_unicode(name)
198 author.name = cast_unicode(name)
197 if email is not None:
199 if email is not None:
198 author.email = cast_unicode(email)
200 author.email = cast_unicode(email)
199 if affiliation is not None:
201 if affiliation is not None:
200 author.affiliation = cast_unicode(affiliation)
202 author.affiliation = cast_unicode(affiliation)
201 if url is not None:
203 if url is not None:
202 author.url = cast_unicode(url)
204 author.url = cast_unicode(url)
203 return author
205 return author
204
206
1 NO CONTENT: file renamed from IPython/nbformat/v3/validator.py to IPython/nbformat/validator.py
NO CONTENT: file renamed from IPython/nbformat/v3/validator.py to IPython/nbformat/validator.py
General Comments 0
You need to be logged in to leave comments. Login now