[kupfer] plugin.calculator: Try to fix paranthesis deficit in expressions



commit f0b79b6c89262b676b9fc75d9d237414621b28b5
Author: Ulrik Sverdrup <ulrik sverdrup gmail com>
Date:   Sun Nov 8 15:47:35 2009 +0100

    plugin.calculator: Try to fix paranthesis deficit in expressions
    
    When given an expression like "log(2" we try to be smart and add the
    missing brackets at the end of the expression.
    
    I can't think of this breaking anything at all, except paranteses
    inside string literals, but we don't support any way to use string
    literals at all. (You *can* do math with string literals and this
    example will fail with new code: '"(".count("(")' -- should return 1,
    but is really bogus.)

 kupfer/plugin/calculator.py |    8 ++++++++
 1 files changed, 8 insertions(+), 0 deletions(-)
---
diff --git a/kupfer/plugin/calculator.py b/kupfer/plugin/calculator.py
index 3bf6f05..85f0bbd 100644
--- a/kupfer/plugin/calculator.py
+++ b/kupfer/plugin/calculator.py
@@ -38,6 +38,12 @@ class Calculate (Action):
 		return True
 	def activate(self, leaf):
 		expr = leaf.object.lstrip("= ")
+
+		# try to add missing parantheses
+		brackets_missing = expr.count("(") - expr.count(")")
+		if brackets_missing > 0:
+			expr += ")"*brackets_missing
+
 		environment = dict(math.__dict__)
 		environment.update(cmath.__dict__)
 		# define some constants missing
@@ -46,6 +52,8 @@ class Calculate (Action):
 		environment["kupfer"] = KupferSurprise("inf")
 		# make the builtins inaccessible
 		environment["__builtins__"] = {}
+
+		pretty.print_debug(__name__, "Evaluating", repr(expr))
 		try:
 			result = eval(expr, environment)
 			resultstr = format_result(result)



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]