<chapter title="Introduction">

\Mathics---to be pronounced like "Mathematics" without the "emat"---is a general-purpose computer algebra system (CAS). It is meant to be a free, open-source alternative to \Mathematica. It is free both as in "free beer" and as in "freedom". Mathics can be run \Mathics locally, and to facilitate installation of the vast amount of software need to run this, there is a <url>:docker image available on dockerhub: https://hub.docker.com/r/mathicsorg/mathics</url>.

The programming language of \Mathics is meant to resemble the \Wolfram Language as much as possible. However, \Mathics is in no way affiliated or supported by \Wolfram. \Mathics will probably never have the power to compete with \Mathematica in industrial applications; it is an alternative though. It also invites community development at all levels.

See the <url>:installation instructions: https://mathics-development-guide.readthedocs.io/en/latest/installing/index.html</url> for the most recent instructions for installing from PyPI, or the source.

For implementation details see <url>https://mathics-development-guide.readthedocs.io/en/latest/</url>.

<section title="Why yet another CAS, one based on Mathematica?">
\Mathematica is great, but it a couple of disadvantages.

<ul>
  <li>It is not open source.
  <li>Its development is tightly controlled and centralized, and as such
  <li>it can't hook into different kinds open-source packages that have independently developed algorithms and methods
</ul>

The second point some may find and advantage.

However, even if you are willing to pay hundreds of dollars for the software, you would will not be able to see what\'s going on "inside" the program if that is your interest. That\'s what free, open-source, and community-supported software is for!

\Mathics aims at combining the best of both worlds: the beauty of \Mathematica backed by a free, extensible Python core which includes a rich set of Python tools including:

<ul>
  <li><url>:mpmath: https://mpmath.org/</url> for floating-point arithmetic with arbitrary precision,
  <li><url>:numpy: https://numpy.org/numpy</url> for numeric computation,
  <li><url>:SymPy: https://sympy.org</url> for symbolic mathematics, and
  <li>optionally <url>:SciPy: https://www.scipy.org/</url> for Scientific calculations.
</ul>

Performance of \Mathics is not, right now, practical in large-scale projects and calculations. However can be used as a tool for exploration and education.

</section>

<section title="What does \Mathics offer?">

Some of the features of \Mathics tries to be compatible with Wolfram-Language kernel within the confines of the Python ecosystem.

Given this, it is a powerful functional programming language, driven by pattern matching and rule application.

Primitive types include rationals, complex numbers, and arbitrary-precision numbers. Other primitive types such as images or graphs, or NLP come from the various Python libraries that \Mathics uses.

Outside of the "core" \Mathics kernel (which has a only primitive command-line interface), in separate github projects, as add-ons, there is:

<ul>
  <li>a Django-based web server
  <li>a command-line interface using either prompt-toolkit, or GNU Readline
  <li>a <url>:Mathics3 module for Graphs:https://pypi.org/project/pymathics-graph/</url> (via <url>:NetworkX:https://networkx.org/</url>),
  <li>a <url>:Mathics3 module for NLP:https://pypi.org/project/pymathics-natlang/</url> (via <url>:nltk:https://www.nltk.org/</url>, <url>:spacy:https://spacy.io/</url>, and others)
  <li>a <url>:A docker container:https://hub.docker.com/r/mathicsorg/mathics</url> which bundles all of the above
</ul>

</section>

<section title="History">
The first alpha versions of \Mathics were done in 2011 by Jan Pöschko. He worked on it for a couple of years to about the v0.5 release in 2012. By then, it had 386 built-in symbols. Currently there are over a 1,000 and even more when \Mathics modules are included.

After that, Angus Griffith took over primary leadership and rewrote the parser to pretty much the stage it is in now. He and later Ben Jones worked on it from 2013 to about 2017 to the v1.0 release. Towards the end of this period, Bernhard Liebl worked on this, mostly focused on graphics.

A <url>:docker image of the v.9 release: https://hub.docker.com/r/arkadi/mathics</url> can be found on dockerhub.

Around 2017, the project was largely abandoned in its largely Python 2.7 state, with support for Python 3.2-3.5 via six.

Subsequently, around mid 2020, it was picked up by the current developers. A list of authors and contributors can be found in the <url>
:<con>AUTHORS.txt</con>:
https://github.com/Mathics3/mathics-core/blob/master/AUTHORS.txt</url> file.
</section>

<section title="What is missing?">
There are lots of ways in which \Mathics could still be improved. <url>:<con>FUTURE.rst</con>: https://github.com/Mathics-3/mathics/blob/master/FUTURE.txt</url> has the current roadmap.

While we always could use help, such as in Python programming, improving Documentation. But there are other ways to help. For example:

<ul>
<li>Ensure this document is complete and accurate. We could use help to ensure all of the Builtin functions described properly and fully, and that they have link to corresponding Wiki, Sympy, WMA and/or mpath links.
Make sure the builtin summaries and examples clear and useful.</li>
<li>We could use help in LaTeX styling, and going over this document to remove overful boxes and things of that nature. We could also use help and our use of Asymptote. The are some graphics primitives such as for polyhedra that haven't been implemented. Similar graphics options are sometimes missing in Asymptote that we have available in other graphics backends.</li>

<li>add another graphics backend: it could be a javascript library like jsfiddle</li>

<li>Consider donating via <url>:Github Sponsors: https://github.com/sponsors</url> or some other mechanism.</li>
</ul>
</section>

See <url>:The Mathics3 Developer Guide:https://mathics-development-guide.readthedocs.io/en/latest/</url> for how to get started using and developing \Mathics.

</chapter>


<chapter title="Language Tutorial">

The following sections are introductions to the basic principles of the language of \Mathics. A few examples and functions are presented. Only their most common usages are listed; for a full description of a Symbols possible arguments, options, etc., see its entry in the Reference of Built-in Symbols.

However if you google for "Mathematica Tutorials" you will find easily dozens of other tutorials which are applicable. Be warned though that \Mathics does not yet offer the full range and features and capabilities of \Mathematica.

<section title="Basic calculations">
\Mathics can be used to calculate basic stuff:

  >> 1 + 2
  = 3

To submit a command to \Mathics, press 'Shift+Return' in the Web interface or 'Return' in the console interface. The result will be printed in a new line below your query.

\Mathics understands all basic arithmetic operators and applies the usual operator precedence. Use parentheses when needed:

  >> 1 - 2 * (3 + 5) / 4
  = -3

The multiplication can be omitted:

  >> 1 - 2 (3 + 5) / 4
  = -3

  >> 2 4
  = 8

Powers can be entered using '^':

  >> 3 ^ 4
  = 81

