porcupine
porcupine copied to clipboard
arithmetic expression evaluator
Currently doing homework where I have to calculate things like 25 % 7
and I'm typing them into python (lol yeah), would be easier to press magic key binding and have 25 % 7
in the file replaced by....
>>> 25 % 7
4
...replaced by 4
What would be your ideal magic key bind?
What are your parameters for when to do the evaluation?
Some kind of error message should appear if you try to evaluate something like asd + 1
. It doesn't matter what exactly the magic key binding is, but it must
- not be in use yet
- not be easy to press accidentally
- ideally somehow guessable, could e.g. involve letter A (arithmetic), M (math) or E (evaluate)
Command-A-E? As for the evaluation should I just use eval(typed_expression)
?
I don't like Command-A-E, because for us non-Mac users, it would become Ctrl+A+E and Ctrl+A already has a well-known meaning. It could be Alt+A+E or Alt+A or Alt+E though.
You can use eval()
if you first ensure that the expression is safe to evaluate, i.e. only contains numbers, parentheses, +
, -
and so on.
Even if you check the expression, eval()
has a downside: 0.1 + 0.2
evals to 0.30000000000000004
, and 2/6
evals to 0.3333333333333333
. For math homework, the expected outputs for those would be 0.3
and 1/3
. The plugin would still be better than nothing, and we can later switch to a custom evaluator if this ever becomes a problem (for some inspiration, maybe look at how ast.literal_eval()
is implemented).
The issue with alt, as we discussed previously, is that it also has special meaning on Mac. Command/Ctrl-E could work as there is nothing there to my knowledge. As for floating-point arithmetic precision errors the user can, in a plugin popup, choose a level of precision and the plugin can round to that level of precision. As for checking for safety a simple regex can check for letters and block the code if any is found. As for what line gets the treatment it would be easy to just do the current selected line but if multiple lines are selected how should this behave?
It shouldn't care about whether the selected expression is one line or multiple lines. For example, if you select the 4 lines inside the parentheses, it should become print(46)
(probably with 46 on a line of its own):
print(
1
+ 23
- 45
+ 67
)
Good to know. I'll write up a quick regex and work on the plugin 😄
@Akuli How can I get the current seletected text through porcupine and how do I add a keybind?
How can I get the current seletected text through porcupine
Once you have a FileTab
, you can do tab.textwidget.get("sel.first", "sel.last")
and how do I add a keybind?
To see how they work, take one of the existing key bindings in default_keybindings.tcl
and search for its name with git grep
.
In most cases the rounding errors can be solved with using Fractions instead of floats