Calculation of arithmetic expressions in a text editor

In his book “Interface: New Directions in the Design of Computer Systems”, Jeff Raskin describes the possibility of calculating arithmetic expressions directly in a text editor without having to run a calculator. Being inspired by this book, as well as by boo1ean 's articles “Translation of selected text from any language into Russian” and imitsuran “Fixing the keyboard layout a la Punto Switcher on bash”, I decided to write an implementation of this idea for Linux. As a result, we have a simple script called by a hotkey that calculates the selected arithmetic expressions, replacing them with the results of calculations.

Decision


The following packages are required for the script to work: xsel, xvkbd and bc. Install:

sudo aptitude install xsel xvkbd bc

Next, open any text editor and write:

#!/bin/sh
PRECISION=4;
SELECTION=$(xsel -o);
if [ $SELECTION = "" ]; then exit 1; fi
RESULT=$(echo "scale=$PRECISION;$SELECTION" | bc);
if [ $RESULT ]; then
	BUFFER=$(xsel -b);
	echo -n "$RESULT" | xsel -b -i;
	xvkbd -xsendevent -text "\[Control_L]\[v]"; 
	echo -n "$BUFFER" | xsel -b -i
fi


In the PRECISION variable, we indicate the accuracy of the decimal fraction (in the presented embodiment, 4 decimal places). In the SELECTION variable, write the selected arithmetic expression, and if the selection is not empty, then calculate its value using bc, write the result in the RESULT variable. If the result is not zero, then in the BUFFER variable we write the current contents of the clipboard, overwrite the contents of the clipboard with the result of the calculation and, using the xvkbd utility, paste Ctrl + V through emulation (since the calculated expression is selected, the insert will overwrite it with the result). We return the contents of the clipboard to the user.

We save the file, for example, under the name selcalc, give execute rights and transfer it to / usr / bin:

sudo chmod +x ./selcalc && sudo mv ./selcalc /usr/bin/

Assign a hotkey to run the script, for example Ctrl + Shift + C (I used the standard GNOME 2 tools).

Using


  • select arithmetic expression
  • press Ctrl + Shift + C
  • in place of the selected expression we see the result of the calculation


Advantages and disadvantages


+ Calculation of arithmetic expressions without the need to run a calculator
+ Support for complex expressions (in fact, any expressions that bc is able to calculate, including control of computation priorities, exponentiation, etc.)
- Does not work in text editors that do not support paste via Ctrl + V, crooked works in some editors (Mozilla Thunderbird, Skype)

Tested in Open Office, Sublime Text 2, gedit, Pidgin, Nautilus (in file rename mode).

The script can be downloaded from the link .

Also popular now: