From 80afbc646d77cb85c1a6b65c715d594ebe14aade 2014-06-04 22:45:47
From: Jonathan Frederic <jon.freder@gmail.com>
Date: 2014-06-04 22:45:47
Subject: [PATCH] Address comments

---

diff --git a/IPython/nbconvert/preprocessors/csshtmlheader.py b/IPython/nbconvert/preprocessors/csshtmlheader.py
index 8d102e0..3fd897f 100755
--- a/IPython/nbconvert/preprocessors/csshtmlheader.py
+++ b/IPython/nbconvert/preprocessors/csshtmlheader.py
@@ -4,6 +4,7 @@
 # Distributed under the terms of the Modified BSD License.
 import os
 import io
+import hashlib
 
 from IPython.utils import path
 from IPython.utils.traitlets import Unicode
@@ -17,6 +18,10 @@ class CSSHTMLHeaderPreprocessor(Preprocessor):
     highlight_class = Unicode('.highlight', config=True,
                               help="CSS highlight class identifier")
 
+    def __init__(self, *pargs, **kwargs):
+        Preprocessor.__init__(self, *pargs, **kwargs)
+        self._default_css_hash = None
+
     def preprocess(self, nb, resources):
         """Fetch and add CSS to the resource dictionary
 
@@ -53,22 +58,27 @@ class CSSHTMLHeaderPreprocessor(Preprocessor):
         with io.open(sheet_filename, encoding='utf-8') as f:
             header.append(f.read())
 
+        # Add pygments CSS
+        formatter = HtmlFormatter()
+        pygments_css = formatter.get_style_defs(self.highlight_class)
+        header.append(pygments_css)
+
         # Load the user's custom CSS and IPython's default custom CSS.  If they
         # differ, assume the user has made modifications to his/her custom CSS
         # and that we should inline it in the nbconvert output.
         profile_dir = resources['profile_dir']
         custom_css_filename = os.path.join(profile_dir, 'static', 'custom', 'custom.css')
         if os.path.isfile(custom_css_filename):
-            with io.open(custom_css_filename, encoding='utf-8') as f:
-                custom_css = f.read()
-            with io.open(os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', 'custom.css'), encoding='utf-8') as f:
-                default_css = f.read()
-            if custom_css != default_css:
-                header.append(custom_css)
-
-        # Add pygments CSS
-        formatter = HtmlFormatter()
-        pygments_css = formatter.get_style_defs(self.highlight_class)
-        header.append(pygments_css)
+            if self._default_css_hash is None:
+                self._default_css_hash = self._hash(os.path.join(DEFAULT_STATIC_FILES_PATH, 'custom', 'custom.css'))
+            if self._hash(custom_css_filename) != self._default_css_hash:
+                with io.open(custom_css_filename, encoding='utf-8') as f:
+                    header.append(f.read())
         return header
 
+    def _hash(self, filename):
+        """Compute the hash of a file."""
+        md5 = hashlib.md5()
+        with open(filename) as f:
+            md5.update(f.read())
+        return md5.digest()