Commits

Christoph Reller committed 0028429 Merge

Merged in judios/tikz (pull request #3)

Windows Support added

Comments (0)

Files changed (4)

     
     brew install poppler
 
+For **Windows** you will need to install this two packages:
+
+* `Xpdf package <http://www.foolabs.com/xpdf/download.html>`__
+* `NetPbm for Windows package <http://gnuwin32.sourceforge.net/packages/netpbm.htm>`__
+  
+  If you don't want to install these packages, you can use only the files nedded.
+  
+    From Xpdf
+
+    * ``pdftoppm`` 
+  
+    From NetPbm
+  
+    * ``pnmcrop.exe`` 
+    * ``pnmtopng.exe``
+    * ``libnetpbm10.dll``
+    * ``libpng13.dll``
+    * ``rgb.txt``
+
+    Put these files in one folder and add the folder to the system path. 
+
+    Also, you need to create a new system variable *RGBDEF=C:\\TikzSphinx\\rgb.txt* assuming you copy the files to the C:\\TikzSphinx folder.
+
+  Additional note to windows install: If using an earlier version of the extension, you may need to modify the tikz.py file. Line
+
+    .. code-block:: python
+
+      p1 = Popen(['pnmcrop', 'tikz-1.ppm'], stdout=PIPE, stderr=PIPE)
+
+    To:
+
+    .. code-block:: python
+
+      p1 = Popen(['pnmcrop', 'tikz-000001.ppm'], stdout=PIPE, stderr=PIPE) 
+
 Configuration
 -------------
 
   extensions = ['sphinxcontrib.tikz']
 
 Also in ``conf.py``, you have to specify the LaTeX preamble in the
-``latex_elements`` dictionary as::
+``latex_elements`` dictionary, adding the tikz package and any other package or library used by the tikz pictures as::
 
   latex_elements = {
   ‹...›
-  'preamble': '\\usepackage{tikz}',
+  'preamble': '''
+  \usepackage{tikz}
+  \usepackage{pgfplots}
+  \usetikzlibrary{arrows}
+  ''',
   ‹...›
   }
 
 if inside a ``\tikz`` macro.  Ti\ *k*\ Z options can be given at the start of
 the ``‹tikz code›``.
 
+Additionaly, the ``:include:`` option can be used to import an entire tikzpicture::
+
+  .. tikz::‹caption, potentially broken
+     across lines›
+     :libs: ‹tikz libraries›
+     :include: <filename>
+
 Examples
 ========
 
 An example role :tikz:`[thick] \node[draw] (a) {A}; \node[draw,dotted,right
 of=a] {B} edge[<-] (a);`
 
+Example of a plot imported from a file:
+
+.. tikz:: 
+  :libs: arrows
+  :include: NewGM-Armijo2.tikz
+
 Caveats
 =======
 

doc/NewGM-Armijo2.tikz

+% This file was created by Julian Diaz using matlab2tikz v0.2.3.
+
+% This file was created by matlab2tikz v0.2.3.
+% Copyright (c) 2008--2012, Nico Schlömer <nico.schloemer@gmail.com>
+% All rights reserved.
+% 
+% The latest updates can be retrieved from
+%   http://www.mathworks.com/matlabcentral/fileexchange/22022-matlab2tikz
+% where you can also make suggestions and rate matlab2tikz.
+% 
+% 
+% 
+\begin{tikzpicture}
+
+\begin{semilogyaxis}[%
+view={0}{90},
+width=4.52083333333333in,
+height=2.99614583333333in,
+scale only axis,
+xmin=0, xmax=18,
+xlabel={Function Evaluations},
+ymin=1e-010, ymax=1,
+yminorticks=true,
+ylabel={Relative Nonlinear Residual},
+title style={align=center},
+title={H-equation\\[1ex]N = 100, c =0.99},
+legend style={align=left}]
+\addplot [
+color=blue,
+solid,
+mark=o,
+mark options={solid}
+]
+coordinates{
+ (0,1)(3,0.28798484544991)(5,0.0618301452420546)(8,0.0125225466985096)(11,0.000376207583347761)(15,3.05717493695019e-007)(18,2.60735183987243e-009) 
+};
+\addlegendentry{Newton-Armijo};
+
+\addplot [
+color=red,
+solid
+]
+coordinates{
+ (0,1)(3,0.28798484544991)(5,0.0618301452420546)(8,0.0125225466985096)(11,0.000376207583347761)(15,3.05717493695019e-007)(18,2.60735183987243e-009) 
+};
+\addlegendentry{GMRES};
+
+\end{semilogyaxis}
+\end{tikzpicture}%
 
 # Additional stuff for the LaTeX preamble.
 'preamble': '''
+\usepackage{amsmath}
 \usepackage{tikz}
+\usepackage{pgfplots}
 \usetikzlibrary{arrows}
 ''',
 }

