##// END OF EJS Templates
rename call methods to transform and postprocess...
Paul Ivanov -
Show More
@@ -1,48 +1,48 b''
1 """
1 """
2 Contains CheeseTransformer
2 Contains CheeseTransformer
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2013, the IPython Development Team.
5 # Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 from ...transformers.base import Transformer
16 from ...transformers.base import Transformer
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Classes
19 # Classes
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 class CheeseTransformer(Transformer):
22 class CheeseTransformer(Transformer):
23 """
23 """
24 Adds a cheese tag to the resources object
24 Adds a cheese tag to the resources object
25 """
25 """
26
26
27
27
28 def __init__(self, **kw):
28 def __init__(self, **kw):
29 """
29 """
30 Public constructor
30 Public constructor
31 """
31 """
32 super(CheeseTransformer, self).__init__(**kw)
32 super(CheeseTransformer, self).__init__(**kw)
33
33
34
34
35 def call(self, nb, resources):
35 def transform(self, nb, resources):
36 """
36 """
37 Sphinx transformation to apply on each notebook.
37 Sphinx transformation to apply on each notebook.
38
38
39 Parameters
39 Parameters
40 ----------
40 ----------
41 nb : NotebookNode
41 nb : NotebookNode
42 Notebook being converted
42 Notebook being converted
43 resources : dictionary
43 resources : dictionary
44 Additional resources used in the conversion process. Allows
44 Additional resources used in the conversion process. Allows
45 transformers to pass variables into the Jinja engine.
45 transformers to pass variables into the Jinja engine.
46 """
46 """
47 resources['cheese'] = 'real'
47 resources['cheese'] = 'real'
48 return nb, resources
48 return nb, resources
@@ -1,35 +1,35 b''
1 """
1 """
2 Basic post processor
2 Basic post processor
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 #Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
8 #
8 #
9 #The full license is in the file COPYING.txt, distributed with this software.
9 #The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 from ..utils.base import NbConvertBase
16 from ..utils.base import NbConvertBase
17
17
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Classes
20 # Classes
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 class PostProcessorBase(NbConvertBase):
22 class PostProcessorBase(NbConvertBase):
23
23
24 def __call__(self, input):
24 def __call__(self, input):
25 """
25 """
26 See def call() ...
26 See def postprocess() ...
27 """
27 """
28 self.call(input)
28 self.postprocess(input)
29
29
30
30
31 def call(self, input):
31 def postprocess(self, input):
32 """
32 """
33 Post-process output from a writer.
33 Post-process output from a writer.
34 """
34 """
35 raise NotImplementedError('call')
35 raise NotImplementedError('postprocess')
@@ -1,60 +1,60 b''
1 """
1 """
2 Contains writer for writing nbconvert output to PDF.
2 Contains writer for writing nbconvert output to PDF.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 #Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
8 #
8 #
9 #The full license is in the file COPYING.txt, distributed with this software.
9 #The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import subprocess
16 import subprocess
17 import os
17 import os
18
18
19 from IPython.utils.traitlets import Integer, List, Bool
19 from IPython.utils.traitlets import Integer, List, Bool
20
20
21 from .base import PostProcessorBase
21 from .base import PostProcessorBase
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Classes
24 # Classes
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 class PDFPostProcessor(PostProcessorBase):
26 class PDFPostProcessor(PostProcessorBase):
27 """Writer designed to write to PDF files"""
27 """Writer designed to write to PDF files"""
28
28
29 iteration_count = Integer(3, config=True, help="""
29 iteration_count = Integer(3, config=True, help="""
30 How many times pdflatex will be called.
30 How many times pdflatex will be called.
31 """)
31 """)
32
32
33 command = List(["pdflatex", "{filename}"], config=True, help="""
33 command = List(["pdflatex", "{filename}"], config=True, help="""
34 Shell command used to compile PDF.""")
34 Shell command used to compile PDF.""")
35
35
36 verbose = Bool(False, config=True, help="""
36 verbose = Bool(False, config=True, help="""
37 Whether or not to display the output of the compile call.
37 Whether or not to display the output of the compile call.
38 """)
38 """)
39
39
40 def call(self, input):
40 def postprocess(self, input):
41 """
41 """
42 Consume and write Jinja output a PDF.
42 Consume and write Jinja output a PDF.
43 See files.py for more...
43 See files.py for more...
44 """
44 """
45 command = [c.format(filename=input) for c in self.command]
45 command = [c.format(filename=input) for c in self.command]
46 self.log.info("Building PDF: %s", command)
46 self.log.info("Building PDF: %s", command)
47 with open(os.devnull, 'rb') as null:
47 with open(os.devnull, 'rb') as null:
48 stdout = subprocess.PIPE if not self.verbose else None
48 stdout = subprocess.PIPE if not self.verbose else None
49 for index in range(self.iteration_count):
49 for index in range(self.iteration_count):
50 p = subprocess.Popen(command, stdout=stdout, stdin=null)
50 p = subprocess.Popen(command, stdout=stdout, stdin=null)
51 out, err = p.communicate()
51 out, err = p.communicate()
52 if p.returncode:
52 if p.returncode:
53 if self.verbose:
53 if self.verbose:
54 # verbose means I didn't capture stdout with PIPE,
54 # verbose means I didn't capture stdout with PIPE,
55 # so it's already been displayed and `out` is None.
55 # so it's already been displayed and `out` is None.
56 out = u''
56 out = u''
57 else:
57 else:
58 out = out.decode('utf-8', 'replace')
58 out = out.decode('utf-8', 'replace')
59 self.log.critical(u"PDF conversion failed: %s\n%s", command, out)
59 self.log.critical(u"PDF conversion failed: %s\n%s", command, out)
60 return
60 return
@@ -1,55 +1,55 b''
1 """
1 """
2 Contains postprocessor for serving nbconvert output.
2 Contains postprocessor for serving nbconvert output.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 #Copyright (c) 2013, the IPython Development Team.
5 #Copyright (c) 2013, the IPython Development Team.
6 #
6 #
7 #Distributed under the terms of the Modified BSD License.
7 #Distributed under the terms of the Modified BSD License.
8 #
8 #
9 #The full license is in the file COPYING.txt, distributed with this software.
9 #The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 import os
16 import os
17 import webbrowser
17 import webbrowser
18
18
19 from BaseHTTPServer import HTTPServer
19 from BaseHTTPServer import HTTPServer
20 from SimpleHTTPServer import SimpleHTTPRequestHandler
20 from SimpleHTTPServer import SimpleHTTPRequestHandler
21
21
22 from IPython.utils.traitlets import Bool
22 from IPython.utils.traitlets import Bool
23
23
24 from .base import PostProcessorBase
24 from .base import PostProcessorBase
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes
27 # Classes
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 class ServePostProcessor(PostProcessorBase):
29 class ServePostProcessor(PostProcessorBase):
30 """Post processor designed to serve files"""
30 """Post processor designed to serve files"""
31
31
32
32
33 open_in_browser = Bool(True, config=True,
33 open_in_browser = Bool(True, config=True,
34 help="""Set to False to deactivate
34 help="""Set to False to deactivate
35 the opening of the browser""")
35 the opening of the browser""")
36
36
37 def call(self, input):
37 def postprocess(self, input):
38 """
38 """
39 Simple implementation to serve the build directory.
39 Simple implementation to serve the build directory.
40 """
40 """
41
41
42 try:
42 try:
43 dirname, filename = os.path.split(input)
43 dirname, filename = os.path.split(input)
44 if dirname:
44 if dirname:
45 os.chdir(dirname)
45 os.chdir(dirname)
46 httpd = HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)
46 httpd = HTTPServer(('127.0.0.1', 8000), SimpleHTTPRequestHandler)
47 sa = httpd.socket.getsockname()
47 sa = httpd.socket.getsockname()
48 url = "http://" + sa[0] + ":" + str(sa[1]) + "/" + filename
48 url = "http://" + sa[0] + ":" + str(sa[1]) + "/" + filename
49 if self.open_in_browser:
49 if self.open_in_browser:
50 webbrowser.open(url, new=2)
50 webbrowser.open(url, new=2)
51 print("Serving your slides on " + url)
51 print("Serving your slides on " + url)
52 print("Use Control-C to stop this server.")
52 print("Use Control-C to stop this server.")
53 httpd.serve_forever()
53 httpd.serve_forever()
54 except KeyboardInterrupt:
54 except KeyboardInterrupt:
55 print("The server is shut down.")
55 print("The server is shut down.")
@@ -1,110 +1,110 b''
1 """
1 """
2 Module that re-groups transformer that would be applied to ipynb files
2 Module that re-groups transformer that would be applied to ipynb files
3 before going through the templating machinery.
3 before going through the templating machinery.
4
4
5 It exposes a convenient class to inherit from to access configurability.
5 It exposes a convenient class to inherit from to access configurability.
6 """
6 """
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Copyright (c) 2013, the IPython Development Team.
8 # Copyright (c) 2013, the IPython Development Team.
9 #
9 #
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11 #
11 #
12 # The full license is in the file COPYING.txt, distributed with this software.
12 # The full license is in the file COPYING.txt, distributed with this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from ..utils.base import NbConvertBase
19 from ..utils.base import NbConvertBase
20 from IPython.utils.traitlets import Bool
20 from IPython.utils.traitlets import Bool
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Classes and Functions
23 # Classes and Functions
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 class Transformer(NbConvertBase):
26 class Transformer(NbConvertBase):
27 """ A configurable transformer
27 """ A configurable transformer
28
28
29 Inherit from this class if you wish to have configurability for your
29 Inherit from this class if you wish to have configurability for your
30 transformer.
30 transformer.
31
31
32 Any configurable traitlets this class exposed will be configurable in profiles
32 Any configurable traitlets this class exposed will be configurable in profiles
33 using c.SubClassName.atribute=value
33 using c.SubClassName.atribute=value
34
34
35 you can overwrite :meth:`transform_cell` to apply a transformation independently on each cell
35 you can overwrite :meth:`transform_cell` to apply a transformation independently on each cell
36 or :meth:`call` if you prefer your own logic. See corresponding docstring for informations.
36 or :meth:`transform` if you prefer your own logic. See corresponding docstring for informations.
37
37
38 Disabled by default and can be enabled via the config by
38 Disabled by default and can be enabled via the config by
39 'c.YourTransformerName.enabled = True'
39 'c.YourTransformerName.enabled = True'
40 """
40 """
41
41
42 enabled = Bool(False, config=True)
42 enabled = Bool(False, config=True)
43
43
44 def __init__(self, **kw):
44 def __init__(self, **kw):
45 """
45 """
46 Public constructor
46 Public constructor
47
47
48 Parameters
48 Parameters
49 ----------
49 ----------
50 config : Config
50 config : Config
51 Configuration file structure
51 Configuration file structure
52 **kw : misc
52 **kw : misc
53 Additional arguments
53 Additional arguments
54 """
54 """
55
55
56 super(Transformer, self).__init__(**kw)
56 super(Transformer, self).__init__(**kw)
57
57
58
58
59 def __call__(self, nb, resources):
59 def __call__(self, nb, resources):
60 if self.enabled:
60 if self.enabled:
61 return self.call(nb,resources)
61 return self.transform(nb,resources)
62 else:
62 else:
63 return nb, resources
63 return nb, resources
64
64
65
65
66 def call(self, nb, resources):
66 def transform(self, nb, resources):
67 """
67 """
68 Transformation to apply on each notebook.
68 Transformation to apply on each notebook.
69
69
70 You should return modified nb, resources.
70 You should return modified nb, resources.
71 If you wish to apply your transform on each cell, you might want to
71 If you wish to apply your transform on each cell, you might want to
72 overwrite transform_cell method instead.
72 overwrite transform_cell method instead.
73
73
74 Parameters
74 Parameters
75 ----------
75 ----------
76 nb : NotebookNode
76 nb : NotebookNode
77 Notebook being converted
77 Notebook being converted
78 resources : dictionary
78 resources : dictionary
79 Additional resources used in the conversion process. Allows
79 Additional resources used in the conversion process. Allows
80 transformers to pass variables into the Jinja engine.
80 transformers to pass variables into the Jinja engine.
81 """
81 """
82 self.log.debug("Applying transform: %s", self.__class__.__name__)
82 self.log.debug("Applying transform: %s", self.__class__.__name__)
83 try :
83 try :
84 for worksheet in nb.worksheets:
84 for worksheet in nb.worksheets:
85 for index, cell in enumerate(worksheet.cells):
85 for index, cell in enumerate(worksheet.cells):
86 worksheet.cells[index], resources = self.transform_cell(cell, resources, index)
86 worksheet.cells[index], resources = self.transform_cell(cell, resources, index)
87 return nb, resources
87 return nb, resources
88 except NotImplementedError:
88 except NotImplementedError:
89 raise NotImplementedError('should be implemented by subclass')
89 raise NotImplementedError('should be implemented by subclass')
90
90
91
91
92 def transform_cell(self, cell, resources, index):
92 def transform_cell(self, cell, resources, index):
93 """
93 """
94 Overwrite if you want to apply a transformation on each cell. You
94 Overwrite if you want to apply a transformation on each cell. You
95 should return modified cell and resource dictionary.
95 should return modified cell and resource dictionary.
96
96
97 Parameters
97 Parameters
98 ----------
98 ----------
99 cell : NotebookNode cell
99 cell : NotebookNode cell
100 Notebook cell being processed
100 Notebook cell being processed
101 resources : dictionary
101 resources : dictionary
102 Additional resources used in the conversion process. Allows
102 Additional resources used in the conversion process. Allows
103 transformers to pass variables into the Jinja engine.
103 transformers to pass variables into the Jinja engine.
104 index : int
104 index : int
105 Index of the cell being processed
105 Index of the cell being processed
106 """
106 """
107
107
108 raise NotImplementedError('should be implemented by subclass')
108 raise NotImplementedError('should be implemented by subclass')
109 return cell, resources
109 return cell, resources
110
110
@@ -1,106 +1,106 b''
1 """Module that pre-processes the notebook for export to HTML.
1 """Module that pre-processes the notebook for export to HTML.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
4 # Copyright (c) 2013, the IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import io
16 import io
17
17
18 from pygments.formatters import HtmlFormatter
18 from pygments.formatters import HtmlFormatter
19
19
20 from IPython.utils import path
20 from IPython.utils import path
21
21
22 from .base import Transformer
22 from .base import Transformer
23
23
24 from IPython.utils.traitlets import Unicode
24 from IPython.utils.traitlets import Unicode
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Classes and functions
27 # Classes and functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class CSSHTMLHeaderTransformer(Transformer):
30 class CSSHTMLHeaderTransformer(Transformer):
31 """
31 """
32 Transformer used to pre-process notebook for HTML output. Adds IPython notebook
32 Transformer used to pre-process notebook for HTML output. Adds IPython notebook
33 front-end CSS and Pygments CSS to HTML output.
33 front-end CSS and Pygments CSS to HTML output.
34 """
34 """
35
35
36 header = []
36 header = []
37
37
38 highlight_class = Unicode('.highlight', config=True,
38 highlight_class = Unicode('.highlight', config=True,
39 help="CSS highlight class identifier")
39 help="CSS highlight class identifier")
40
40
41 def __init__(self, config=None, **kw):
41 def __init__(self, config=None, **kw):
42 """
42 """
43 Public constructor
43 Public constructor
44
44
45 Parameters
45 Parameters
46 ----------
46 ----------
47 config : Config
47 config : Config
48 Configuration file structure
48 Configuration file structure
49 **kw : misc
49 **kw : misc
50 Additional arguments
50 Additional arguments
51 """
51 """
52
52
53 super(CSSHTMLHeaderTransformer, self).__init__(config=config, **kw)
53 super(CSSHTMLHeaderTransformer, self).__init__(config=config, **kw)
54
54
55 if self.enabled :
55 if self.enabled :
56 self._regen_header()
56 self._regen_header()
57
57
58
58
59 def call(self, nb, resources):
59 def transform(self, nb, resources):
60 """Fetch and add CSS to the resource dictionary
60 """Fetch and add CSS to the resource dictionary
61
61
62 Fetch CSS from IPython and Pygments to add at the beginning
62 Fetch CSS from IPython and Pygments to add at the beginning
63 of the html files. Add this css in resources in the
63 of the html files. Add this css in resources in the
64 "inlining.css" key
64 "inlining.css" key
65
65
66 Parameters
66 Parameters
67 ----------
67 ----------
68 nb : NotebookNode
68 nb : NotebookNode
69 Notebook being converted
69 Notebook being converted
70 resources : dictionary
70 resources : dictionary
71 Additional resources used in the conversion process. Allows
71 Additional resources used in the conversion process. Allows
72 transformers to pass variables into the Jinja engine.
72 transformers to pass variables into the Jinja engine.
73 """
73 """
74
74
75 resources['inlining'] = {}
75 resources['inlining'] = {}
76 resources['inlining']['css'] = self.header
76 resources['inlining']['css'] = self.header
77
77
78 return nb, resources
78 return nb, resources
79
79
80
80
81 def _regen_header(self):
81 def _regen_header(self):
82 """
82 """
83 Fills self.header with lines of CSS extracted from IPython
83 Fills self.header with lines of CSS extracted from IPython
84 and Pygments.
84 and Pygments.
85 """
85 """
86
86
87 #Clear existing header.
87 #Clear existing header.
88 header = []
88 header = []
89
89
90 #Construct path to IPy CSS
90 #Construct path to IPy CSS
91 sheet_filename = os.path.join(path.get_ipython_package_dir(),
91 sheet_filename = os.path.join(path.get_ipython_package_dir(),
92 'html', 'static', 'style', 'style.min.css')
92 'html', 'static', 'style', 'style.min.css')
93
93
94 #Load style CSS file.
94 #Load style CSS file.
95 with io.open(sheet_filename, encoding='utf-8') as file:
95 with io.open(sheet_filename, encoding='utf-8') as file:
96 file_text = file.read()
96 file_text = file.read()
97 header.append(file_text)
97 header.append(file_text)
98
98
99 #Add pygments CSS
99 #Add pygments CSS
100 formatter = HtmlFormatter()
100 formatter = HtmlFormatter()
101 pygments_css = formatter.get_style_defs(self.highlight_class)
101 pygments_css = formatter.get_style_defs(self.highlight_class)
102 header.append(pygments_css)
102 header.append(pygments_css)
103
103
104 #Set header
104 #Set header
105 self.header = header
105 self.header = header
106
106
@@ -1,94 +1,94 b''
1 """Module that pre-processes the notebook for export via Reveal.
1 """Module that pre-processes the notebook for export via Reveal.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2013, the IPython Development Team.
4 # Copyright (c) 2013, the IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import urllib2
16 import urllib2
17
17
18 from .base import Transformer
18 from .base import Transformer
19 from IPython.utils.traitlets import Unicode, Bool
19 from IPython.utils.traitlets import Unicode, Bool
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Classes and functions
22 # Classes and functions
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 class RevealHelpTransformer(Transformer):
25 class RevealHelpTransformer(Transformer):
26
26
27 url_prefix = Unicode('//cdn.jsdelivr.net/reveal.js/2.4.0',
27 url_prefix = Unicode('//cdn.jsdelivr.net/reveal.js/2.4.0',
28 config=True,
28 config=True,
29 help="""If you want to use a local reveal.js library,
29 help="""If you want to use a local reveal.js library,
30 use 'url_prefix':'reveal.js' in your config object.""")
30 use 'url_prefix':'reveal.js' in your config object.""")
31
31
32 speaker_notes = Bool(False,
32 speaker_notes = Bool(False,
33 config=True,
33 config=True,
34 help="""If you want to use the speaker notes
34 help="""If you want to use the speaker notes
35 set this to True.""")
35 set this to True.""")
36
36
37 def call(self, nb, resources):
37 def transform(self, nb, resources):
38 """
38 """
39 Called once to 'transform' contents of the notebook.
39 Called once to 'transform' contents of the notebook.
40
40
41 Parameters
41 Parameters
42 ----------
42 ----------
43 nb : NotebookNode
43 nb : NotebookNode
44 Notebook being converted
44 Notebook being converted
45 resources : dictionary
45 resources : dictionary
46 Additional resources used in the conversion process. Allows
46 Additional resources used in the conversion process. Allows
47 transformers to pass variables into the Jinja engine.
47 transformers to pass variables into the Jinja engine.
48 """
48 """
49
49
50 for worksheet in nb.worksheets :
50 for worksheet in nb.worksheets :
51 for index, cell in enumerate(worksheet.cells):
51 for index, cell in enumerate(worksheet.cells):
52
52
53 #Make sure the cell has slideshow metadata.
53 #Make sure the cell has slideshow metadata.
54 cell.metadata.align_type = cell.get('metadata', {}).get('slideshow', {}).get('align_type', 'Left')
54 cell.metadata.align_type = cell.get('metadata', {}).get('slideshow', {}).get('align_type', 'Left')
55 cell.metadata.slide_type = cell.get('metadata', {}).get('slideshow', {}).get('slide_type', '-')
55 cell.metadata.slide_type = cell.get('metadata', {}).get('slideshow', {}).get('slide_type', '-')
56
56
57 #Get the slide type. If type is start of subslide or slide,
57 #Get the slide type. If type is start of subslide or slide,
58 #end the last subslide/slide.
58 #end the last subslide/slide.
59 if cell.metadata.slide_type in ['slide']:
59 if cell.metadata.slide_type in ['slide']:
60 worksheet.cells[index - 1].metadata.slide_helper = 'slide_end'
60 worksheet.cells[index - 1].metadata.slide_helper = 'slide_end'
61 if cell.metadata.slide_type in ['subslide']:
61 if cell.metadata.slide_type in ['subslide']:
62 worksheet.cells[index - 1].metadata.slide_helper = 'subslide_end'
62 worksheet.cells[index - 1].metadata.slide_helper = 'subslide_end'
63
63
64
64
65 if not isinstance(resources['reveal'], dict):
65 if not isinstance(resources['reveal'], dict):
66 resources['reveal'] = {}
66 resources['reveal'] = {}
67 resources['reveal']['url_prefix'] = self.url_prefix
67 resources['reveal']['url_prefix'] = self.url_prefix
68 resources['reveal']['notes_prefix'] = self.url_prefix
68 resources['reveal']['notes_prefix'] = self.url_prefix
69
69
70 cdn = 'http://cdn.jsdelivr.net/reveal.js/2.4.0'
70 cdn = 'http://cdn.jsdelivr.net/reveal.js/2.4.0'
71 local = 'local'
71 local = 'local'
72 html_path = 'plugin/notes/notes.html'
72 html_path = 'plugin/notes/notes.html'
73 js_path = 'plugin/notes/notes.js'
73 js_path = 'plugin/notes/notes.js'
74
74
75 html_infile = os.path.join(cdn, html_path)
75 html_infile = os.path.join(cdn, html_path)
76 js_infile = os.path.join(cdn, js_path)
76 js_infile = os.path.join(cdn, js_path)
77 html_outfile = os.path.join(local, html_path)
77 html_outfile = os.path.join(local, html_path)
78 js_outfile = os.path.join(local, js_path)
78 js_outfile = os.path.join(local, js_path)
79
79
80 if self.speaker_notes:
80 if self.speaker_notes:
81 if 'outputs' not in resources:
81 if 'outputs' not in resources:
82 resources['outputs'] = {}
82 resources['outputs'] = {}
83 resources['outputs'][html_outfile] = self.notes_helper(html_infile)
83 resources['outputs'][html_outfile] = self.notes_helper(html_infile)
84 resources['outputs'][js_outfile] = self.notes_helper(js_infile)
84 resources['outputs'][js_outfile] = self.notes_helper(js_infile)
85 resources['reveal']['notes_prefix'] = local
85 resources['reveal']['notes_prefix'] = local
86
86
87 return nb, resources
87 return nb, resources
88
88
89 def notes_helper(self, infile):
89 def notes_helper(self, infile):
90 """Helper function to get the content from an url."""
90 """Helper function to get the content from an url."""
91
91
92 content = urllib2.urlopen(infile).read()
92 content = urllib2.urlopen(infile).read()
93
93
94 return content
94 return content
@@ -1,264 +1,264 b''
1 """Module that allows custom Sphinx parameters to be set on the notebook and
1 """Module that allows custom Sphinx parameters to be set on the notebook and
2 on the 'other' object passed into Jinja. Called prior to Jinja conversion
2 on the 'other' object passed into Jinja. Called prior to Jinja conversion
3 process.
3 process.
4 """
4 """
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (c) 2013, the IPython Development Team.
6 # Copyright (c) 2013, the IPython Development Team.
7 #
7 #
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9 #
9 #
10 # The full license is in the file COPYING.txt, distributed with this software.
10 # The full license is in the file COPYING.txt, distributed with this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import print_function, absolute_import
17 from __future__ import print_function, absolute_import
18
18
19 # Stdlib imports
19 # Stdlib imports
20 import os.path
20 import os.path
21
21
22 # Used to set the default date to today's date
22 # Used to set the default date to today's date
23 from datetime import date
23 from datetime import date
24
24
25 # Third-party imports
25 # Third-party imports
26 # Needed for Pygments latex definitions.
26 # Needed for Pygments latex definitions.
27 from pygments.formatters import LatexFormatter
27 from pygments.formatters import LatexFormatter
28
28
29 # Our own imports
29 # Our own imports
30 # Configurable traitlets
30 # Configurable traitlets
31 from IPython.utils.traitlets import Unicode, Bool
31 from IPython.utils.traitlets import Unicode, Bool
32
32
33 # Needed to override transformer
33 # Needed to override transformer
34 from .base import (Transformer)
34 from .base import (Transformer)
35
35
36 from IPython.nbconvert.utils import console
36 from IPython.nbconvert.utils import console
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Classes and functions
39 # Classes and functions
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42 class SphinxTransformer(Transformer):
42 class SphinxTransformer(Transformer):
43 """
43 """
44 Sphinx utility transformer.
44 Sphinx utility transformer.
45
45
46 This transformer is used to set variables needed by the latex to build
46 This transformer is used to set variables needed by the latex to build
47 Sphinx stylized templates.
47 Sphinx stylized templates.
48 """
48 """
49
49
50 interactive = Bool(False, config=True, help="""
50 interactive = Bool(False, config=True, help="""
51 Allows you to define whether or not the Sphinx exporter will prompt
51 Allows you to define whether or not the Sphinx exporter will prompt
52 you for input during the conversion process. If this is set to false,
52 you for input during the conversion process. If this is set to false,
53 the author, version, release, date, and chapter_style traits should
53 the author, version, release, date, and chapter_style traits should
54 be set.
54 be set.
55 """)
55 """)
56
56
57 author = Unicode("Unknown Author", config=True, help="Author name")
57 author = Unicode("Unknown Author", config=True, help="Author name")
58
58
59 version = Unicode("", config=True, help="""
59 version = Unicode("", config=True, help="""
60 Version number
60 Version number
61 You can leave this blank if you do not want to render a version number.
61 You can leave this blank if you do not want to render a version number.
62 Example: "1.0.0"
62 Example: "1.0.0"
63 """)
63 """)
64
64
65 release = Unicode("", config=True, help="""
65 release = Unicode("", config=True, help="""
66 Release name
66 Release name
67 You can leave this blank if you do not want to render a release name.
67 You can leave this blank if you do not want to render a release name.
68 Example: "Rough Draft"
68 Example: "Rough Draft"
69 """)
69 """)
70
70
71 publish_date = Unicode("", config=True, help="""
71 publish_date = Unicode("", config=True, help="""
72 Publish date
72 Publish date
73 This is the date to render on the document as the publish date.
73 This is the date to render on the document as the publish date.
74 Leave this blank to default to todays date.
74 Leave this blank to default to todays date.
75 Example: "June 12, 1990"
75 Example: "June 12, 1990"
76 """)
76 """)
77
77
78 chapter_style = Unicode("Bjarne", config=True, help="""
78 chapter_style = Unicode("Bjarne", config=True, help="""
79 Sphinx chapter style
79 Sphinx chapter style
80 This is the style to use for the chapter headers in the document.
80 This is the style to use for the chapter headers in the document.
81 You may choose one of the following:
81 You may choose one of the following:
82 "Bjarne" (default)
82 "Bjarne" (default)
83 "Lenny"
83 "Lenny"
84 "Glenn"
84 "Glenn"
85 "Conny"
85 "Conny"
86 "Rejne"
86 "Rejne"
87 "Sonny" (used for international documents)
87 "Sonny" (used for international documents)
88 """)
88 """)
89
89
90 output_style = Unicode("notebook", config=True, help="""
90 output_style = Unicode("notebook", config=True, help="""
91 Nbconvert Ipython
91 Nbconvert Ipython
92 notebook input/output formatting style.
92 notebook input/output formatting style.
93 You may choose one of the following:
93 You may choose one of the following:
94 "simple (recommended for long code segments)"
94 "simple (recommended for long code segments)"
95 "notebook" (default)
95 "notebook" (default)
96 """)
96 """)
97
97
98 center_output = Bool(False, config=True, help="""
98 center_output = Bool(False, config=True, help="""
99 Optional attempt to center all output. If this is false, no additional
99 Optional attempt to center all output. If this is false, no additional
100 formatting is applied.
100 formatting is applied.
101 """)
101 """)
102
102
103 use_headers = Bool(True, config=True, help="""
103 use_headers = Bool(True, config=True, help="""
104 Whether not a header should be added to the document.
104 Whether not a header should be added to the document.
105 """)
105 """)
106
106
107 #Allow the user to override the title of the notebook (useful for
107 #Allow the user to override the title of the notebook (useful for
108 #fancy document titles that the file system doesn't support.)
108 #fancy document titles that the file system doesn't support.)
109 overridetitle = Unicode("", config=True, help="")
109 overridetitle = Unicode("", config=True, help="")
110
110
111
111
112 def call(self, nb, resources):
112 def transform(self, nb, resources):
113 """
113 """
114 Sphinx transformation to apply on each notebook.
114 Sphinx transformation to apply on each notebook.
115
115
116 Parameters
116 Parameters
117 ----------
117 ----------
118 nb : NotebookNode
118 nb : NotebookNode
119 Notebook being converted
119 Notebook being converted
120 resources : dictionary
120 resources : dictionary
121 Additional resources used in the conversion process. Allows
121 Additional resources used in the conversion process. Allows
122 transformers to pass variables into the Jinja engine.
122 transformers to pass variables into the Jinja engine.
123 """
123 """
124 # import sphinx here, so that sphinx is not a dependency when it's not used
124 # import sphinx here, so that sphinx is not a dependency when it's not used
125 import sphinx
125 import sphinx
126
126
127 # TODO: Add versatile method of additional notebook metadata. Include
127 # TODO: Add versatile method of additional notebook metadata. Include
128 # handling of multiple files. For now use a temporay namespace,
128 # handling of multiple files. For now use a temporay namespace,
129 # '_draft' to signify that this needs to change.
129 # '_draft' to signify that this needs to change.
130 if not isinstance(resources["sphinx"], dict):
130 if not isinstance(resources["sphinx"], dict):
131 resources["sphinx"] = {}
131 resources["sphinx"] = {}
132
132
133 if self.interactive:
133 if self.interactive:
134
134
135 # Prompt the user for additional meta data that doesn't exist currently
135 # Prompt the user for additional meta data that doesn't exist currently
136 # but would be usefull for Sphinx.
136 # but would be usefull for Sphinx.
137 resources["sphinx"]["author"] = self._prompt_author()
137 resources["sphinx"]["author"] = self._prompt_author()
138 resources["sphinx"]["version"] = self._prompt_version()
138 resources["sphinx"]["version"] = self._prompt_version()
139 resources["sphinx"]["release"] = self._prompt_release()
139 resources["sphinx"]["release"] = self._prompt_release()
140 resources["sphinx"]["date"] = self._prompt_date()
140 resources["sphinx"]["date"] = self._prompt_date()
141
141
142 # Prompt the user for the document style.
142 # Prompt the user for the document style.
143 resources["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style()
143 resources["sphinx"]["chapterstyle"] = self._prompt_chapter_title_style()
144 resources["sphinx"]["outputstyle"] = self._prompt_output_style()
144 resources["sphinx"]["outputstyle"] = self._prompt_output_style()
145
145
146 # Small options
146 # Small options
147 resources["sphinx"]["centeroutput"] = console.prompt_boolean("Do you want to center the output? (false)", False)
147 resources["sphinx"]["centeroutput"] = console.prompt_boolean("Do you want to center the output? (false)", False)
148 resources["sphinx"]["header"] = console.prompt_boolean("Should a Sphinx document header be used? (true)", True)
148 resources["sphinx"]["header"] = console.prompt_boolean("Should a Sphinx document header be used? (true)", True)
149 else:
149 else:
150
150
151 # Try to use the traitlets.
151 # Try to use the traitlets.
152 resources["sphinx"]["author"] = self.author
152 resources["sphinx"]["author"] = self.author
153 resources["sphinx"]["version"] = self.version
153 resources["sphinx"]["version"] = self.version
154 resources["sphinx"]["release"] = self.release
154 resources["sphinx"]["release"] = self.release
155
155
156 # Use todays date if none is provided.
156 # Use todays date if none is provided.
157 if self.publish_date:
157 if self.publish_date:
158 resources["sphinx"]["date"] = self.publish_date
158 resources["sphinx"]["date"] = self.publish_date
159 elif len(resources['metadata']['modified_date'].strip()) == 0:
159 elif len(resources['metadata']['modified_date'].strip()) == 0:
160 resources["sphinx"]["date"] = date.today().strftime("%B %-d, %Y")
160 resources["sphinx"]["date"] = date.today().strftime("%B %-d, %Y")
161 else:
161 else:
162 resources["sphinx"]["date"] = resources['metadata']['modified_date']
162 resources["sphinx"]["date"] = resources['metadata']['modified_date']
163
163
164 # Sphinx traitlets.
164 # Sphinx traitlets.
165 resources["sphinx"]["chapterstyle"] = self.chapter_style
165 resources["sphinx"]["chapterstyle"] = self.chapter_style
166 resources["sphinx"]["outputstyle"] = self.output_style
166 resources["sphinx"]["outputstyle"] = self.output_style
167 resources["sphinx"]["centeroutput"] = self.center_output
167 resources["sphinx"]["centeroutput"] = self.center_output
168 resources["sphinx"]["header"] = self.use_headers
168 resources["sphinx"]["header"] = self.use_headers
169
169
170 # Find and pass in the path to the Sphinx dependencies.
170 # Find and pass in the path to the Sphinx dependencies.
171 resources["sphinx"]["texinputs"] = os.path.realpath(os.path.join(sphinx.package_dir, "texinputs"))
171 resources["sphinx"]["texinputs"] = os.path.realpath(os.path.join(sphinx.package_dir, "texinputs"))
172
172
173 # Generate Pygments definitions for Latex
173 # Generate Pygments definitions for Latex
174 resources["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def()
174 resources["sphinx"]["pygment_definitions"] = self._generate_pygments_latex_def()
175
175
176 if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0):
176 if not (self.overridetitle == None or len(self.overridetitle.strip()) == 0):
177 resources['metadata']['name'] = self.overridetitle
177 resources['metadata']['name'] = self.overridetitle
178
178
179 # End
179 # End
180 return nb, resources
180 return nb, resources
181
181
182
182
183 def _generate_pygments_latex_def(self):
183 def _generate_pygments_latex_def(self):
184 """
184 """
185 Generate the pygments latex definitions that allows pygments
185 Generate the pygments latex definitions that allows pygments
186 to work in latex.
186 to work in latex.
187 """
187 """
188
188
189 return LatexFormatter().get_style_defs()
189 return LatexFormatter().get_style_defs()
190
190
191
191
192 def _prompt_author(self):
192 def _prompt_author(self):
193 """
193 """
194 Prompt the user to input an Author name
194 Prompt the user to input an Author name
195 """
195 """
196 return console.input("Author name: ")
196 return console.input("Author name: ")
197
197
198
198
199 def _prompt_version(self):
199 def _prompt_version(self):
200 """
200 """
201 prompt the user to enter a version number
201 prompt the user to enter a version number
202 """
202 """
203 return console.input("Version (ie ""1.0.0""): ")
203 return console.input("Version (ie ""1.0.0""): ")
204
204
205
205
206 def _prompt_release(self):
206 def _prompt_release(self):
207 """
207 """
208 Prompt the user to input a release name
208 Prompt the user to input a release name
209 """
209 """
210
210
211 return console.input("Release Name (ie ""Rough draft""): ")
211 return console.input("Release Name (ie ""Rough draft""): ")
212
212
213
213
214 def _prompt_date(self, resources):
214 def _prompt_date(self, resources):
215 """
215 """
216 Prompt the user to enter a date
216 Prompt the user to enter a date
217 """
217 """
218
218
219 if resources['metadata']['modified_date']:
219 if resources['metadata']['modified_date']:
220 default_date = resources['metadata']['modified_date']
220 default_date = resources['metadata']['modified_date']
221 else:
221 else:
222 default_date = date.today().strftime("%B %-d, %Y")
222 default_date = date.today().strftime("%B %-d, %Y")
223
223
224 user_date = console.input("Date (deafults to \"" + default_date + "\"): ")
224 user_date = console.input("Date (deafults to \"" + default_date + "\"): ")
225 if len(user_date.strip()) == 0:
225 if len(user_date.strip()) == 0:
226 user_date = default_date
226 user_date = default_date
227 return user_date
227 return user_date
228
228
229
229
230 def _prompt_output_style(self):
230 def _prompt_output_style(self):
231 """
231 """
232 Prompts the user to pick an IPython output style.
232 Prompts the user to pick an IPython output style.
233 """
233 """
234
234
235 # Dictionary of available output styles
235 # Dictionary of available output styles
236 styles = {1: "simple",
236 styles = {1: "simple",
237 2: "notebook"}
237 2: "notebook"}
238
238
239 #Append comments to the menu when displaying it to the user.
239 #Append comments to the menu when displaying it to the user.
240 comments = {1: "(recommended for long code segments)",
240 comments = {1: "(recommended for long code segments)",
241 2: "(default)"}
241 2: "(default)"}
242
242
243 return console.prompt_dictionary(styles, default_style=2, menu_comments=comments)
243 return console.prompt_dictionary(styles, default_style=2, menu_comments=comments)
244
244
245
245
246 def _prompt_chapter_title_style(self):
246 def _prompt_chapter_title_style(self):
247 """
247 """
248 Prompts the user to pick a Sphinx chapter style
248 Prompts the user to pick a Sphinx chapter style
249 """
249 """
250
250
251 # Dictionary of available Sphinx styles
251 # Dictionary of available Sphinx styles
252 styles = {1: "Bjarne",
252 styles = {1: "Bjarne",
253 2: "Lenny",
253 2: "Lenny",
254 3: "Glenn",
254 3: "Glenn",
255 4: "Conny",
255 4: "Conny",
256 5: "Rejne",
256 5: "Rejne",
257 6: "Sonny"}
257 6: "Sonny"}
258
258
259 #Append comments to the menu when displaying it to the user.
259 #Append comments to the menu when displaying it to the user.
260 comments = {1: "(default)",
260 comments = {1: "(default)",
261 6: "(for international documents)"}
261 6: "(for international documents)"}
262
262
263 return console.prompt_dictionary(styles, menu_comments=comments)
263 return console.prompt_dictionary(styles, menu_comments=comments)
264
264
@@ -1,12 +1,16 b''
1 =====================
1 =====================
2 Development version
2 Development version
3 =====================
3 =====================
4
4
5 This document describes in-flight development work.
5 This document describes in-flight development work.
6
6
7
7
8 Backwards incompatible changes
8 Backwards incompatible changes
9 ------------------------------
9 ------------------------------
10
10
11 * Python 2.6 and 3.2 are no longer supported: the minimum required
11 * Python 2.6 and 3.2 are no longer supported: the minimum required
12 Python versions are now 2.7 and 3.3.
12 Python versions are now 2.7 and 3.3.
13 * The `call` methods for nbconvert transformers has been renamed to
14 `transform`.
15 * The `call` methods of nbconvert post-processsors have been renamed to
16 `postprocess`.
General Comments 0
You need to be logged in to leave comments. Login now