zsh-workers
 help / color / mirror / code / Atom feed
* Calculator function
@ 2001-07-27 10:59 Peter Stephenson
  2001-07-27 19:10 ` Bart Schaefer
  0 siblings, 1 reply; 7+ messages in thread
From: Peter Stephenson @ 2001-07-27 10:59 UTC (permalink / raw)
  To: Zsh hackers list

I keep meaning to add this.  Maybe someone has a better one somewhere?

Index: Doc/Zsh/contrib.yo
===================================================================
RCS file: /cvsroot/zsh/zsh/Doc/Zsh/contrib.yo,v
retrieving revision 1.12
diff -u -r1.12 contrib.yo
--- Doc/Zsh/contrib.yo	2001/07/20 13:04:51	1.12
+++ Doc/Zsh/contrib.yo	2001/07/27 10:57:27
@@ -786,6 +786,42 @@
 ifzman(above)\
 ifnzman((noderef(Utilities))).
 )
+findex(zcalc)
+item(tt(zcalc) [ var(expression) ... ])(
+A reasonably powerful calculator based on zsh's arithmetic evaluation
+facility.  The syntax is similar to that of formulae in most programming
+languages; see
+ifzman(the section `Arithmetic Evaluation' in zmanref(zshmisc))\
+ifnzman(noderef(Arithmetic Evaluation)) for details.  The mathematical
+library tt(zsh/mathfunc) will be loaded if it is available; see
+ifzman(the section `The zsh/mathfunc Module' in zmanref(zshmodules))\
+ifnzman(noderef(The zsh/mathfunc Module)).  The mathematical functions
+correspond to the raw system libraries, so trigonometric functions are
+evaluated using radians, and so on.
+
+Each line typed is evaluated as an expression.  The prompt shows a number,
+which corresponds to a positional parameter where the result of that
+calculation is stored.  For example, the result of the calculation on the
+line preceeded by `tt(4> )' is available as tt($4).  Full command line
+editing, including the history of previous calculations, is available.
+To exit, enter a blank line or type `tt(q)' on its own.
+
+If arguments are given to tt(zcalc) on start up, they are used to prime the
+first few positional parameters.  A visual indication of this is given when
+the calculator starts.
+
+The constants tt(PI) (3.14159...) and tt(E) (2.71828...) are provided.
+Parameter assignment is possible, but note that all parameters will be put
+into the global namespace.
+
+An extra facility is provided for changing the default output base.  Use,
+for example, `tt([#16])' to display hexadecimal output preceeded by an
+indication of the base, or `tt([##16])' just to display the raw number in
+the given base.  Bases themselves are always specified in decimal.
+`tt([#])' restores the normal output format.
+
+See the comments in the function for a few extra tips.
+)
 findex(zed)
 item(tt(zed) [ tt(-f) ] var(name))(
 This function uses the ZLE editor to edit a file or function.  It rebinds
Index: Functions/Misc/zcalc
===================================================================
RCS file: zcalc
diff -N zcalc
--- /dev/null	Thu May 24 22:33:05 2001
+++ zcalc	Fri Jul 27 03:57:27 2001
@@ -0,0 +1,142 @@
+#!/usr/local/bin/zsh -i
+#
+# Zsh calculator.  Understands most ordinary arithmetic expressions.
+# Line editing and history are available. A blank line or `q' quits.
+#
+# Runs as a script or a function.  If used as a function, the history
+# is remembered for reuse in a later call (and also currently in the
+# shell's own history).  There are various problems using this as a
+# script, so a function is recommended.
+#
+# The prompt shows a number for the current line.  The corresponding
+# result can be referred to with $<line-no>, e.g.
+#   1> 32 + 10
+#   42
+#   2> $1 ** 2
+#   1764
+# The set of remembered numbers is primed with anything given on the
+# command line.  For example,
+#   zcalc '2 * 16'
+#   1> 32                     # printed by function
+#   2> $1 + 2                 # typed by user
+#   34
+#   3> 
+# Here, 32 is stored as $1.  This works in the obvious way for any
+# number of arguments.
+#
+# If the mathfunc library is available, probably understands most system
+# mathematical functions.  The left parenthesis must be adjacent to the
+# end of the function name, to distinguish from shell parameters
+# (translation: to prevent the maintainers from having to write proper
+# lookahead parsing).  For example,
+#   1> sqrt(2)
+#   1.4142135623730951
+# is right, but `sqrt (2)' will give you an error.
+#
+# You can do things with parameters like
+#   1> pi = 4.0 * atan(1)
+# too.  These go into global parameters, so be careful.  You can declare
+# local variables, however:
+#   1> local pi
+# but note this can't appear on the same line as a calculation.  Don't
+# use the variables listed in the `local' and `integer' lines below
+# (translation: I can't be bothered to provide a sandbox).
+#
+# Some constants are already available: (case sensitive as always):
+#   PI     pi, i.e. 3.1415926545897931
+#   E      e, i.e. 2.7182818284590455
+#
+# You can also change the output base.
+#   1> [#16]
+#   1>
+# Changes the default output to hexadecimal with numbers preceded by `16#'.
+# Note the line isn't remembered.
+#   2> [##16]
+#   2>
+# Change the default output base to hexadecimal with no prefix.
+#   3> [#]
+# Reset the default output base.
+#
+# This is based on the builtin feature that you can change the output base
+# of a given expression.  For example,
+#   1> [##16]  32 + 20 / 2
+#   2A
+#   2> 
+# prints the result of the calculation in hexadecimal.
+#
+# You can't change the default input base, but the shell allows any small
+# integer as a base:
+#   1> 2#1111
+#   15
+#   2> [##13] 13#6 * 13#9
+#   42
+# and the standard C-like notation with a leading 0x for hexadecimal is
+# also understood.  However, leading 0 for octal is not understood --- it's
+# too confusing in a calculator.  Use 8#777 etc.
+#
+#
+# To do:
+# - separate zcalc history from shell history using arrays --- or allow
+#   zsh to switch internally to and from array-based history.
+# - allow setting number of decimal places for display, scientific notation, 
+#   etc.
+
+emulate -L zsh
+setopt extendedglob
+
+local line latest base defbase match mbegin mend
+integer num
+
+zmodload -i zsh/mathfunc 2>/dev/null
+
+# Supply some constants.
+float PI E
+(( PI = 4 * atan(1), E = exp(1) ))
+
+for (( num = 1; num <= $#; num++ )); do
+  # Make sure all arguments have been evaluated.
+  # The `$' before the second argv forces string rather than numeric
+  # substitution.
+  (( argv[$num] = $argv[$num] ))
+  print "$num> $argv[$num]"
+done
+
+while vared -chp "$num> " line; do
+  [[ -z $line ]] && break
+  # special cases
+  # Set default base if `[#16]' or `[##16]' etc. on its own.
+  # Unset it if `[#]' or `[##]'.
+  if [[ $line = (#b)[[:blank:]]#('[#'(\#|)(<->|)']')[[:blank:]]#(*) ]]; then
+    if [[ -z $match[4] ]]; then
+      if [[ -z $match[3] ]]; then
+	defbase=
+      else
+	defbase=$match[1]
+      fi
+      print -s -- $line
+      line=
+      continue
+    else
+      base=
+    fi
+  else
+    base=$defbase
+  fi
+  # Exit if `q' on its own.
+  [[ $line = [[:blank:]]#q[[:blank:]]# ]] && return 0
+
+  print -s -- $line
+  if [[ $line = [[:blank:]]#local([[:blank:]]##*|) ]]; then
+    eval $line
+  else
+    # Latest value is stored as a string, because it might be floating
+    # point or integer --- we don't know till after the evaluation, and
+    # arrays always store scalars anyway.
+    eval "latest=\$(( $base $line ))"
+    argv[num++]=$latest
+    print -- $latest
+  fi
+  line=
+done
+
+return 0

-- 
Peter Stephenson <pws@csr.com>                  Software Engineer
CSR Ltd., Unit 300, Science Park, Milton Road,
Cambridge, CB4 0XL, UK                          Tel: +44 (0)1223 392070


**********************************************************************
The information transmitted is intended only for the person or
entity to which it is addressed and may contain confidential 
and/or privileged material. 
Any review, retransmission, dissemination or other use of, or
taking of any action in reliance upon, this information by 
persons or entities other than the intended recipient is 
prohibited.  
If you received this in error, please contact the sender and 
delete the material from any computer.
**********************************************************************


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-27 10:59 Calculator function Peter Stephenson
@ 2001-07-27 19:10 ` Bart Schaefer
  2001-07-27 23:17   ` Peter Stephenson
  0 siblings, 1 reply; 7+ messages in thread
From: Bart Schaefer @ 2001-07-27 19:10 UTC (permalink / raw)
  To: Peter Stephenson, Zsh hackers list

On Jul 27, 11:59am, Peter Stephenson wrote:
> 
> I keep meaning to add this.  Maybe someone has a better one somewhere?

This is pretty nifty.  Questions as they pop into my head:

> +Each line typed is evaluated as an expression.  The prompt shows a number,
> +which corresponds to a positional parameter where the result of that
> +calculation is stored.  For example, the result of the calculation on the
> +line preceeded by `tt(4> )' is available as tt($4).

Why not have the prompt look like `$4= ' instead of `4> '?

> +# Line editing and history are available. A blank line or `q' quits.

Hrm, I'd rather that blank lines were just ignored ... I think ...

> +# To do:
> +# - separate zcalc history from shell history using arrays --- or allow
> +#   zsh to switch internally to and from array-based history.

I posted a function some while back that switches history contexts by
dumping the history to a file, then zeroing and restoring HISTSIZE.  I
can't seem to track it down just now ... there's something sort of like
it in zsh-users/3506.

What were you thinking of, here?

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Zsh: http://www.zsh.org | PHPerl Project: http://phperl.sourceforge.net   


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-27 19:10 ` Bart Schaefer
@ 2001-07-27 23:17   ` Peter Stephenson
  2001-07-27 23:26     ` Bart Schaefer
  0 siblings, 1 reply; 7+ messages in thread
From: Peter Stephenson @ 2001-07-27 23:17 UTC (permalink / raw)
  To: Zsh hackers list

"Bart Schaefer" wrote:
> > +Each line typed is evaluated as an expression.  The prompt shows a number,
> > +which corresponds to a positional parameter where the result of that
> > +calculation is stored.  For example, the result of the calculation on the
> > +line preceeded by `tt(4> )' is available as tt($4).
> 
> Why not have the prompt look like `$4= ' instead of `4> '?

Probably not having thought of it.  But possibly because I wanted it to
look a prompt, since it prefixes the formula rather than the result.  It
can be made configurable with some psvar trickery.  See patch.

(This should really be expanded so that the same prompt is used to show
parameters passed on the command line, which I haven't done yet.)

> > +# Line editing and history are available. A blank line or `q' quits.
> 
> Hrm, I'd rather that blank lines were just ignored ... I think ...

I didn't like the idea that `q' didn't just show the variable $q,
however (despite the double negative).  It's a good idea to make ^D end
of file --- the option -e to vared handles this properly, so I've added
that.  Maybe I can delete both the q and the empty line thing.
 
> > +# To do:
> > +# - separate zcalc history from shell history using arrays --- or allow
> > +#   zsh to switch internally to and from array-based history.
> 
> I posted a function some while back that switches history contexts by
> dumping the history to a file, then zeroing and restoring HISTSIZE.  I
> can't seem to track it down just now ... there's something sort of like
> it in zsh-users/3506.
> 
> What were you thinking of, here?

That function would probably be exactly what was needed.

The other proposal was that instead of using an invisible internal list
manipulated by the history code, the shell code would use an array
variable containing the lines and perhaps an index variable.  Zle would
manipulate the index to reflect the history setting, (or we could find
another way of doing this) but the function would be responsible for any
changes to the array and all the household management done in the usual
case by the history options

Index: Functions/Misc/zcalc
===================================================================
RCS file: /cvsroot/zsh/zsh/Functions/Misc/zcalc,v
retrieving revision 1.1
diff -u -r1.1 zcalc
--- Functions/Misc/zcalc	2001/07/27 11:34:46	1.1
+++ Functions/Misc/zcalc	2001/07/27 22:10:18
@@ -84,11 +84,13 @@
 emulate -L zsh
 setopt extendedglob
 
-local line latest base defbase match mbegin mend
+local line latest base defbase match mbegin mend psvar
 integer num
 
 zmodload -i zsh/mathfunc 2>/dev/null
 
+: ${ZCALCPROMPT="%1v> "}
+
 # Supply some constants.
 float PI E
 (( PI = 4 * atan(1), E = exp(1) ))
@@ -101,7 +103,8 @@
   print "$num> $argv[$num]"
 done
 
-while vared -chp "$num> " line; do
+psvar[1]=$num
+while vared -cehp "${(%)ZCALCPROMPT}" line; do
   [[ -z $line ]] && break
   # special cases
   # Set default base if `[#16]' or `[##16]' etc. on its own.
@@ -134,6 +137,7 @@
     # arrays always store scalars anyway.
     eval "latest=\$(( $base $line ))"
     argv[num++]=$latest
+    psvar[1]=$num
     print -- $latest
   fi
   line=
Index: Doc/Zsh/contrib.yo
===================================================================
RCS file: /cvsroot/zsh/zsh/Doc/Zsh/contrib.yo,v
retrieving revision 1.13
diff -u -r1.13 contrib.yo
--- Doc/Zsh/contrib.yo	2001/07/27 11:34:46	1.13
+++ Doc/Zsh/contrib.yo	2001/07/27 22:10:23
@@ -820,6 +820,12 @@
 the given base.  Bases themselves are always specified in decimal.
 `tt([#])' restores the normal output format.
 
+The prompt is configurable via the parameter tt(ZCALCPROMPT), which
+undergoes standard prompt expansion.  The index of the current entry is
+stored locally in the first element of the array tt(psvar), which can be
+referred to in tt(ZCALCPROMPT) as `tt(%1v)'.  The default prompt is
+`tt(%1v> )'.
+
 See the comments in the function for a few extra tips.
 )
 findex(zed)

-- 
Peter Stephenson <pws@pwstephenson.fsnet.co.uk>
Work: pws@csr.com
Web: http://www.pwstephenson.fsnet.co.uk


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-27 23:17   ` Peter Stephenson
@ 2001-07-27 23:26     ` Bart Schaefer
  2001-07-29 21:52       ` Peter Stephenson
  0 siblings, 1 reply; 7+ messages in thread
From: Bart Schaefer @ 2001-07-27 23:26 UTC (permalink / raw)
  To: Zsh hackers list

On Jul 28, 12:17am, Peter Stephenson wrote:
> +while vared -cehp "${(%)ZCALCPROMPT}" line; do

Hrm, don't you want (%%) there?


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-27 23:26     ` Bart Schaefer
@ 2001-07-29 21:52       ` Peter Stephenson
  2001-07-30  0:58         ` Bart Schaefer
  0 siblings, 1 reply; 7+ messages in thread
From: Peter Stephenson @ 2001-07-29 21:52 UTC (permalink / raw)
  To: Zsh hackers list

"Bart Schaefer" wrote:
> On Jul 28, 12:17am, Peter Stephenson wrote:
> > +while vared -cehp "${(%)ZCALCPROMPT}" line; do
> 
> Hrm, don't you want (%%) there?

Couldn't really decide.  With that, you need to change the prompt if you
unset PROMPT_PERCENT.  I'm not sure it's good to force that on users of
a function.  Change it if you feel strongly.

-- 
Peter Stephenson <pws@pwstephenson.fsnet.co.uk>
Work: pws@csr.com
Web: http://www.pwstephenson.fsnet.co.uk


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-29 21:52       ` Peter Stephenson
@ 2001-07-30  0:58         ` Bart Schaefer
  2001-07-30  9:47           ` Peter Stephenson
  0 siblings, 1 reply; 7+ messages in thread
From: Bart Schaefer @ 2001-07-30  0:58 UTC (permalink / raw)
  To: Peter Stephenson, Zsh hackers list

On Jul 29, 10:52pm, Peter Stephenson wrote:
} Subject: Re: Calculator function
}
} "Bart Schaefer" wrote:
} > On Jul 28, 12:17am, Peter Stephenson wrote:
} > > +while vared -cehp "${(%)ZCALCPROMPT}" line; do
} > 
} > Hrm, don't you want (%%) there?
} 
} Couldn't really decide.  With that, you need to change the prompt if you
} unset PROMPT_PERCENT.

Hmhm.  Doesn't make that much difference to me, really, but why would it
be a big deal to `setopt localoptions promptpercent' within zcalc?  As it
stands, zcalc is ignoring the surrounding promptpercent setting anyway; it
just happens to also be ignoring the surrounding prompt(subst|bang).

} I'm not sure it's good to force that on users of a function.

Force what?

-- 
Bart Schaefer                                 Brass Lantern Enterprises
http://www.well.com/user/barts              http://www.brasslantern.com

Zsh: http://www.zsh.org | PHPerl Project: http://phperl.sourceforge.net   


^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: Calculator function
  2001-07-30  0:58         ` Bart Schaefer
@ 2001-07-30  9:47           ` Peter Stephenson
  0 siblings, 0 replies; 7+ messages in thread
From: Peter Stephenson @ 2001-07-30  9:47 UTC (permalink / raw)
  To: Zsh hackers list

Bart Schaefer wrote:
> On Jul 29, 10:52pm, Peter Stephenson wrote:
> Hmhm.  Doesn't make that much difference to me, really, but why would it
> be a big deal to `setopt localoptions promptpercent' within zcalc?

It wouldn't, given what I'm doing any.

> } I'm not sure it's good to force that on users of a function.
> 
> Force what?

The whole point is that this isn't part of the base shell and expecting
people to have to fiddle with its settings just because they are using
different options seems to me unnecessary.  So I was proposing the fixed
feature that it uses full prompt substitution; it uses zsh-specific
features in any case.  But it could be done a lot of different ways.

-- 
Peter Stephenson <pws@csr.com>                  Software Engineer
CSR Ltd., Unit 300, Science Park, Milton Road,
Cambridge, CB4 0XL, UK                          Tel: +44 (0)1223 392070


**********************************************************************
The information transmitted is intended only for the person or
entity to which it is addressed and may contain confidential 
and/or privileged material. 
Any review, retransmission, dissemination or other use of, or
taking of any action in reliance upon, this information by 
persons or entities other than the intended recipient is 
prohibited.  
If you received this in error, please contact the sender and 
delete the material from any computer.
**********************************************************************


^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2001-07-30  9:47 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2001-07-27 10:59 Calculator function Peter Stephenson
2001-07-27 19:10 ` Bart Schaefer
2001-07-27 23:17   ` Peter Stephenson
2001-07-27 23:26     ` Bart Schaefer
2001-07-29 21:52       ` Peter Stephenson
2001-07-30  0:58         ` Bart Schaefer
2001-07-30  9:47           ` Peter Stephenson

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).