sphinxcontrib/tikz.py

 import posixpath
 import shutil
 import sys
+import codecs
+
 from os import path, getcwd, chdir, mkdir, system
 from string import Template
 from subprocess import Popen, PIPE, call
 
 from sphinx.util.compat import Directive
 
+_Win_ = sys.platform[0:3] == 'win'
+
 class TikzExtError(SphinxError):
     category = 'Tikz extension error'
 
     required_arguments = 0
     optional_arguments = 1
     final_argument_whitespace = True
-    option_spec = {'libs':directives.unchanged,'stringsubst':directives.flag}
+    option_spec = {'libs':directives.unchanged,'stringsubst':directives.flag, 'include':directives.unchanged}
 
     def run(self):
         node = tikz()
-        if not self.content:
+
+        node['include']=self.options.get('include', '')
+        if node['include'] != '':
+            env = self.state.document.settings.env
+            rel_filename, filename = env.relfn2path(node['include'])
+            env.note_dependency(rel_filename)
+            try:
+                fp = codecs.open(filename, 'r', 'utf-8')
+                try:
+                    node['tikz'] = '\n' + fp.read() + '\n'
+                finally:
+                    fp.close()
+            except (IOError, OSError):
+                return [self.state.document.reporter.warning(
+                    'External Tikz file %r not found or reading '
+                    'it failed' % filename, line=self.lineno)]
             node['caption'] = ''
-            node['tikz'] = '\n'.join(self.arguments)
+            if self.arguments:
+                node['caption'] = '\n'.join(self.arguments)
         else:
-            node['tikz'] = '\n'.join(self.content)
-            node['caption'] = '\n'.join(self.arguments)
+            if not self.content:
+                node['caption'] = ''
+                node['tikz'] = '\n'.join(self.arguments)
+            else:
+                node['tikz'] = '\n'.join(self.content)
+                node['caption'] = '\n'.join(self.arguments)
+        
         node['libs'] = self.options.get('libs', '')
         if 'stringsubst' in self.options:
             node['stringsubst'] = True
         else:
             node['stringsubst'] = False
+        if node['tikz'] == '':
+            return [self.state_machine.reporter.warning(
+                    'Ignoring "tikz" directive without content.',
+                    line=self.lineno)]
         return [node]
 
 DOC_HEAD = r'''
 \documentclass[12pt]{article}
 \usepackage[utf8]{inputenc}
+\usepackage{amsmath}
 \usepackage{tikz}
+\usepackage{pgfplots}
 \usetikzlibrary{%s}
 \pagestyle{empty}
 '''
 
 DOC_BODY = r'''
 \begin{document}
-\begin{tikzpicture}
 %s
-\end{tikzpicture}
 \end{document}
 '''
 
