Contributing Guidelines
***********************

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

How to Contribute
=================

The mailing list for Octave development discussions is maintainers@octave.org.  Patches should be submitted to Octave's patch tracker (https://savannah.gnu.org/patch/?func=additem&group=octave). This concerns the development of Octave core, i.e., code that goes in to Octave directly.  You may consider developing and publishing a package instead; a great place for this is the allied Octave-Forge project (http://octave.sourceforge.net).  Note that the Octave core project is inherently more conservative and follows narrower rules.

Building the Development Sources
================================

The directions for building from the development sources change from time to time, so you should read the resources for developers on the web or in the development sources archive.  Start here: http://www.octave.org/get-involved.html.

Basics of Generating a Changeset
================================

The best way to contribute is to create a Mercurial changeset and submit it to the bug (http://savannah.gnu.org/bugs/?group=octave) or patch (http://savannah.gnu.org/patch/?func=additem&group=octave) trackers (Please use the patch tracker only for patches which add new features.  If you have a patch to submit that fixes a bug, you should use the bug tracker instead.). 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 http://www.selenic.com/mercurial/wiki/index.cgi/Tutorial.  There you will also find help about how to install Mercurial.

A simple contribution sequence could look like this:

     hg clone http://www.octave.org/hg/octave
                                  # make a local copy of the octave
                                  # source repository
     cd octave
     # change some sources...
     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
     # attach ../cool.diff to your bug report

You may want to get familiar with Mercurial queues to manage your changesets.  To work with queues you must activate the extension mq with the following entry in Mercurial's configuration file .hgrc (or Mercurial.ini on Windows):

     [extensions]
     mq=

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 bug tracker:

     hg qnew nasty_bug            # create a new patch
     # change sources...
     hg qref                      # save the changes into the patch
     # change even more...
     hg qref -m "solution to nasty bug!"
                                  # save again with commit message
     hg export -o ../nasty.diff tip
                                  # export the patch
     # attach ../nasty.diff to your bug report
     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...
     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
     # attach ../doc.diff to your bug report
     hg qpop
     # discussion in the bug tracker ...
     hg qpush nasty_bug           # apply the patch again
     # change sources yet again ...
     hg qref
     hg export -o ../nasty2.diff tip
     # attach ../nasty2.diff to your bug report

Mercurial has a few more useful extensions that really should be enabled. They are not enabled by default due to a number of factors (mostly because they don't work in all terminal types).

The following entries in the .hgrc are recommended

     [extensions]
     graphlog=
     color=
     progress=
     pager=

For the color extension, default color and formatting of hg status can be modified by

     [color]
     status.modified = magenta bold
     status.added = green bold
     status.removed = red bold
     status.deleted = cyan bold
     status.unknown = black  bold
     status.ignored = black bold

Sometimes a few further improvements for the pager extension are necessary.  The following options should not be enabled unless paging is not working correctly.

     [pager]
     # Some options for the less pager, see less(1) for their meaning.
     pager = LESS='FSRX' less

     # Some commands that aren't paged by default; also enable paging
     # for them
     attend = tags, help, annotate, cat, diff, export, status, \
              outgoing, incoming

Enabling the described extensions should immediately lead to a difference when using the command line version of hg.  Of these options, the only one that enables a new command is graphlog.  It is recommanded that to use the command hg glog, instead of hg log, for a better feel about what commits are being based on.

General Guidelines
==================

All Octave's sources are distributed under the GNU General Public License (GPL).  Currently, Octave uses GPL version 3.  For details about this license, see 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):

     ## Copyright (C) 1996-2013 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/>.

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 .hgrc (or Mercurial.ini on Windows) with your name and email, which will be 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 then 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 for changelogs, as in the following example:

     look for methods before constructors

     * symtab.cc (symbol_table::fcn_info::fcn_info_rep::find):
     Look for class methods before constructors, contrary to 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.

In this example, the names of the file changed is listed first, 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 was changed, not why it was changed. Any explanation for 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 (http://bugs.octave.org), please add '(bug #XXXXX)' to the first line of the commit messages.  For example:

     Fix bug for complex input for gradient (bug #34292).

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

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 statement blocks.  The recommended indent is 2 spaces.  When calling functions, put spaces after commas and before the calling parentheses, like this:

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

An exception are matrix or cell constructors:

       [sin(x), cos(x)]
       {sin(x), cos(x)}

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

       A(:,i,j)

but

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

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 endif, endswitch) rather than the generic end.

Enclose the if, while, until, and switch conditions in parentheses, as in C:

     if (isvector (a))
       s = sum (a);
     endif

Do not do this, however, with the iteration counter portion of a for statement.  Write:

     for i = 1:n
       b(i) = sum (a(:,i));
     endfor

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:

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

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 before the left open parenthesis and after commas, for both function definitions and function calls.

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

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

If you have nested 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:

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

Consider putting extra braces around a multi-line 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 are needed.  Use local variables of blocks---it helps optimization.  Don't write a 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:

     octave_value retval;

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

     double d1, d2;

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 return statements---use nested if statements if possible.

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 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 http://autoconf-archive.cryp.to.

If you give a code example in the documentation written in Texinfo with the @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 @example environment) for finding the appropriate line width:

              1         2         3         4         5         6
     123456789012345678901234567890123456789012345678901234567890