2007-01-16 01:29:18 +00:00
|
|
|
function math --description "Perform math calculations in bc"
|
2017-07-14 23:03:31 +00:00
|
|
|
if not set -q argv[2]
|
|
|
|
# Make sure an invocation like `math "-1 + 1"` doesn't treat the string as an option.
|
|
|
|
set argv -- $argv
|
|
|
|
end
|
|
|
|
|
|
|
|
set -l options 'h/help' 's/scale=' '#-val'
|
|
|
|
argparse -n math --stop-nonopt --min-args=1 $options -- $argv
|
2017-07-13 20:53:46 +00:00
|
|
|
or return
|
2016-05-03 03:53:48 +00:00
|
|
|
|
2017-07-13 20:53:46 +00:00
|
|
|
if set -q _flag_help
|
|
|
|
__fish_print_help math
|
|
|
|
return 0
|
2016-05-03 03:53:48 +00:00
|
|
|
end
|
|
|
|
|
2017-07-14 23:03:31 +00:00
|
|
|
set -l scale 0 # default is integer arithmetic
|
2017-07-13 20:53:46 +00:00
|
|
|
if set -q _flag_scale
|
|
|
|
set scale $_flag_scale
|
|
|
|
if not string match -q -r '^\d+$' "$scale"
|
|
|
|
printf (_ "%s: Expected an integer to follow --scale") math >&2
|
|
|
|
return 2 # missing argument is an error
|
|
|
|
end
|
2016-05-03 03:53:48 +00:00
|
|
|
end
|
|
|
|
|
2017-07-14 23:03:31 +00:00
|
|
|
if set -q _flag_val
|
|
|
|
# The expression began with a negative number. Put it back in the expression.
|
|
|
|
# The correct thing is for the person calling us to insert a `--` separator before the
|
|
|
|
# expression to stop parsing flags. But we'll work around that missing token here.
|
|
|
|
set argv -$_flag_val $argv
|
|
|
|
end
|
|
|
|
|
2016-12-29 14:13:48 +00:00
|
|
|
# Set BC_LINE_LENGTH to a ridiculously high number so it only uses one line for most results.
|
|
|
|
# We can't use 0 since some systems (including macOS) use an ancient bc that doesn't support it.
|
2017-01-09 02:31:55 +00:00
|
|
|
# We also can't count on this being recognized since some BSD systems don't recognize this env
|
|
|
|
# var at all and limit the line length to 70.
|
|
|
|
set -lx BC_LINE_LENGTH 500
|
2016-12-29 14:13:48 +00:00
|
|
|
set -l out (echo "scale=$scale; $argv" | bc)
|
2017-01-09 02:31:55 +00:00
|
|
|
if set -q out[2]
|
|
|
|
set out (string join '' (string replace \\ '' $out))
|
|
|
|
end
|
2016-05-03 03:53:48 +00:00
|
|
|
switch "$out"
|
|
|
|
case ''
|
|
|
|
# No output indicates an error occurred.
|
|
|
|
return 3
|
2006-11-17 16:24:38 +00:00
|
|
|
|
2016-05-03 03:53:48 +00:00
|
|
|
case 0
|
|
|
|
# For historical reasons a zero result translates to a failure status.
|
|
|
|
echo 0
|
|
|
|
return 1
|
2010-09-18 02:18:26 +00:00
|
|
|
|
2016-05-03 03:53:48 +00:00
|
|
|
case '*'
|
|
|
|
# For historical reasons a non-zero result translates to a success status.
|
|
|
|
echo $out
|
|
|
|
return 0
|
|
|
|
end
|
2006-09-04 16:00:23 +00:00
|
|
|
end
|