Integer divisions yield rational numbers:

  >> 6 / 4
  = 3 / 2

To convert the result to a floating point number, apply the function 'N':
  >> N[6 / 4]
  = 1.5

As you can see, functions are applied using square braces '[' and ']', in contrast to the common notation of '(' and ')'. At first hand, this might seem strange, but this distinction between function application and precedence change is necessary to allow some general syntax structures, as you will see later.

\Mathics provides many common mathematical functions and constants, e.g.:
  >> Log[E]
  = 1

  >> Sin[Pi]
  = 0

  >> Cos[0.5]
  = 0.877583

When entering floating point numbers in your query, \Mathics will perform a numerical evaluation and present a numerical result, pretty much like if you had applied 'N'.

Of course, \Mathics has complex numbers:
  >> Sqrt[-4]
  = 2 I

  >> I ^ 2
  = -1

  >> (3 + 2 I) ^ 4
  = -119 + 120 I

  >> (3 + 2 I) ^ (2.5 - I)
  = 43.663 + 8.28556 I

  >> Tan[I + 0.5]
  = 0.195577 + 0.842966 I

'Abs' calculates absolute values:
  >> Abs[-3]
  = 3

  >> Abs[3 + 4 I]
  = 5

\Mathics can operate with pretty huge numbers:
  >> 100!
  = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

('!' denotes the factorial function.)
The precision of numerical evaluation can be set:

  >> N[Pi, 30]
  = 3.14159265358979323846264338328

Division by zero is forbidden:
  >> 1 / 0
  : Infinite expression 1 / 0 encountered.
   = ComplexInfinity

Other expressions involving 'Infinity' are evaluated:
  >> Infinity + 2 Infinity
  = Infinity

In contrast to combinatorial belief, '0^0' is undefined:
  >> 0 ^ 0
 : Indeterminate expression 0 ^ 0 encountered.
   = Indeterminate

The result of the previous query to \Mathics can be accessed by '%':

  >> 3 + 4
  = 7

  >> % ^ 2
  = 49

  ##
</section>

<section title="Precision and Accuracy">

\Mathics handles relative and absolute uncertanties in numerical quantities. The <em>precision</em> or relative accuracy, is set by adding a RawBackquote character ('`') and the number of digits of precision in the mantissa. For example:

  >> 3.1416`3
   = 3.14

Above, two decimal places are shown in output after the decimal point, but three places of precision are stored.

The relative uncertainty of '3.1416`3' is 10^-3. It is numerically equivalent, in three places after the decimal point, to 3.1413`4:

  >> 3.1416`3 == 3.1413`4
   = True

