Last active
December 17, 2015 17:29
-
-
Save felixrabe/5645996 to your computer and use it in GitHub Desktop.
Sublime Text 2 FelixCalculatorCommand { "keys": ["alt+c"], "command": "felix_calculator" }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sublime, sublime_plugin | |
from math import * | |
class FelixCalculatorCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
window = self.view.window() | |
window.show_input_panel('Enter operation and operand (e.g. +i, +20, sqrt(x), -, =):', '', | |
self.on_done, None, None) | |
def on_done(self, input_text): | |
edit = self.view.begin_edit('Felix Calculation') | |
try: | |
i = -1 | |
for sel in self.view.sel(): | |
i += 1 | |
selection_text = self.view.substr(sel) | |
result = None | |
if len(input_text) == 1: # replace selection by line of input_text | |
result = input_text * len(selection_text) | |
elif 'x' in input_text: # x is replaced by selection, then evaluated | |
expr = input_text.replace('x', selection_text) | |
else: # evaluate '(<selection>) <input>' (e.g. sel='2', inp='*3' yields '(2) *3' => '6') | |
expr = ('(%s) ' % selection_text) + input_text | |
if result is None: | |
try: | |
result = eval(expr) | |
except: | |
continue | |
self.view.replace(edit, sel, str(result)) | |
finally: | |
self.view.end_edit(edit) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment