#@+leo-ver=4
#@+node:@file script_io_to_body.py
"""Send output from the Execute Script command to the end of the body pane"""

from leoPlugins import *
from leoGlobals import *

#@+others
#@+node:onStart
def onStart (tag,keywords):
	
	import leoFrame
	
	# Replace frame.put with newPut.
	funcToMethod(newExecuteScript,leoFrame.LeoFrame,"OnExecuteScript")
#@-node:onStart
#@+node:newExecuteScript
# Execute the _selected_ body text as a Python script and sends the output to the end of the body pane.

def newExecuteScript(self,event=None,v=None):
	
	c = self.commands ; body = self.body ; s = None
	if v == None:
		v = c.currentVnode() 

	# Assume any selected body text is a script.
	start,end = getTextSelection(body)
	if start and end and start != end: # 7/7/03
		s = body.get(start,end)
	else:
		s = ""
	s = s.strip()
	if s and len(s) > 0:
		s += '\n' # Make sure we end the script properly.
		try:
			# Switch output.
			import leoFrame,leoGlobals
			oldput = leoFrame.LeoFrame.put
			oldputnl = leoFrame.LeoFrame.putnl
			oldes = leoGlobals.es
			oldenl = leoGlobals.enl
			oldecnl = leoGlobals.ecnl
			oldecnls = leoGlobals.ecnls
			leoGlobals.es = newEs
			leoGlobals.enl = newEnl
			leoGlobals.ecnl = newEcnl
			leoGlobals.ecnls = newEcnls
			funcToMethod(newPut,leoFrame.LeoFrame,"put")
			funcToMethod(newPutNl,leoFrame.LeoFrame,"putNl")
			redirectStderr()
			redirectStdout()
			exec s in {} # Use {} to get a pristine environment!
			# Restore output.
			funcToMethod(oldput,leoFrame.LeoFrame,"put")
			funcToMethod(oldputnl,leoFrame.LeoFrame,"putNl")
			leoGlobals.es = oldes
			leoGlobals.enl = oldenl
			leoGlobals.ecnl = oldecnl
			leoGlobals.ecnls = oldecnls
			restoreStderr()
			restoreStdout()
		except:
			es("exception executing script")
			es_exception(full=false)
	else:
		es("no script selected")
#@-node:newExecuteScript
#@+node:newPut and newPutNl
# Same as frame.put except sends output to the end of the body text.
def newPut (self,s):
	if self.body:
			self.body.insert("end",s)
			# self.body.see("end")
			c = self.commands ; v = c.currentVnode()
			self.tree.onBodyChanged(v,"Typing")
	else: print s,

# Same as frame.putnl exceptsends output to the end of the body text.
def newPutNl (self):
	newPut (self,'\n')
#@nonl
#@-node:newPut and newPutNl
#@+node:newEs, etc.
def newEnl():
	print
	
def newEcnl():
	print
	
def newEcnls(n):
	while n > 0:
		n -= 1
		print

def newEs(s,*args,**keys):
	newline = keys.get("newline",true)
	if type(s) != type("") and type(s) != type(u""):
		s = repr(s)
	for arg in args:
		if type(arg) != type("") and type(arg) != type(u""):
			arg = repr(arg)
		s = s + ", " + arg
	if newline:
		print s
	else:
		print s,
#@-node:newEs, etc.
#@-others

if 0: # Register the handlers...
	registerHandler("start1", onStart)

	__version__ = "1.2" # Set version for the plugin handler.
	plugin_signon(__name__)
#@-node:@file script_io_to_body.py
#@-leo
