@c Copyright (C) 2012 John W. Eaton
@c Copyright (C) 2008-2012 Jaroslav Hajek
@c
@c This file is part of Octave.
@c
@c Octave is free software; you can redistribute it and/or modify it
@c under the terms of the GNU General Public License as published by the
@c Free Software Foundation; either version 3 of the License, or (at
@c your option) any later version.
@c
@c Octave is distributed in the hope that it will be useful, but WITHOUT
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
@c FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
@c for more details.
@c
@c You should have received a copy of the GNU General Public License
@c along with Octave; see the file COPYING.  If not, see
@c <http://www.gnu.org/licenses/>.

@node Contributing Guidelines
@appendix Contributing Guidelines
@cindex coding standards
@cindex Octave development

This chapter is dedicated to those who wish to contribute code to Octave.

@menu
* How to Contribute::
* Building the Development Sources::
* Basics of Generating a Changeset::
* General Guidelines::
* Octave Sources (m-files)::
* C++ Sources::
* Other Sources::
@end menu

@node How to Contribute
@section How to Contribute
The mailing list for Octave development discussion and sending
contributions is @email{maintainers@@octave.org}.  This concerns the
development of Octave core, i.e., code that goes to Octave directly.
You may consider developing and publishing a package instead; a great
place for this is the allied Octave-Forge project
(@url{http://octave.sf.net}).  Note that the Octave project is
inherently more conservative and follows narrower rules.

@node Building the Development Sources
@section Building the Development Sources

In addition to all the tools (both optional and required) that are
listed in @ref{Build Dependencies} you will need:

@table @asis
@item Mercurial
Distributed version control system (@url{http://mercurial.selenic.com}).
Octave's sources are stored in a Mercurial archive.

@item Git
Distributed version control system (@url{http://git-scm.com}).  The
gnulib sources that Octave depends on are stored in a Git archive.
@end table

Once you have the required tools installed, you can build Octave by
doing

@itemize @bullet
@item
Check out a copy of the Octave sources:
@example
hg clone http://hg.savannah.gnu.org/hgweb/octave
@end example

@item
Change to the top-level directory of the newly checked out sources:
@example
cd octave
@end example

@item
Generate the necessary configuration files:
@example
./autogen.sh
@end example

@item
Create a build directory and change to it:
@example
mkdir build
cd build
@end example
By using a separate build directory, you will keep the source directory
clean and it will be easy to completely remove all files generated by
the build.  You can also have parallel build trees for different
purposes that all share the same sources.  For example, one build tree
may be configured to disable compiler optimization in order to allow for
easier debugging while another may be configured to test building with
other specialized compiler flags.

@item
Run Octave's configure script from the build directory:
@example
../configure
@end example

@item
Run make in the build directory:
@example
make
@end example
@end itemize

Once the build is finished, you will see a message like the following:

@example
@group
Octave successfully built.  Now choose from the following:

   ./run-octave    - to run in place to test before installing
   make check      - to run the tests
   make install    - to install (PREFIX=...)
@end group
@end example

@node Basics of Generating a Changeset
@section Basics of Generating a Changeset

The preferable form of contribution is creating a Mercurial changeset
and sending it via e-mail to the octave-maintainers mailing list.
Mercurial is the source code management system currently used to develop
Octave.  Other forms of contributions (e.g., simple diff patches) are
also acceptable, but they slow down the review process.  If you want to
make more contributions, you should really get familiar with Mercurial.
A good place to start is
@url{http://www.selenic.com/mercurial/wiki/index.cgi/Tutorial}.  There
you will also find help how to install Mercurial.

A simple contribution sequence could look like this:

@example
@group
hg clone http://www.octave.org/hg/octave
                             # make a local copy of the octave
                             # source repository
cd octave
# change some sources@dots{}
hg commit -m "make Octave the coolest software ever"
                             # commit the changeset into your
                             # local repository
hg export -o ../cool.diff tip
                             # export the changeset to a diff
                             # file
# send ../cool.diff via email
@end group
@end example

You may want to get familiar with Mercurial queues to manage your
changesets.  Here is a slightly more complex example using Mercurial
queues, where work on two unrelated changesets is done in parallel and
one of the changesets is updated after discussion on the maintainers
mailing list:

@example
hg qnew nasty_bug            # create a new patch
# change sources@dots{}
hg qref                      # save the changes into the patch
# change even more@dots{}
hg qref -m "solution to nasty bug!"
                             # save again with commit message
hg export -o ../nasty.diff tip
                             # export the patch
# send ../nasty.diff via email
hg qpop                      # undo the application of the patch
                             # and remove the changes from the
                             # source tree
hg qnew doc_improvements     # create an unrelated patch
# change doc sources@dots{}
hg qref -m "could not find myfav.m in the doc"
                             # save the changes into the patch
hg export -o ../doc.diff tip
                             # export the second patch
# send ../doc.diff tip via email
hg qpop
# discussion in the maintainers mailing list @dots{}
hg qpush nasty_bug           # apply the patch again
# change sources yet again @dots{}
hg qref
hg export -o ../nasty2.diff tip
# send ../nasty2.diff via email
@end example

@node General Guidelines
@section General Guidelines

All Octave's sources are distributed under the General Public License
(GPL).  Currently, Octave uses GPL version 3.  For details about this
license, see @url{http://www.gnu.org/licenses/gpl.html}.  Therefore,
whenever you create a new source file, it should have the following
comment header (use appropriate year, name and comment marks):

@example
## Copyright (C) 1996-2012 John W. Eaton <jwe@@octave.org>
##
## This file is part of Octave.
##
## Octave is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public
## License as published by the Free Software Foundation;
## either version 3 of the License, or (at your option) any
## later version.
##
## Octave is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
## PURPOSE.  See the GNU General Public License for more
## details.
##
## You should have received a copy of the GNU General Public
## License along with Octave; see the file COPYING.  If not,
## see <http://www.gnu.org/licenses/>.
@end example

Always include commit messages in changesets.  After making your source
changes, record and briefly describe the changes in your commit message.
You should have previously configured your @file{.hgrc} (or
@file{Mercurial.ini} on Windows) with your name and email, which will
get automatically added to your commit message.  Your commit message
should have a brief one-line explanation of what the commit does.  If you
are patching a bug, this one-line explanation should mention the bug
number at the end.  If your change is small and only touches one file,
this is typically sufficient.  If you are modifying several files or
several parts of one file, you should enumerate your changes roughly
following the GNU coding standards on changelogs, like the following
example:

@example
@group
look for methods before constructors

* symtab.cc (symbol_table::fcn_info::fcn_info_rep::find):
Look for class methods before constructors, contrary to @sc{matlab}
documentation.

* test/ctor-vs-method: New directory of test classes.
* test/test_ctor_vs_method.m: New file.
* test/Makefile.am: Include ctor-vs-method/module.mk.
(FCN_FILES): Include test_ctor_vs_method.m in the list.
@end group
@end example

@noindent
In this example, the names of files is mentioned, and in parentheses the
name of the function in that file that was modified.  There is no need to
mention the function for m-files that only contain one function.  The
commit message should describe what is changed, not why.  Any explanation
of why a change is needed should appear as comments in the code,
particularly if there is something that might not be obvious to someone
reading it later.

When submitting code which addresses a known bug on the Octave bug
tracker (@url{http://bugs.octave.org}), please add '(bug #XXXXX)' to the
first line of the commit messages.  For example:

@example
@group
Fix bug for complex input for gradient (bug #34292).
@end group
@end example

The preferred comment mark for places that may need further attention is
FIXME.

@node Octave Sources (m-files)
@section Octave Sources (m-files)

Don't use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Indent the bodies of
the statement blocks.  Recommended indent is 2 spaces.  When calling
functions, put spaces after commas and before the calling parentheses,
like this:

@example
  x = max (sin (y+3), 2);
@end example

@noindent
An exception are matrix and vector constructors:

@example
  [sin(x), cos(x)]
@end example

@noindent
Here, putting spaces after @code{sin}, @code{cos} would result in a
parse error.  In indexing expression, do not put a space after the
identifier (this differentiates indexing and function calls nicely).
The space after comma is not necessary if index expressions are simple,
i.e., you may write

@example
  A(:,i,j)
@end example

@noindent
but

@example
  A([1:i-1;i+1:n], XI(:,2:n-1))
@end example

Use lowercase names if possible.  Uppercase is acceptable for variable
names consisting of 1-2 letters.  Do not use mixed case names.  Function
names must be lowercase.  Function names are global, so choose them
wisely.

Always use a specific end-of-block statement (like @code{endif},
@code{endswitch}) rather than generic @code{end}.

Enclose the @code{if}, @code{while}, @code{until} and @code{switch}
conditions in parentheses, like in C:

@example
@group
if (isvector (a))
  s = sum(a);
endif
@end group
@end example

@noindent
Do not do this, however, with the iteration counter portion of a
@code{for} statement.  Write:

@example
@group
for i = 1:n
  b(i) = sum (a(:,i));
endfor
@end group
@end example

@node C++ Sources
@section C++ Sources

Don't use tabs.  Tabs cause trouble.  If you are used to them, set up
your editor so that it converts tabs to spaces.  Format function headers
like this:

@example
@group
static bool
matches_patterns (const string_vector& patterns, int pat_idx,
                  int num_pat, const std::string& name)
@end group
@end example

@noindent
The function name should start in column 1, and multi-line argument
lists should be aligned on the first char after the open parenthesis.
You should put a space after the left open parenthesis and after commas,
for both function definitions and function calls.

Recommended indent is 2 spaces.  When indenting, indent the statement
after control structures (like @code{if}, @code{while}, etc.).  If there
is a compound statement, indent @emph{both} the curly braces and the
body of the statement (so that the body gets indented by @emph{two}
indents).  Example:

@example
@group
if (have_args)
  @{
    idx.push_back (first_args);
    have_args = false;
  @}
else
  idx.push_back (make_value_list (*p_args, *p_arg_nm, &tmp));
@end group
@end example

@noindent
If you have nested @code{if} statements, use extra braces for extra
clarification.

Split long expressions in such a way that a continuation line starts
with an operator rather than identifier.  If the split occurs inside
braces, continuation should be aligned with the first char after the
innermost braces enclosing the split.  Example:

@example
@group
SVD::type type = ((nargout == 0 || nargout == 1)
                  ? SVD::sigma_only
                  : (nargin == 2) ? SVD::economy : SVD::std);
@end group
@end example

@noindent
Consider putting extra braces around a multiline expression to make it
more readable, even if they are not necessary.  Also, do not hesitate to
put extra braces anywhere if it improves clarity.

Declare variables just before they're needed.  Use local variables of
blocks---it helps optimization.  Don't write multi-line variable
declaration with a single type specification and multiple variables.  If
the variables don't fit on single line, repeat the type specification.
Example:

@example
@group
octave_value retval;

octave_idx_type nr = b.rows ();
octave_idx_type nc = b.cols ();

double d1, d2;
@end group
@end example

Use lowercase names if possible.  Uppercase is acceptable for variable
names consisting of 1-2 letters.  Do not use mixed case names.

Use Octave's types and classes if possible.  Otherwise, use the C++
standard library.  Use of STL containers and algorithms is encouraged.
Use templates wisely to reduce code duplication.  Avoid comma
expressions, labels and gotos, and explicit typecasts.  If you need to
typecast, use the modern C++ casting operators.  In functions, minimize
the number of @code{return} statements---use nested @code{if} statements
if possible.

@node Other Sources
@section Other Sources
Apart from C++ and Octave language (m-files), Octave's sources include
files written in C, Fortran, M4, Perl, Unix shell, AWK, Texinfo and
@TeX{}.  There are not many rules to follow when using these other
languages; some of them are summarized below.  In any case, the golden
rule is: if you modify a source file, try to follow any conventions you
can detect in the file or other similar files.

For C you should obviously follow all C++ rules that can apply.

If you modify a Fortran file, you should stay within Fortran 77 with
common extensions like @code{END DO}.  Currently, we want all sources to
be compilable with the f2c and g77 compilers, without special flags if
possible.  This usually means that non-legacy compilers also accept the
sources.

The M4 macro language is mainly used for Autoconf configuration files.
You should follow normal M4 rules when contributing to these files.
Some M4 files come from external source, namely the Autoconf archive
@url{http://autoconf-archive.cryp.to}.

If you give a code example in the documentation written in Texinfo with
the @code{@@example} environment, you should be aware that the text
within such an environment will not be wrapped.  It is recommended that
you keep the lines short enough to fit on pages in the generated pdf or
ps documents.  Here is a ruler (in an @code{@@example} environment) for
finding the appropriate line width:

@example
@group
         1         2         3         4         5         6
123456789012345678901234567890123456789012345678901234567890
@end group
@end example