We can get the precision of the number by using the \Mathics Built-in function <url>:'Precision': /doc/reference-of-built-in-symbols/atomic-elements-of-expressions/representation-of-numbers/precision/</url>:

    >> Precision[3.1413`4]
     = 4.

While 3.1419 not the closest approximation to Pi in 4 digits after the decimal point (or with precision 4), for 3 digits of precision it is:

    >> Pi == 3.141987654321`3
     = True

<url>The absolute accuracy of a number, is set by adding a two RawBackquotes '``' and the number digits.

For example:

  >> 13.1416``4
   = 13.142

is a number having a absolute uncertainty of 10^-4. This number is numerically equivalent to '13.1413``4':

  >> 13.1416``4 == 13.1413``4
   = True

The absolute accuracy for the value 0 is a fixed-precision Real number:

  >> 0``4
   = 0.0000

See also <url>:Accuracy and precision: https://en.wikipedia.org/wiki/Accuracy_and_precision</url>.
</section>


<section title="Symbols and Assignments">
Symbols need not be declared in \Mathics, they can just be entered and remain variable:
  >> x
  = x
Basic simplifications are performed:
  >> x + 2 x
  = 3 x
Symbols can have any name that consists of characters and digits:
  >> iAm1Symbol ^ 2
  = iAm1Symbol ^ 2

You can assign values to symbols:
  >> a = 2
  = 2
  >> a ^ 3
  = 8
  >> a = 4
  = 4
  >> a ^ 3
  = 64
Assigning a value returns that value. If you want to suppress the output of any result, add a ';' to the end of your query:
  >> a = 4;

Values can be copied from one variable to another:

  >> b = a;

Now changing 'a' does not affect 'b':

  >> a = 3;
  >> b
   = 4

Such a dependency can be achieved by using "delayed assignment" with the ':=' operator (which does not return anything, as the right side is not even evaluated):

  >> b := a ^ 2
  >> b
   = 9

  >> a = 5;
  >> b
   = 25

  ##
</section>


<section title="Comparisons and Boolean Logic">
Values can be compared for equality using the operator '==':

  >> 3 == 3
  = True

  >> 3 == 4
   = False

The special symbols 'True' and 'False' are used to denote truth values. Naturally, there are inequality comparisons as well:

  >> 3 > 4
  = False

Inequalities can be chained:
  >> 3 < 4 >= 2 != 1
  = True

Truth values can be negated using '!' (logical <em>not</em>) and combined using '&&' (logical <em>and</em>) and '||' (logical <em>or</em>):

  >> !True
  = False

  >> !False
  = True

  >> 3 < 4 && 6 > 5
  = True

'&&' has higher precedence than '||', i.e. it binds stronger:

  >> True && True || False && False
  = True

  >> True && (True || False) && False
  = False

  ##
</section>

<section title="Strings">
Strings can be entered with '"' as delimiters:

  >> "Hello world!"
  = Hello world!

As you can see, quotation marks are not printed in the output by default. This can be changed by using 'InputForm':
  >> InputForm["Hello world!"]
  = "Hello world!"

Strings can be joined using '<>':
  >> "Hello" <> " " <> "world!"
  = Hello world!

Numbers cannot be joined to strings:
  >> "Debian" <> 6
  : String expected.
  = Debian <> 6

They have to be converted to strings using 'ToString' first:
  >> "Debian" <> ToString[6]
  = Debian6

  ##
</section>

<section title="Working with Lists">
Lists can be entered in \Mathics with curly braces '{' and '}':

  >> mylist = {a, b, c, d}
  = {a, b, c, d}

There are various functions for constructing lists:
  >> Range[5]
  = {1, 2, 3, 4, 5}

  >> Array[f, 4]
  = {f[1], f[2], f[3], f[4]}

  >> ConstantArray[x, 4]
  = {x, x, x, x}

  >> Table[n ^ 2, {n, 2, 5}]
  = {4, 9, 16, 25}

The number of elements of a list can be determined with 'Length':
  >> Length[mylist]
  = 4

Elements can be extracted using double square braces:
  >> mylist[[3]]
  = c

Negative indices count from the end:
  >> mylist[[-3]]
  = b

Lists can be nested:
  >> mymatrix = {{1, 2}, {3, 4}, {5, 6}};

There are alternate forms to display lists:
  >> TableForm[mymatrix]
  = 1   2
  .
  . 3   4
  .
  . 5   6

  >> MatrixForm[mymatrix]
  = 1   2
  .
  . 3   4
  .
  . 5   6

There are various ways of extracting elements from a list:

  >> mymatrix[[2, 1]]
  = 3
  >> mymatrix[[;;, 2]]
  = {2, 4, 6}
  >> Take[mylist, 3]
  = {a, b, c}
  >> Take[mylist, -2]
  = {c, d}
  >> Drop[mylist, 2]
  = {c, d}
  >> First[mymatrix]
  = {1, 2}
  >> Last[mylist]
  = d
  >> Most[mylist]
  = {a, b, c}
  >> Rest[mylist]
  = {b, c, d}

Lists can be used to assign values to multiple variables at once:

  >> {a, b} = {1, 2};
  >> a
  = 1
  >> b
  = 2

Operations like addition and multiplication, "thread" over lists; lists are combined element-wise:

  >> {1, 2, 3} + {4, 5, 6}
  = {5, 7, 9}
  >> {1, 2, 3} * {4, 5, 6}
  = {4, 10, 18}

It is an error to combine lists with unequal lengths:
  >> {1, 2} + {4, 5, 6}
  : Objects of unequal length cannot be combined.
  = {1, 2} + {4, 5, 6}

  ##
</section>

<section title="The Structure of \Mathics Objects">
Every expression in \Mathics is built upon the same principle: it consists of a <em>head</em> and an arbitrary number of <em>children</em>, unless it is an <em>atom</em>, i.e. it can not be subdivided any further. To put it another way: everything is a function call. This can be best seen when displaying expressions in their "full form":

  >> FullForm[a + b + c]
  = Plus[a, b, c]

Nested calculations are nested function calls:
  >> FullForm[a + b * (c + d)]
  = Plus[a, Times[b, Plus[c, d]]]

Even lists are function calls of the function 'List':
  >> Head[{1, 2, 3}]
  = List

However, its full form is presented with ${\ldots}$
  >> FullForm[{1, 2, 3}]
   = {1,2,3}

 The head of an expression can be determined with 'Head':
  >> Head[a + b + c]
  = Plus

The children of an expression can be accessed like list elements:
  >> (a + b + c)[[2]]
  = b

The head is the 0th element:
  >> (a + b + c)[[0]]
  = Plus

The head of an expression can be exchanged using the function 'Apply':

  >> Apply[g, f[x, y]]
  = g[x, y]

  >> Apply[Plus, a * b * c]
  = a + b + c

'Apply' can be written using the operator '@@':
  >> Times @@ {1, 2, 3, 4}
  = 24

(This exchanges the head 'List' of '{1, 2, 3, 4}' with 'Times', and then the expression 'Times[1, 2, 3, 4]' is evaluated, yielding 24.)
'Apply' can also be applied on a certain <em>level</em> of an expression:

  >> Apply[f, {{1, 2}, {3, 4}}, {1}]
  = {f[1, 2], f[3, 4]}

Or even on a range of levels:
  >> Apply[f, {{1, 2}, {3, 4}}, {0, 2}]
  = f[f[1, 2], f[3, 4]]

'Apply' is similar to 'Map' ('/@'):
  >> Map[f, {1, 2, 3, 4}]
  = {f[1], f[2], f[3], f[4]}

  >> f /@ {{1, 2}, {3, 4}}
  = {f[{1, 2}], f[{3, 4}]}

The atoms of \Mathics are numbers, symbols, and strings. 'AtomQ' tests whether an expression is an atom:

  >> AtomQ[5]
  = True

  >> AtomQ[a + b]
  = False

The full form of rational and complex numbers looks like they were compound expressions:
  >> FullForm[3 / 5]
  = Rational[3, 5]
  >> FullForm[3 + 4 I]
  = Complex[3, 4]

However, they are still atoms, thus unaffected by applying functions, for instance:
  >> f @@ Complex[3, 4]
  = 3 + 4 I

Nevertheless, every atom has a head:
  >> Head /@ {1, 1/2, 2.0, I, "a string", x}
  = {Integer, Rational, Real, Complex, String, Symbol}

The operator '===' tests whether two expressions are the same on a structural level:
  >> 3 === 3
  = True

  >> 3 == 3.0
  = True

But:

  >> 3 === 3.0
  = False

because '3' (an 'Integer') and '3.0' (a 'Real') are structurally different.

  ##
</section>

<section title="Functions and Patterns">

Functions can be defined in the following way:
  >> f[x_] := x ^ 2

This tells \Mathics to replace every occurrence of 'f' with one (arbitrary) parameter 'x' with 'x ^ 2'.
  >> f[3]
  = 9

  >> f[a]
  = a ^ 2

The definition of 'f' does not specify anything for two parameters, so any such call will stay unevaluated:
  >> f[1, 2]
  = f[1, 2]

In fact, <em>functions</em> in \Mathics are just one aspect of <em>patterns</em>: 'f[x_]' is a pattern that <em>matches</em> expressions like 'f[3]' and 'f[a]'. The following patterns are available:
<dl>
  <dt>'_' or 'Blank[]'
  <dd>matches one expression.
  <dt>'Pattern[$x$, $p$]'
  <dd>matches the pattern $p$ and stores the value in $x$.
  <dt>'$x$_' or 'Pattern[$x$, Blank[]]'
  <dd>matches one expression and stores it in $x$.
  <dt>'__' or 'BlankSequence[]'
  <dd>matches a sequence of one or more expressions.
  <dt>'___' or 'BlankNullSequence[]'
  <dd>matches a sequence of zero or more expressions.
  <dt>'_$h$' or 'Blank[$h$]'
  <dd>matches one expression with head $h$.
  <dt>'$x$_$h$' or 'Pattern[$x$, Blank[$h$]]'
  <dd>matches one expression with head $h$ and stores it in $x$.
  <dt>'$p$ | $q$' or 'Alternatives[$p$, $q$]'
  <dd>matches either pattern $p$ or $q$.
  <dt>'$p$ ? $t$' or 'PatternTest[$p$, $t$]'
  <dd>matches $p$ if the test '$t$[$p$]' yields 'True'.
  <dt>'$p$ /; $c$' or 'Condition[$p$, $c$]'
  <dd>matches $p$ if condition $c$ holds.
  <dt>'Verbatim[$p$]'
  <dd>matches an expression that equals $p$, without regarding patterns inside $p$.
</dl>

As before, patterns can be used to define functions:

  >> g[s___] := Plus[s] ^ 2
  >> g[1, 2, 3]
  = 36

'MatchQ[$e$, $p$]' tests whether $e$ matches $p$:
  >> MatchQ[a + b, x_ + y_]
  = True

  >> MatchQ[6, _Integer]
  = True

'ReplaceAll' ('/.') replaces all occurrences of a pattern in an expression using a 'Rule' given by '->':
  >> {2, "a", 3, 2.5, "b", c} /. x_Integer -> x ^ 2
  = {4, a, 9, 2.5, b, c}

You can also specify a list of rules:
  >> {2, "a", 3, 2.5, "b", c} /. {x_Integer -> x ^ 2.0, y_String -> 10}
  = {4., 10, 9., 2.5, 10, c}

'ReplaceRepeated' ('//.') applies a set of rules repeatedly, until the expression doesn\'t change anymore:
  >> {2, "a", 3, 2.5, "b", c} //. {x_Integer -> x ^ 2.0, y_String -> 10}
  = {4., 100., 9., 2.5, 100., c}

There is a "delayed" version of 'Rule' which can be specified by ':>' (similar to the relation of ':=' to '='):

  >> a :> 1 + 2
  = a :> 1 + 2

  >> a -> 1 + 2
  = a -> 3

This is useful when the right side of a rule should not be evaluated immediately (before matching):
  >> {1, 2} /. x_Integer -> N[x]
  = {1, 2}

Here, 'N' is applied to 'x' before the actual matching, simply yielding 'x'. With a delayed rule this can be avoided:
  >> {1, 2} /. x_Integer :> N[x]
  = {1., 2.}

'ReplaceAll' and 'ReplaceRepeated' take the first possible match.
However 'ReplaceList' returns a list of all possible matches.
This can be used to get all subsequences of a list, for instance:

  >> ReplaceList[{a, b, c}, {___, x__, ___} -> {x}]
  = {{a}, {a, b}, {a, b, c}, {b}, {b, c}, {c}}
'ReplaceAll' would just return the first expression:
  >> ReplaceAll[{a, b, c}, {___, x__, ___} -> {x}]
   = {a}

In addition to defining functions as rules for certain patterns, there are <em>pure</em> functions that can be defined using the '&' postfix operator, where everything before it is treated as the function body and '#' can be used as argument placeholder:

  >> h = # ^ 2 &;
  >> h[3]
  = 9

Multiple arguments can simply be indexed:
  >> sum = #1 + #2 &;
  >> sum[4, 6]
  = 10

It is also possible to name arguments using 'Function':
  >> prod = Function[{x, y}, x * y];
  >> prod[4, 6]
  = 24

Pure functions are very handy when functions are used only locally, e.g., when combined with operators like 'Map':
  >> # ^ 2 & /@ Range[5]
  = {1, 4, 9, 16, 25}

Sort according to the second part of a list:
  >> Sort[{{x, 10}, {y, 2}, {z, 5}}, #1[[2]] < #2[[2]] &]
  = {{y, 2}, {z, 5}, {x, 10}}

Functions can be applied using prefix or postfix notation, in addition to using '[]':
  >> h @ 3
  = 9

  >> 3 // h
  = 9

  ##
</section>

<section title="Program-Flow Control Statements">
Like most programming languages, \Mathics has common program-flow control statements for conditions, loops, etc.:
<dl>
<dt>'If[$cond$, $pos$, $neg$]'
  <dd>returns $pos$ if $cond$ evaluates to 'True', and $neg$ if it evaluates to 'False'.
<dt>'Which[$cond1$, $expr1$, $cond2$, $expr2$, ...]'
        <dd>yields $expr1$ if $cond1$ evaluates to 'True', $expr2$ if $cond2$ evaluates to 'True', etc.
<dt>'Do[$expr$, {$i$, $max$}]'
  <dd>evaluates $expr$ $max$ times, substituting $i$ in $expr$ with values from 1 to $max$.
<dt>'For[$start$, $test$, $incr$, $body$]'
        <dd>evaluates $start$, and then iteratively $body$ and $incr$ as long as $test$ evaluates to 'True'.
<dt>'While[$test$, $body$]'
        <dd>evaluates $body$ as long as $test$ evaluates to 'True'.
<dt>'Nest[$f$, $expr$, $n$]'
        <dd>returns an expression with $f$ applied $n$ times to $expr$.
<dt>'NestWhile[$f$, $expr$, $test$]'
        <dd>applies a function $f$ repeatedly on an expression $expr$, until
        applying $test$ on the result no longer yields 'True'.
<dt>'FixedPoint[$f$, $expr$]'
        <dd>starting with $expr$, repeatedly applies $f$ until the result no longer changes.
</dl>

  >> If[2 < 3, a, b]
  = a
  >> x = 3; Which[x < 2, a, x > 4, b, x < 5, c]
  = c

Compound statements can be entered with ';'. The result of a compound expression is its last part or 'Null' if it ends with a ';'.
  >> 1; 2; 3
  = 3
  >> 1; 2; 3;

Inside 'For', 'While', and 'Do' loops, 'Break[]' exits the loop and 'Continue[]' continues to the next iteration.

  >> For[i = 1, i <= 5, i++, If[i == 4, Break[]]; Print[i]]
  | 1
  | 2
  | 3

 ##

</section>

<section title="Scoping">
By default, all symbols are "global" in \Mathics, i.e. they can be read and written in any part of your program.
However, sometimes "local" variables are needed in order not to disturb the global namespace. \Mathics provides two ways to support this:
<ul>
<li><em>lexical scoping</em> by 'Module', and
<li><em>dynamic scoping</em> by 'Block'.
</ul>
<dl>
<dt>'Module[{$vars$}, $expr$]'
        <dd>localizes variables by giving them a temporary name of the form
    'name$number', where number is the current value of '$ModuleNumber'. Each time a module
    is evaluated, '$ModuleNumber' is incremented.
<dt>'Block[{$vars$}, $expr$]'
        <dd>temporarily stores the definitions of certain variables, evaluates
        $expr$ with reset values and restores the original definitions afterwards.
</dl>

Both scoping constructs shield inner variables from affecting outer ones:

  >> t = 3;
  >> Module[{t}, t = 2]
  = 2
  >> Block[{t}, t = 2]
  = 2
  >> t
  = 3

'Module' creates new variables:
  >> y = x ^ 3;

  >> Module[{x = 2}, x * y]
  = 2 x ^ 3

'Block' does not:
  >> Block[{x = 2}, x * y]
   = 16

Thus, 'Block' can be used to temporarily assign a value to a variable:
  >> expr = x ^ 2 + x;
  >> Block[{x = 3}, expr]
  = 12

  >> x
  = x

'Block' can also be used to temporarily change the value of system parameters:

  >> Block[{$RecursionLimit = 30}, x = 2 x]
  : Recursion depth of 30 exceeded.
  = $Aborted

  >> f[x_] := f[x + 1]; Block[{$IterationLimit = 30}, f[1]]
  : Iteration limit of 30 exceeded.
  = $Aborted

It is common to use scoping constructs for function definitions with local variables:

  >> fac[n_] := Module[{k, p}, p = 1; For[k = 1, k <= n, ++k, p *= k]; p]
  >> fac[10]
  = 3628800

  >> 10!
  = 3628800

 ##
</section>

<section title="Formatting Output">
The way results are formatted for output in \Mathics is rather sophisticated, as compatibility to the way \Mathematica does things is one of the design goals. It can be summed up in the following procedure:
<ol>
<li>The result of the query is calculated.
<li>The result is stored in 'Out' (which '%' is a shortcut for).
<li>Any 'Format' rules for the desired output form are applied to the result. In the console version of \Mathics, the result is formatted as 'OutputForm'; 'MathMLForm' for the 'StandardForm' is used in the interactive Web version; and 'TeXForm' for the 'StandardForm' is used to generate the \LaTeX version of this documentation.
<li>'MakeBoxes' is applied to the formatted result, again given either 'OutputForm', 'MathMLForm', or 'TeXForm' depending on the execution context of \Mathics. This yields a new expression consisting of "box constructs".
<li>The boxes are turned into an ordinary string and displayed in the console, sent to the browser, or written to the documentation \LaTeX file.
</ol>
As a consequence, there are various ways to implement your own formatting strategy for custom objects.

You can specify how a symbol shall be formatted by assigning values to 'Format':
  >> Format[x] = "y";
  >> x
  = y
This will apply to 'MathMLForm', 'OutputForm', 'StandardForm', 'TeXForm', and 'TraditionalForm'.

  >> x // InputForm
  = x
You can specify a specific form in the assignment to 'Format':
  >> Format[x, TeXForm] = "z";
  >> x // TeXForm
  = \text{z}

Special formats might not be very relevant for individual symbols, but rather for custom functions (objects):
  >> Format[r[args___]] = "<an r object>";
  >> r[1, 2, 3]
  = <an r object>
You can use several helper functions to format expressions:
<dl>
<dt>'Infix[$expr$, $op$]'
  <dd>formats the arguments of $expr$ with infix operator $op$.
<dt>'Prefix[$expr$, $op$]'
  <dd>formats the argument of $expr$ with prefix operator $op$.
<dt>'Postfix[$expr$, $op$]'
  <dd>formats the argument of $expr$ with postfix operator $op$.
<dt>'StringForm[$form$, $arg1$, $arg2$, ...]'
  <dd>formats arguments using a format string.
</dl>

  >> Format[r[args___]] = Infix[{args}, "~"];
  >> r[1, 2, 3]
  = 1 ~ 2 ~ 3
  >> StringForm["`1` and `2`", n, m]
  = n and m

There are several methods to display expressions in 2-D:
<dl>
<dt>'Row[{...}]'
  <dd>displays expressions in a row.
<dt>'Grid[{{...}}]'
  <dd>displays a matrix in two-dimensional form.
<dt>'Subscript[$expr$, $i1$, $i2$, ...]'
  <dd>displays $expr$ with subscript indices $i1$, $i2$, ...
<dt>'Superscript[$expr$, $exp$]'
  <dd>displays $expr$ with superscript (exponent) $exp$.
</dl>

  >> Grid[{{a, b}, {c, d}}]
  = a   b
  .
  . c   d

  >> Subscript[a, 1, 2] // TeXForm
  = a_{1,2}

If you want even more low-level control over expression display, override 'MakeBoxes':

  >> MakeBoxes[b, StandardForm] = "c";
  >> b
  = b

## this will be displayed as c in the browser and LaTeX documentation
This will even apply to 'TeXForm', because 'TeXForm' implies 'StandardForm':
  >> b // TeXForm
  = c

Except some other form is applied first:
  >> b // OutputForm // TeXForm
  = b
'MakeBoxes' for another form:

  >> MakeBoxes[b, TeXForm] = "d";
  >> b // TeXForm
  = d
You can cause a much bigger mess by overriding 'MakeBoxes' than by sticking to 'Format', e.g. generate invalid XML:

  >> MakeBoxes[c, MathMLForm] = "<not closed";
  >> c // MathMLForm
  = <not closed

However, this will not affect formatting of expressions involving 'c':
  >> c + 1 // MathMLForm
  = ...

That\'s because 'MathMLForm' will, when not overridden for a special case, call 'StandardForm' first.
'Format' will produce escaped output:

  >> Format[d, MathMLForm] = "<not closed";
  >> d // MathMLForm
  = ...

  >> d + 1 // MathMLForm
  = ...

For instance, you can override 'MakeBoxes' to format lists in a different way:
  >> MakeBoxes[{items___}, StandardForm] := RowBox[{"[", Sequence @@ Riffle[MakeBoxes /@ {items}, " "], "]"}]
  >> {1, 2, 3}
   = {1, 2, 3}

  #> {1, 2, 3} // TeXForm
   = \left[1 2 3\right]

However, this will not be accepted as input to \Mathics anymore:
  >> [1 2 3]
  : Expression cannot begin with "[1 2 3]" (line 1 of "<test>").

  >> Clear[MakeBoxes]

By the way, 'MakeBoxes' is the only built-in symbol that is not protected by default:
  >> Attributes[MakeBoxes]
  = {HoldAllComplete}

'MakeBoxes' must return a valid box construct:
  >> MakeBoxes[squared[args___], StandardForm] := squared[args] ^ 2
  >> squared[1, 2]
   = squared[1, 2]

## different in LaTeX and MathML
 X> squared[1, 2] // TeXForm
  : Power[squared[1, 2], 2] is not a valid box structure.
  =

The desired effect can be achieved in the following way:
  >> MakeBoxes[squared[args___], StandardForm] := SuperscriptBox[RowBox[{MakeBoxes[squared], "[", RowBox[Riffle[MakeBoxes[#]& /@ {args}, ","]], "]"}], 2]
  >> squared[1, 2]
  = squared[1, 2]

  #> squared[1, 2] // TeXForm
   = \text{squared}\left[1,2\right]^2

You can view the box structure of a formatted expression using 'ToBoxes':

  >> ToBoxes[m + n]
   = RowBox[{m, +, n}]

The list elements in this 'RowBox' are strings, though string delimiters are not shown in the default output form:

  >> InputForm[%]
   = RowBox[{"m", "+", "n"}]

  ##
</section>

<section title="Graphics Introduction Examples">
Two-dimensional graphics can be created using the function 'Graphics' and a list of graphics primitives. For three-dimensional graphics see the following section. The following primitives are available:
<dl>
<dt>'Circle[{$x$, $y$}, $r$]'
  <dd>draws a circle.
  <dt>'Disk[{$x$, $y$}, $r$]'

  <dd>draws a filled disk.
  <dt>'Rectangle[{$x1$, $y1$}, {$x2$, $y2$}]'

  <dd>draws a filled rectangle.
  <dt>'Polygon[{{$x1$, $y1$}, {$x2$, $y2$}, ...}]'

  <dd>draws a filled polygon.
  <dt>'Line[{{$x1$, $y1$}, {$x2$, $y2$}, ...}]'

  <dd>draws a line.
  <dt>'Text[$text$, {$x$, $y$}]'
  <dd>draws text in a graphics.
</dl>

  >> Graphics[{Circle[{0, 0}, 1]}]
   = -Graphics-

  >> Graphics[{Line[{{0, 0}, {0, 1}, {1, 1}, {1, -1}}], Rectangle[{0, 0}, {-1, -1}]}]
  = -Graphics-

Colors can be added in the list of graphics primitives to change the drawing color. The following ways to specify colors are supported:
<dl>
  <dt>'RGBColor[$r$, $g$, $b$]'
  <dd>specifies a color using red, green, and blue.

  <dt>'CMYKColor[$c$, $m$, $y$, $k$]'
  <dd>specifies a color using cyan, magenta, yellow, and black.

  <dt>'Hue[$h$, $s$, $b$]'
  <dd>specifies a color using hue, saturation, and brightness.

  <dt>'GrayLevel[$l$]'
  <dd>specifies a color using a gray level.
</dl>
All components range from 0 to 1. Each color function can be supplied with an additional argument specifying the desired opacity ("alpha") of the color. There are many predefined colors, such as 'Black', 'White', 'Red', 'Green', 'Blue', etc.

  >> Graphics[{Red, Disk[]}]
  = -Graphics-

Table of hues:

  >> Graphics[Table[{Hue[h, s], Disk[{12h, 8s}]}, {h, 0, 1, 1/6}, {s, 0, 1, 1/4}]]
   = -Graphics-

  ##

Colors can be mixed and altered using the following functions:
<dl>
<dt>'Blend[{$color1$, $color2$}, $ratio$]'
  <dd>mixes $color1$ and $color2$ with $ratio$, where a ratio of 0 returns $color1$ and a ratio of 1 returns $color2$.
<dt>'Lighter[$color$]'
  <dd>makes $color$ lighter (mixes it with 'White').
<dt>'Darker[$color$]'
  <dd>makes $color$ darker (mixes it with 'Black').
</dl>

  >> Graphics[{Lighter[Red], Disk[]}]
   = -Graphics-

'Graphics' produces a 'GraphicsBox':
  >> Head[ToBoxes[Graphics[{Circle[]}]]]
   = GraphicsBox

  ##
</section>

<section title="3D Graphics">
Three-dimensional graphics are created using the function 'Graphics3D' and a list of 3D primitives. The following primitives are supported so far:
<dl>
<dt>'Polygon[{{$x1$, $y1$, $z1$}, {$x2$, $y2$, $z3$}, ...}]'
  <dd>draws a filled polygon.
<dt>'Line[{{$x1$, $y1$, $z1$}, {$x2$, $y2$, $z3$}, ...}]'
  <dd>draws a line.
<dt>'Point[{$x1$, $y1$, $z1$}]'
  <dd>draws a point.
</dl>

  >> Graphics3D[Polygon[{{0,0,0}, {0,1,1}, {1,0,0}}]]
   = -Graphics3D-

Colors can also be added to three-dimensional primitives.
  >> Graphics3D[{Orange, Polygon[{{0,0,0}, {1,1,1}, {1,0,0}}]}, Axes->True]
   = -Graphics3D-

'Graphics3D' produces a 'Graphics3DBox':
  >> Head[ToBoxes[Graphics3D[{Polygon[]}]]]
   = Graphics3DBox

  ##
</section>

<section title="Plotting Introduction Examples">
\Mathics can plot functions:
  >> Plot[Sin[x], {x, 0, 2 Pi}]
   = -Graphics-
You can also plot multiple functions at once:
  >> Plot[{Sin[x], Cos[x], x ^ 2}, {x, -1, 1}]
   = -Graphics-

Two-dimensional functions can be plotted using 'DensityPlot':
  >> DensityPlot[x ^ 2 + 1 / y, {x, -1, 1}, {y, 1, 4}]
   = -Graphics-
You can use a custom coloring function:
  >> DensityPlot[x ^ 2 + 1 / y, {x, -1, 1}, {y, 1, 4}, ColorFunction -> (Blend[{Red, Green, Blue}, #]&)]
   = -Graphics-
One problem with 'DensityPlot' is that it\'s still very slow, basically due to function evaluation being pretty slow in general---and 'DensityPlot' has to evaluate a lot of functions.

Three-dimensional plots are supported as well:
  >> Plot3D[Exp[x] Cos[y], {x, -2, 1}, {y, -Pi, 2 Pi}]
   = -Graphics3D-

  ##
</section>


</chapter>

<chapter title="Further Tutorial Examples">

<section title="Curve sketching">
Let\'s sketch the function
  >> f[x_] := 4 x / (x ^ 2 + 3 x + 5)

The derivatives are:
  >> {f'[x], f''[x], f'''[x]} // Together
   = {-4 (-5 + x ^ 2) / (5 + 3 x + x ^ 2) ^ 2, 8 (-15 - 15 x + x ^ 3) / (5 + 3 x + x ^ 2) ^ 3, -24 (-20 - 60 x - 30 x ^ 2 + x ^ 4) / (5 + 3 x + x ^ 2) ^ 4}

To get the extreme values of 'f', compute the zeroes of the first derivatives:
  >> extremes = Solve[f'[x] == 0, x]
   = {{x -> -Sqrt[5]}, {x -> Sqrt[5]}}

And test the second derivative:
  >> f''[x] /. extremes // N
   = {1.65086, -0.064079}

Thus, there is a local maximum at 'x = Sqrt[5]' and a local minimum at 'x = -Sqrt[5]'.
Compute the inflection points numerically, chopping imaginary parts close to 0:
  >> inflections = Solve[f''[x] == 0, x] // N // Chop
   = {{x -> -1.0852}, {x -> -3.21463}, {x -> 4.29983}}

Insert into the third derivative:
  >> f'''[x] /. inflections

   = {-3.67683, 0.694905, 0.00671894}
Being different from 0, all three points are actual inflection points.
'f' is not defined where its denominator is 0:
  >> Solve[Denominator[f[x]] == 0, x]
   = {{x -> -3 / 2 - I / 2 Sqrt[11]}, {x -> -3 / 2 + I / 2 Sqrt[11]}}

These are non-real numbers, consequently 'f' is defined on all real numbers.
The behaviour of 'f' at the boundaries of its definition:
  >> Limit[f[x], x -> Infinity]
   = 0
  >> Limit[f[x], x -> -Infinity]
   = 0

Finally, let\'s plot 'f':
  >> Plot[f[x], {x, -8, 6}]
   = -Graphics-

  ##
</section>


<section title="Linear algebra">
Let\'s consider the matrix
  >> A = {{1, 1, 0}, {1, 0, 1}, {0, 1, 1}};
  >> MatrixForm[A]
   = 1   1   0
  .
  . 1   0   1
  .
  . 0   1   1

We can compute its eigenvalues and eigenvectors:
  >> Eigenvalues[A]
   = {2, -1, 1}
  >> Eigenvectors[A]
   = {{1, 1, 1}, {1, -2, 1}, {-1, 0, 1}}
This yields the diagonalization of 'A':
  >> T = Transpose[Eigenvectors[A]]; MatrixForm[T]
   = 1   1    -1
  .
  . 1   -2   0
  .
  . 1   1    1
  >> Inverse[T] . A . T // MatrixForm
   = 2   0    0
  .
  . 0   -1   0
  .
  . 0   0    1
  >> % == DiagonalMatrix[Eigenvalues[A]]
   = True

We can solve linear systems:
  >> LinearSolve[A, {1, 2, 3}]
   = {0, 1, 2}
  >> A . %
   = {1, 2, 3}
In this case, the solution is unique:
  >> NullSpace[A]
   = {}

Let\'s consider a singular matrix:
  >> B = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  >> MatrixRank[B]
   = 2
  >> s = LinearSolve[B, {1, 2, 3}]
   = {-1 / 3, 2 / 3, 0}
  >> NullSpace[B]
   = {{1, -2, 1}}
  >> B . (RandomInteger[100] * %[[1]] + s)
   = {1, 2, 3}

 ##
</section>


<section title="Dice">
Let\'s play with dice in this example. A 'Dice' object shall represent the outcome of a series of rolling a dice with six faces, e.g.:
  >> Dice[1, 6, 4, 4]
   = Dice[1, 6, 4, 4]

Like in most games, the ordering of the individual throws does not matter. We can express this by making 'Dice' 'Orderless':
  >> SetAttributes[Dice, Orderless]
  >> Dice[1, 6, 4, 4]
   = Dice[1, 4, 4, 6]

A dice object shall be displayed as a rectangle with the given number of points in it, positioned like on a traditional dice:
  >> Format[Dice[n_Integer?(1 <= # <= 6 &)]] := Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{1 - p, 1 - p}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, 1 - p}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{1 - p, p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{1 - p, 0.5}, r]}]}, ImageSize -> Tiny]]
  >> Dice[1]
   = -Graphics-

  #> Definition[Dice]
    = Attributes[Dice] = {Orderless}
   .
   . Format[Dice[n_Integer ? (1 <= #1 <= 6&)], MathMLForm] = Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{Plus[1, Times[-1, p]], 0.5}, r]}]}, ImageSize -> Tiny]]
   .
   . Format[Dice[n_Integer ? (1 <= #1 <= 6&)], OutputForm] = Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{Plus[1, Times[-1, p]], 0.5}, r]}]}, ImageSize -> Tiny]]
   .
   . Format[Dice[n_Integer ? (1 <= #1 <= 6&)], StandardForm] = Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{Plus[1, Times[-1, p]], 0.5}, r]}]}, ImageSize -> Tiny]]
   .
   . Format[Dice[n_Integer ? (1 <= #1 <= 6&)], TeXForm] = Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{Plus[1, Times[-1, p]], 0.5}, r]}]}, ImageSize -> Tiny]]
   .
   . Format[Dice[n_Integer ? (1 <= #1 <= 6&)], TraditionalForm] = Block[{p = 0.2, r = 0.05}, Graphics[{EdgeForm[Black], White, Rectangle[], Black, EdgeForm[], If[OddQ[n], Disk[{0.5, 0.5}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{p, p}, r]], If[MemberQ[{2, 3, 4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{p, Plus[1, Times[-1, p]]}, r]], If[MemberQ[{4, 5, 6}, n], Disk[{Plus[1, Times[-1, p]], p}, r]], If[n === 6, {Disk[{p, 0.5}, r], Disk[{Plus[1, Times[-1, p]], 0.5}, r]}]}, ImageSize -> Tiny]]

The empty series of dice shall be displayed as an empty dice:
  >> Format[Dice[]] := Graphics[{EdgeForm[Black], White, Rectangle[]}, ImageSize -> Tiny]
  >> Dice[]
   = -Graphics-

Any non-empty series of dice shall be displayed as a row of individual dice:
  >> Format[Dice[d___Integer?(1 <= # <= 6 &)]] := Row[Dice /@ {d}]
  >> Dice[1, 6, 4, 4]
   = -Graphics--Graphics--Graphics--Graphics-

Note that \Mathics will automatically sort the given format rules according to their "generality", so the rule for the empty dice does not get overridden by the rule for a series of dice.
We can still see the original form by using 'InputForm':

  >> Dice[1, 6, 4, 4] // InputForm
   = Dice[1, 4, 4, 6]

We want to combine 'Dice' objects using the '+' operator:
  >> Dice[a___] + Dice[b___] ^:= Dice[Sequence @@ {a, b}]

The '^:=' ('UpSetDelayed') tells \Mathics to associate this rule with 'Dice' instead of 'Plus'.
'Plus' is protected---we would have to unprotect it first:
  >> Dice[a___] + Dice[b___] := Dice[Sequence @@ {a, b}]
  : Tag Plus in Dice[a___] + Dice[b___] is Protected.
   = $Failed

We can now combine dice:
  >> Dice[1, 5] + Dice[3, 2] + Dice[4]
   = -Graphics--Graphics--Graphics--Graphics--Graphics-

  #> Dice[1, 5] + Dice[3, 2] + Dice[4] // InputForm
   = Dice[1, 2, 3, 4, 5]

Let\'s write a function that returns the sum of the rolled dice:
  >> DiceSum[Dice[d___]] := Plus @@ {d}
  >> DiceSum @ Dice[1, 2, 5]
   = 8

And now let\'s put some dice into a table:
  >> Table[{Dice[Sequence @@ d], DiceSum @ Dice[Sequence @@ d]}, {d, {{1, 2}, {2, 2}, {2, 6}}}] // TableForm
   = -Graphics--Graphics-   3
  .
  . -Graphics--Graphics-   4
  .
  . -Graphics--Graphics-   8

  ##

It is not very sophisticated from a mathematical point of view, but it\'s beautiful.

</section>

</chapter>



<chapter title="Django-based Web Interface">

In the future, we plan on providing an interface to Jupyter as a separate package.

However currently as part \Mathics, we distribute a browser-based interface using long-term-release (LTS) Django 4.

Since a Jupyter-based interface seems preferable to the home-grown interface described here, it is doubtful whether there will be future improvements to the this interface.

When you enter Mathics in the top after the Mathics logo and the word "Mathics" you'll see a <i>menubar</i>.

It looks like this:

<imgpng src="menubar.png" title="Mathics Menu Bar" label="menubar">

These save and load worksheets, share sessions, run a gallery of examples, go to the GitHub organization page, and provide information about the particular Mathics3 installation.

These are explained in the sections below.

<section title="URIs">

For the most part, the application is a single-page application.
Assuming your are running locally or on a host called 'localhost' using the default port, 8000, here are some URLs and what they do:

<dl>
  <dt><url>http://localhost:8000</url>
  <dd>The single-page application; the main page.
  <dt><url>http://localhost:8000/about</url>
  <dd>A page giving:
  <ul>
    <li>the software versions of this package and version information of important software this uses.
    <li>directory path information for the current setup
    <li>machine information
    <li>system information
    <li>customizable system settings
  </ul>
  <dt><url>http://localhost:8000/doc</url>
  <dd>An on-line formatted version of the documentation, which include this text. You can see this as a right side frame of the main page, when clicking "?" on the right-hand upper corner.
</dl>
</section>
<section title="Saving, Loading, and Deleting Worksheets">

<subsection title="Saving Worksheets">

Worksheets exist in the browser window only and are not stored on the server, by default. To save all your queries and results, use the <em>Save</em> button which is the middle graphic of the menu bar. It looks like this:

<imgpng src="save-button.png" title="Mathics Save Button" label="save-button">

Depending on browser, desktop, and OS-settings, the "Ctrl+S" key combination may do the same thing.

<subsection title="Loading and Deleting Worksheets">

Saved worksheets can be loaded or deleted using the <em>File Open</em> button which is the left-most button in the menu bar. It looks like this:

<imgpng src="file-open-button.png" title="Mathics File Open Button" label="file-open-button">

Depending on browser, desktop, and OS-settings, the "Ctrl+O" key combination may do the same thing.

A pop-up menu should appear with the list of saved worksheets with an option to either load or delete the worksheet.

</section>

<section title="Gallery Examples">

We have a number of examples showing off briefly some of the capabilities of the system. These are run when you hit hit the button that looks like this:

<imgpng src="gallery.png" title="Run Gallery Demo examples Button" label="gallery-button">

It is also shown in the pop-up text that appears when Mathics3 is first run.

</section>

<section title="Persistence of Mathics Definitions in a Session">

When you use the Django-based Web interface of \Mathics, a browser session is created. Cookies have to be enabled to allow this. Your session holds a key which is used to access your definitions that are stored in a database on the server. As long as you don\'t clear the cookies in your browser, your definitions will remain even when you close and re-open the browser.

This implies that you should not store sensitive, private information in \Mathics variables when using the online Web interface. In addition to their values being stored in a database on the server, your queries might be saved for debugging purposes. However, the fact that they are transmitted over plain HTTP should make you aware that you should not transmit any sensitive information. When you want to do calculations with that kind of stuff, simply install \Mathics locally!

If you are using a public terminal, to erase all your definitions and close the browser window. When you use \Mathics in a browser, use the command <con>Quit[]</con> or its alias, <con>Exit[]</con>.

When you reload the current page in a browser using the default URL, e.g <con>http:localhost:8000</con>, all of the previous input and output disappears.

On the other hand, Definitions as described above do not, unless <con>Quit[]</con> or <con>Exit[]</con> is entered as described above.

If you want a URL that will that records the input entered the <em>Generate Input Hash</em> button does this. The button looks like this:

<imgpng src="generate-hash-button.png" title="Mathics Generate Input Hash Button" label="generate-input-hash-button">

For example, assuming you have a \Mathics server running at port 8000 on <con>localhost</con>, and you enter the URL <con>http://localhost:8000/#cXVlcmllcz14</con>, you should see a single line of input containing <con>x</con> entered.

Of course, what the value of this is when evaluated depends on whether <con>x</con> has been previously defined.

</section>

<section title="Keyboard Commands">

There are some keyboard commands you can use in the Django-based Web interface of \Mathics.

<dl>
<dt>'Shift+Return'</dt>
	<dd>This evaluates the current cell (the most important one, for sure). On the right-hand side you may also see an "=" button which can be clicked to do the same thing.</dd>
<dt>'Ctrl+D'</dt>
	<dd>This moves the cursor over to the documentation pane on the right-hand side. From here you can perform a search for a pre-defined \Mathics function, or symbol. Clicking on the "?" symbol on the right-hand side does the same thing.</dd>
<dt>'Ctrl+C'</dt>
	<dd>This moves the cursor back to document code pane area where you type \Mathics expressions</dd>
<dt>'Ctrl+S'</dt>
	<dd>Save worksheet</dd>
<dt>'Ctrl+O'</dt>
	<dd>Open worksheet</dd>
<dt>'Right Click' on MathML output</dt>
	<dd>Opens MathJax Menu</dd>
</dl>

Of special note is the last item on the list: right-click to open the MathJax menu. Under "Math Setting"/"Zoom Trigger",  if the zoom trigger is set to a value other then "No Zoom", then when that trigger is applied on MathML formatted output, the MathML formula pop up a window for the formula. The window can show the formula larger. Also, this is a way to see output that is too large to fit on the display since the window allows for scrolling.

Keyboard commands behavior depends the browser used, the operating system, desktop settings, and customization. We hook into the desktop "Open the current document" and "Save the current document" functions that many desktops provide. For example see: <url>:Finding keyboard shortcuts: https://help.ubuntu.com/community/KeyboardShortcuts#Finding_keyboard_shortcuts</url>

Often, these shortcut keyboard command are only recognized when a text field has focus; otherwise,the browser might do some browser-specific actions, like setting a bookmark etc.

</section>

</chapter>
