# HG changeset patch
# User Jason Grout <jason.grout@drake.edu>
# Date 1309542233 18000
# Node ID 4897dc1aa08855a8fa8672e4c831e05d35af0dc7
# Parent 90cdc6a8ad4e4bed83142b4ca0e6c551acd73204
imported patch embedded.patch

diff --git a/sage/databases/sql_db.py b/sage/databases/sql_db.py
--- a/sage/databases/sql_db.py
+++ b/sage/databases/sql_db.py
@@ -352,6 +352,7 @@
     global p
     p = 0
     def row_str(row, html):
+        #TODO: 
         f = 0
         global p
         cur_str = []
@@ -359,10 +360,7 @@
             if index in pcol_index:
                 if html:
                     plot = pcol_map[p%len(pcol_map)](row[index])
-                    plot.save('%d.png'%p, figsize=[1,1])
-                    field_val = '     <td bgcolor=white align=center> ' \
-                        + '%s <br> <img src="cell://%d.png"> '%(row[index],p) \
-                        + '</td>\n'
+                    field_val = plot.show(figsize=[1,1])
                     p += 1
                 else:
                     raise NotImplementedError('Cannot display plot on ' \
@@ -376,26 +374,19 @@
                     f += 1
                 else:
                     field_val = row[index]
-                if html:
-                    field_val = '     <td bgcolor=white align=center> ' \
-                        + str(field_val) + ' </td>\n'
-                else:
+                if not html:
                     field_val = str(field_val).ljust(max_field_size)
             cur_str.append(field_val)
-        return ' '.join(cur_str)
+        if html:
+            return cur_str
+        else:
+            return ' '.join(cur_str)
 
-    from sage.server.support import EMBEDDED_MODE
-    if EMBEDDED_MODE or (kwds.has_key('html_table') and kwds['html_table']):
+    import sage.misc.misc as misc    
+    if misc.EMBEDDED_MODE or (kwds.has_key('html_table') and kwds['html_table']):
         # Notebook Version
-        ret = '<html><!--notruncate-->\n'
-        ret += '  <table bgcolor=lightgrey cellpadding=0>\n'
-        ret += '    <tr>\n      <td bgcolor=white align=center> '
-        ret += (' </td>\n      <td bgcolor=white ' \
-               + 'align=center> ').join(col_titles)
-        ret += ' </td>\n    </tr>\n'
-        ret += '\n'.join(['    <tr>\n ' + row_str(row, True) + '    </tr>' \
-               for row in cur])
-        ret += '\n  </table>\n</html>'
+        import html
+        ret = html.table_str([row_str(row,True) for row in cur], header=col_titles)
     else:
         # Command Prompt Version
         ret = ' '.join([col.ljust(max_field_size) for col in col_titles])
diff --git a/sage/graphs/graph_editor.py b/sage/graphs/graph_editor.py
--- a/sage/graphs/graph_editor.py
+++ b/sage/graphs/graph_editor.py
@@ -18,8 +18,6 @@
 from sage.misc.html import html
 
 import sagenb.notebook.interact
-from sagenb.misc.support import EMBEDDED_MODE
-
 
 def graph_to_js(g):
     """
@@ -103,8 +101,9 @@
     """
     if graph is None:
         graph = graphs.CompleteGraph(2)
-        
-    if not EMBEDDED_MODE:
+
+    import sage.misc.misc as misc    
+    if not misc.EMBEDDED_MODE:
         return "This graph editor only runs in the Sage notebook."
 
     graph.layout(save_pos = True, **layout_options)
diff --git a/sage/interfaces/maxima_abstract.py b/sage/interfaces/maxima_abstract.py
--- a/sage/interfaces/maxima_abstract.py
+++ b/sage/interfaces/maxima_abstract.py
@@ -158,7 +158,9 @@
             ...
         """
         cmd = 'maxima --very-quiet -r "%s(%s);" '%(command, s)
-        if sage.server.support.EMBEDDED_MODE:
+        
+        import sage.misc.misc as misc    
+        if misc.EMBEDDED_MODE:
             cmd += '< /dev/null'
 
         if redirect:
diff --git a/sage/interfaces/r.py b/sage/interfaces/r.py
--- a/sage/interfaces/r.py
+++ b/sage/interfaces/r.py
@@ -212,7 +212,7 @@
 ##########################################################################
 
 from expect import Expect, ExpectElement, ExpectFunction, FunctionElement
-from sage.misc.misc import DOT_SAGE
+from sage.misc.misc import EMBEDDED_MODE, DOT_SAGE
 import re
 import sage.rings.integer
 
@@ -363,7 +363,6 @@
         if "TRUE" not in s+t:
             raise RuntimeError, "R was not compiled with PNG support"
 
-        from sage.server.support import EMBEDDED_MODE
         if EMBEDDED_MODE:
             self.setwd('"%s"'%os.path.abspath('.'))
         return RFunction(self, 'png')(*args, **kwds)
@@ -714,8 +713,7 @@
             This is similar to typing r.command?. 
         """
         s = self.eval('help("%s")'%command).strip()     # ?cmd is only an unsafe shortcut
-        import sage.plot.plot
-        if sage.plot.plot.EMBEDDED_MODE:
+        if EMBEDDED_MODE:
             s = s.replace('_\x08','')
         return HelpExpression(s)
 
@@ -1034,7 +1032,6 @@
         """
         # We have to define this to override the plot function defined in the
         # superclass.
-        from sage.server.support import EMBEDDED_MODE
         if EMBEDDED_MODE:
             self.setwd('"%s"'%os.path.abspath('.'))
         RFunction(self, 'plot')(*args, **kwds)
diff --git a/sage/misc/hg.py b/sage/misc/hg.py
--- a/sage/misc/hg.py
+++ b/sage/misc/hg.py
@@ -73,7 +73,7 @@
 import os, shutil
 
 from   viewer import browser
-from   misc   import tmp_filename, branch_current_hg, embedded
+from   misc   import EMBEDDED_MODE, tmp_filename, branch_current_hg
 from   remote_file import get_remote_file as get_remote_file0
 from   sage.server.misc import print_open_msg
 from   subprocess import Popen
@@ -112,7 +112,7 @@
         '--config pager.pager=cat'
         sage: sage.server.support.EMBEDDED_MODE=False
     """
-    if embedded():
+    if EMBEDDED_MODE:
         return '--config pager.pager=cat'
     else:
         return '--config pager.pager="LESS=\'R\' less"'
@@ -852,7 +852,7 @@
             cd ... && sage --hg log   --config pager.pager="LESS='R' less"
             ...
         """
-        if embedded() and limit is None:
+        if EMBEDDED_MODE and limit is None:
             limit = 20
         options = ''
         if branches:
@@ -1504,7 +1504,7 @@
             sage: hg_sage.commit('hg.py', comment='miscellaneous fixes') # not tested
             cd ... && sage --hg commit -m "miscellaneous fixes" hg.py
         """
-        if embedded() and comment is None:
+        if EMBEDDED_MODE and comment is None:
             raise RuntimeError, "You're using the Sage notebook, so you *must* explicitly specify the comment in the commit command."
         if diff:
             self.diff(files)
diff --git a/sage/misc/html.py b/sage/misc/html.py
--- a/sage/misc/html.py
+++ b/sage/misc/html.py
@@ -171,7 +171,14 @@
             t += s[:i] + '<span class="math">%s</span>'%\
                      latex(sage_eval(s[6+i:j], locals=locals))
             s = s[j+7:] 
-        print "<html><font color='black'>%s</font></html>"%t
+
+        from sage.misc.misc import EMBEDDED_MODE
+        import sys
+        if EMBEDDED_MODE:
+            if EMBEDDED_MODE['frontend']=='notebook':
+                print "<html><font color='black'>%s</font></html>"%t
+            elif EMBEDDED_MODE['frontend']=='sagecell':
+                sys._sage_messages.message_queue.display({'text/html':"<font color='black'>%s</font>"%t})
         return ''
 
     def table(self, x, header = False):
@@ -238,7 +245,7 @@
             </table>
             </div>
             </html>
-
+ 
             sage: html.table([(x,n(sin(x), digits=2)) for x in [0..3]], header = ["$x$", "$\sin(x)$"])
             <html>
             <div class="notruncate">
@@ -270,9 +277,13 @@
             </html>
 
         """
+        print self.table_str(x, header=header)
+
+    def table_str(self, x, header):
         import types
         from sage.misc.all import latex
         from itertools import cycle
+        ret = ""
         if isinstance(x, types.GeneratorType):
             x = list(x)
         if isinstance(x, (list, tuple)):
@@ -280,24 +291,25 @@
             if rows > 0:
                 # if the table has less then 100 rows, don't truncate the output in the notebook
                 if rows <= 100:
-                    print "<html>\n<div class=\"notruncate\">\n<table class=\"table_form\">\n<tbody>"
+                    ret += "<html>\n<div class=\"notruncate\">\n<table class=\"table_form\">\n<tbody>"
                 else:
-                    print "<html>\n<div class=\"truncate\">\n<table class=\"table_form\">\n<tbody>"
+                    ret += "<html>\n<div class=\"truncate\">\n<table class=\"table_form\">\n<tbody>"
                 
                 if header is True:
                     header=x[0]
                     x = list(x[1:])
 
                 if header is not False:
-                    print "<tr>"
-                    self._table_columns(header, True)
-                    print "</tr>"
+                    ret += "<tr>"
+                    ret += self._table_columns(header, True)
+                    ret += "</tr>"
 
                 for row_class, row in zip(cycle(["row-a", "row-b"]), x):
-                    print "<tr class =\"%s\">" % row_class
-                    self._table_columns(row, False)
-                    print "</tr>"
-                print "</tbody>\n</table>\n</div>\n</html>"
+                    ret += "<tr class =\"%s\">" % row_class
+                    ret += self._table_columns(row, False)
+                    ret += "</tr>"
+                ret += "</tbody>\n</table>\n</div>\n</html>"
+        return ret
 
     def _table_columns(self, row, header=False):
         r"""
@@ -320,13 +332,16 @@
         elif not isinstance(row, (list, tuple)):
             row = [row]
 
+        ret = ""
         for column in xrange(len(row)):
             if isinstance(row[column], Graphics):
-                print column_tag % row[column].show(linkmode = True)
+                ret += column_tag % row[column].show(linkmode = True)
             elif isinstance(row[column], str):
-                print column_tag % math_parse(row[column])
+                ret += column_tag % math_parse(row[column])
             else:
-                print column_tag % ('<span class="math">%s</span>' % latex(row[column]))
+                ret += column_tag % ('<span class="math">%s</span>' % latex(row[column]))
+
+        return ret
 
     def iframe(self, url, height=400, width=800):
         r"""
diff --git a/sage/misc/latex.py b/sage/misc/latex.py
--- a/sage/misc/latex.py
+++ b/sage/misc/latex.py
@@ -16,8 +16,6 @@
 #*****************************************************************************
 
 
-EMBEDDED_MODE = False
-
 COMMON_HEADER = \
 r'''\usepackage{amsmath}
 \usepackage{amssymb}
@@ -56,6 +54,7 @@
 
 from misc import tmp_dir, graphics_filename
 import sage_eval
+from sage.misc.misc import EMBEDDED_MODE
 from sage.misc.sage_ostools import have_program
 from sage.misc.cachefunc import cached_function, cached_method
 
@@ -238,10 +237,10 @@
 
     TESTS::
 
-        sage: sage.misc.latex.EMBEDDED_MODE = True
+        sage: sage.misc.latex.EMBEDDED_MODE = {'frontend': 'notebook'}
         sage: builtin_constant_function(True)
         '{\\rm True}'
-        sage: sage.misc.latex.EMBEDDED_MODE = False
+        sage: sage.misc.latex.EMBEDDED_MODE = {}
     """
     if EMBEDDED_MODE:
         return "{\\rm %s}"%x
@@ -2055,7 +2054,7 @@
         Traceback (most recent call last):
         ...
         ValueError: Unsupported LaTeX engine.
-        sage: sage.misc.latex.EMBEDDED_MODE = True
+        sage: sage.misc.latex.EMBEDDED_MODE = {'frontend':'notebook'}
         sage: view(4, engine="garbage", viewer="pdf")
         Traceback (most recent call last):
         ...
diff --git a/sage/misc/misc.py b/sage/misc/misc.py
--- a/sage/misc/misc.py
+++ b/sage/misc/misc.py
@@ -47,6 +47,13 @@
 
 LOCAL_IDENTIFIER = '%s.%s'%(HOSTNAME , os.getpid())
 
+# EMBEDDED_MODE is a dictionary.  If Sage is embedded, this dictionary
+# is non-empty and EMBEDDED_MODE['frontend']='notebook' or 'sagecell'.
+# In the case of sagecell, another option will be set,
+# EMBEDDED_MODE['sage']=True/False, which specifies whether the
+# sage-mode is active or not.
+EMBEDDED_MODE={}
+
 def sage_makedirs(dir):
     """
     Python version of ``mkdir -p``: try to create a directory, and also
@@ -2161,19 +2168,6 @@
     """    
     return "0"*(size-len(str(s))) + str(s)
 
-import sage.server.support
-
-def embedded():
-    """
-    Return True if this copy of Sage is running embedded in the Sage
-    notebook.
-    
-    EXAMPLES::
-    
-        sage: sage.misc.misc.embedded()    # output True if in the notebook
-        False
-    """
-    return sage.server.support.EMBEDDED_MODE
 
 
 #############################################
diff --git a/sage/misc/pager.py b/sage/misc/pager.py
--- a/sage/misc/pager.py
+++ b/sage/misc/pager.py
@@ -15,12 +15,11 @@
 # Any code in sage that uses a pager should use this pager.
 
 
-EMBEDDED_MODE = False
-
 def cat(x):
     print x
 
 def pager():
+    from sage.misc.misc import EMBEDDED_MODE
     if EMBEDDED_MODE:
         return cat
     else:
diff --git a/sage/misc/sagedoc.py b/sage/misc/sagedoc.py
--- a/sage/misc/sagedoc.py
+++ b/sage/misc/sagedoc.py
@@ -36,7 +36,7 @@
 import os, re, sys
 import pydoc
 from sage.misc.viewer import browser
-from sage.misc.misc import SAGE_DOC, tmp_dir
+from sage.misc.misc import EMBEDDED_MODE, SAGE_DOC, tmp_dir
 from sagenb.misc.sphinxify import sphinxify
 import sage.version
 
@@ -827,7 +827,6 @@
     if not interact:
         return results
 
-    from sage.server.support import EMBEDDED_MODE
     if EMBEDDED_MODE:   # I.e., running from the notebook
         if multiline: # insert the colons that format_search_as_html expects
             results = ":\n".join(results.splitlines()) + ":"
@@ -1392,7 +1391,6 @@
         if testing:
             return (url, path)
 
-        from sage.server.support import EMBEDDED_MODE
         if EMBEDDED_MODE:
             os.system(browser() + " " + url)
         else:
diff --git a/sage/misc/sageinspect.py b/sage/misc/sageinspect.py
--- a/sage/misc/sageinspect.py
+++ b/sage/misc/sageinspect.py
@@ -128,7 +128,6 @@
 import functools
 import os
 import tokenize
-EMBEDDED_MODE = False
 
 def isclassinstance(obj):
     r"""
@@ -1139,7 +1138,8 @@
         # sometimes s contains "*args" or "**keywds", and the
         # asterisks confuse ReST/sphinx/docutils, so escape them:
         # change * to \*, and change ** to \**.
-        if EMBEDDED_MODE:
+        import sage.misc.misc as misc
+        if misc.EMBEDDED_MODE:
             s = s.replace('**', '\\**')  # replace ** with \**
             t = ''
             while True:  # replace * with \*
@@ -1256,13 +1256,14 @@
     - extensions by Nick Alexander
     """
     import sage.misc.sagedoc
+    import sage.misc.misc as misc
     if obj is None: return ''
     r = _sage_getdoc_unformatted(obj)
 
     if r is None:
         return ''
 
-    s = sage.misc.sagedoc.format(str(r), embedded=(embedded_override or EMBEDDED_MODE))
+    s = sage.misc.sagedoc.format(str(r), embedded=(embedded_override or misc.EMBEDDED_MODE))
 
     # If there is a Cython embedded position, it needs to be stripped
     pos = _extract_embedded_position(s)
diff --git a/sage/misc/session.pyx b/sage/misc/session.pyx
--- a/sage/misc/session.pyx
+++ b/sage/misc/session.pyx
@@ -65,7 +65,7 @@
 cdef caller_locals = __builtin__.locals
 
 # Sage imports
-from misc import embedded
+from sage.misc.misc import EMBEDDED_MODE
 from sage.structure.sage_object import load, save
 
 # This module-scope variables is used to save the 
@@ -299,7 +299,7 @@
                 print "Not saving %s: %s"%(k, msg)
             pass
     save(D, name)
-    if embedded():
+    if EMBEDDED_MODE:
         # Also save D to the data directory if we're using the notebook.
         save(D, '../../data/' + name)
 
@@ -341,7 +341,7 @@
     """
     state = caller_locals()
     
-    if embedded():
+    if EMBEDDED_MODE:
         if not os.path.exists(name):
             nm = '../../data/' + name
             if not nm.endswith('.sobj'): nm += '.sobj'
diff --git a/sage/misc/trace.py b/sage/misc/trace.py
--- a/sage/misc/trace.py
+++ b/sage/misc/trace.py
@@ -65,13 +65,13 @@
     
     We test what happens in notebook embedded mode::
     
-        sage: sage.plot.plot.EMBEDDED_MODE = True
-        sage: trace('print factor(10)')
+        sage: sage.misc.misc.EMBEDDED_MODE = {'frontend':'notebook'}
+        sage: trace('print factor(0)')
         Traceback (most recent call last):
         ...
         NotImplementedError: the trace command is not implemented in the Sage notebook; you must use the command line.
     """
-    from sage.plot.plot import EMBEDDED_MODE
+    from sage.misc.misc import EMBEDDED_MODE
     if EMBEDDED_MODE:
         raise NotImplementedError, "the trace command is not implemented in the Sage notebook; you must use the command line."
 
diff --git a/sage/plot/animate.py b/sage/plot/animate.py
--- a/sage/plot/animate.py
+++ b/sage/plot/animate.py
@@ -20,7 +20,7 @@
 from sage.structure.sage_object import SageObject
 
 import plot
-import sage.misc.misc
+import sage.misc.misc as misc
 import sage.misc.viewer
 
 class Animation(SageObject):
@@ -453,7 +453,7 @@
             self.gif(savefile=filename, delay=delay, iterations=iterations)
             return
         
-        if plot.EMBEDDED_MODE:
+        if misc.EMBEDDED_MODE:
             self.gif(delay = delay, iterations = iterations)
         else:
             filename = sage.misc.misc.tmp_filename() + '.gif'
diff --git a/sage/plot/plot.py b/sage/plot/plot.py
--- a/sage/plot/plot.py
+++ b/sage/plot/plot.py
@@ -343,7 +343,7 @@
 ## going to be used.
 
 #DEFAULT_FIGSIZE=(6, 3.70820393249937)
-EMBEDDED_MODE = False
+from sage.misc.misc import EMBEDDED_MODE
 DOCTEST_MODE = False
 import sage.misc.misc
 from sage.misc.misc import srange
diff --git a/sage/plot/plot3d/base.pyx b/sage/plot/plot3d/base.pyx
--- a/sage/plot/plot3d/base.pyx
+++ b/sage/plot/plot3d/base.pyx
@@ -821,7 +821,7 @@
         return box_min, box_max
 
     def _prepare_for_jmol(self, frame, axes, frame_aspect_ratio, aspect_ratio, zoom):
-        from sage.plot.plot import EMBEDDED_MODE
+        from sage.misc.misc import EMBEDDED_MODE
         if EMBEDDED_MODE:
             s = 6
         else:
@@ -1075,7 +1075,8 @@
         else:
             filename = sage.misc.misc.tmp_filename()
 
-        from sage.plot.plot import EMBEDDED_MODE, DOCTEST_MODE
+        from sage.plot.plot import DOCTEST_MODE
+        from sage.misc.misc import EMBEDDED_MODE
         ext = None
 
         # Tachyon resolution options
diff --git a/sage/plot/plot3d/tachyon.py b/sage/plot/plot3d/tachyon.py
--- a/sage/plot/plot3d/tachyon.py
+++ b/sage/plot/plot3d/tachyon.py
@@ -315,7 +315,7 @@
             filename = sage.misc.misc.graphics_filename()
             self.save(SAGE_TMP + '/test.png', verbose=verbose, extra_opts=extra_opts)
             return
-        if sage.plot.plot.EMBEDDED_MODE:
+        if sage.misc.misc.EMBEDDED_MODE:
             filename = sage.misc.misc.graphics_filename()
             self.save(filename, verbose=verbose, extra_opts=extra_opts)
             return