-def render_tikz(self,tikz,libs='',stringsubst=False):
+def render_tikz(self,node,libs='',stringsubst=False):
+    tikz = node['tikz']
     hashkey = tikz.encode('utf-8')
     fname = 'tikz-%s.png' % (sha(hashkey).hexdigest())
     relfn = posixpath.join(self.builder.imgpath, fname)
     latex += self.builder.config.tikz_latex_preamble
     if stringsubst:
         tikz = Template(tikz).substitute(wd=curdir.replace('\\','/'))
+    if node['include'] == '':
+        tikz = '\\begin{tikzpicture}\n' + tikz + '\n\\end{tikzpicture}'
     latex += DOC_BODY % tikz
     if isinstance(latex, unicode):
         latex = latex.encode('utf-8')
     # stdout, stderr = p1.communicate()
 
     try:
-        p = Popen(['pdftoppm', '-r', '120', '-singlefile', 'tikz.pdf', 'tikz'],
+        if _Win_:
+            p = Popen(['pdftoppm', '-r', '120', 'tikz.pdf', 'tikz'], 
+                  stdout=PIPE, stderr=PIPE)
+        else:
+            p = Popen(['pdftoppm', '-r', '120', '-singlefile', 'tikz.pdf', 'tikz'],
                   stdout=PIPE, stderr=PIPE)
     except OSError, e:
         if e.errno != ENOENT:   # No such file or directory
 
     elif self.builder.config.tikz_proc_suite == 'Netpbm':
         try:
-            p1 = Popen(['pnmcrop', 'tikz.ppm'], stdout=PIPE, stderr=PIPE)
+            if _Win_:
+                p1 = Popen(['pnmcrop', 'tikz-000001.ppm'], stdout=PIPE, stderr=PIPE)
+            else:
+                p1 = Popen(['pnmcrop', 'tikz.ppm'], stdout=PIPE, stderr=PIPE)
         except OSError, err:
             if err.errno != ENOENT:   # No such file or directory
                 raise
     libs = self.builder.config.tikz_tikzlibraries
     libs = libs.replace(' ', '').replace('\t', '').strip(', ')
     try:
-        fname = render_tikz(self,node['tikz'],libs);
+        fname = render_tikz(self,node,libs);
     except TikzExtError, exc:
         info = str(exc)[str(exc).find('!'):-1]
         sm = nodes.system_message(info, type='WARNING', level=2,
     libs = libs.replace(' ', '').replace('\t', '').strip(', ')
 
     try:
-        fname = render_tikz(self,node['tikz'],libs,node['stringsubst'])
+        fname = render_tikz(self,node,libs,node['stringsubst'])
     except TikzExtError, exc:
         info = str(exc)[str(exc).find('!'):-1]
         sm = nodes.system_message(info, type='WARNING', level=2,
     raise nodes.SkipNode
 
 def latex_visit_tikz(self, node):
+    if node['include'] != '':
+        begTikzPic = ''
+        endTikzPic = ''
+        node['tikz']=node['tikz'].replace('\r\n','\n')
+    else:
+        begTikzPic = '\\begin{tikzpicture}'
+        endTikzPic = '\\end{tikzpicture}'
+
     if node['caption']:
         if node['stringsubst']:
             node['tikz'] = node['tikz'] % {'wd': getcwd()}
-        latex = '\\begin{figure}[htp]\\centering\\begin{tikzpicture}' + \
-                node['tikz'] + '\\end{tikzpicture}' + '\\caption{' + \
+        latex = '\\begin{figure}[htp]\\centering' + begTikzPic + \
+                node['tikz'] + endTikzPic + '\\caption{' + \
                 self.encode(node['caption']).strip() + '}\\end{figure}'
     else:
-        latex = '\\begin{center}\\begin{tikzpicture}' + node['tikz'] + \
-            '\\end{tikzpicture}\\end{center}'
+        latex = '\\begin{center}' + begTikzPic + node['tikz'] + \
+            endTikzPic + '\\end{center}'
     self.body.append(latex)
 
 def depart_tikz(self,node):
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.