-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleMath.py
68 lines (55 loc) · 2.1 KB
/
simpleMath.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import sublime
import sublime_plugin
import re
import time
from . import pyperclip as clipboard
import math
class SimpleMathCommand(sublime_plugin.TextCommand):
def display(self, title, value):
# copy to clipboard and display operation result
if isinstance(value, float):
if value.is_integer():
value = int(value)
clipboard.copy(value)
sublime.status_message(' ' + title + ': ' + str(value) + " copied value to clipboard")
def getText(self):
# get highlighted text
sel = self.view.sel()[0]
if sel.begin() == sel.end():
return self.view.substr(sublime.Region(0, self.view.size()))
else:
return self.view.substr(sel)
def getNumbers(self):
text = self.getText()
result = re.findall(r'(\d+\.\d+|\d+)', text)
return [float(x) for x in result]
class SummCommand(SimpleMathCommand):
def run(self, edit):
# find summ of all numbers in text
numbers = self.getNumbers()
summ = sum(numbers)
self.display("Summ", summ)
class MultiplyCommand(SimpleMathCommand):
def run(self, edit):
# multiply all numbers in text
numbers = self.getNumbers()
multiplied = 1.0
for i in numbers:
multiplied*=i
self.display("Multiplied", multiplied)
class CalculateCommand(SimpleMathCommand):
def run(self, edit):
# calculate math expression
expression = self.getText()
# remove non mathematical symbols
expression = "".join(re.findall(r'(\d+\.\d+|\d+|\*|\/|\+|\-|\(|\))', expression))
# remove whitespaces
expression = re.sub(r' ', r'', expression)
# add multiply characters if needed
expression = re.sub(r'(\d)(\()', r'\1*\2', expression)
expression = re.sub(r'(\))(\d)', r'\1*\2', expression)
try:
result = eval(expression)
self.display("Result", result)
except Exception as e:
sublime.status_message(" ERROR: " + repr(e))