changeset 16644:856cb7cba231 classdef

maint: periodic merge of default to classdef
author John W. Eaton <jwe@octave.org>
date Sun, 12 May 2013 21:45:57 -0400
parents 8abae9ea4cb5 (current diff) 4258750c76ed (diff)
children 450c03932d6c
files libgui/qterminal/libqterminal/QTerminalInterface.h libinterp/interpfcn/symtab.cc libinterp/octave-value/ov-fcn.h libinterp/octave-value/ov-usr-fcn.cc libinterp/octave-value/ov-usr-fcn.h libinterp/parse-tree/lex.ll libinterp/parse-tree/oct-parse.in.yy libinterp/parse-tree/parse.h libinterp/parse-tree/pt-bp.h liboctave/util/base-list.h test/Makefile.am
diffstat 77 files changed, 5090 insertions(+), 802 deletions(-) [+]
line wrap: on
line diff
--- a/Makefile.am	Mon Apr 29 19:13:40 2013 -0400
+++ b/Makefile.am	Sun May 12 21:45:57 2013 -0400
@@ -124,12 +124,7 @@
 	chmod a+rx "$@"
 
 .gdbinit: etc/gdbinit
-	@if [ -f .gdbinit ]; then \
-	  echo "refusing to overwrite .gdbinit with newer version from $<" 1>&2; \
-	else \
-	  echo "Installing .gdbinit from version at $<" ; \
-	  cp $< $@; \
-	fi
+	@$(gdbinit_install_rule)
 
 if AMCOND_BUILD_DOCS
 AUTHORS BUGS INSTALL.OCTAVE:
--- a/NEWS	Mon Apr 29 19:13:40 2013 -0400
+++ b/NEWS	Sun May 12 21:45:57 2013 -0400
@@ -180,7 +180,7 @@
 
       betaincinv   ellipj    findfigs     polyeig       tetramesh
       cmpermute    ellipke   fminsearch   rgbplot       waterfall
-      cmunique     erfcinv   importdata   shrinkfaces
+      cmunique     erfcinv   importdata   shrinkfaces   gallery
       colorcube    erfi      iscolormap   splinefit
       dawson       expint    lines        strjoin
 
--- a/build-aux/common.mk	Mon Apr 29 19:13:40 2013 -0400
+++ b/build-aux/common.mk	Sun May 12 21:45:57 2013 -0400
@@ -718,6 +718,15 @@
 mv $@-t $@
 endef
 
+define gdbinit_install_rule
+if [ -f .gdbinit ]; then \
+  echo "refusing to overwrite .gdbinit with newer version from $<" 1>&2; \
+else \
+  echo "Installing .gdbinit from version at $<" ; \
+  cp $< $@; \
+fi
+endef
+
 %.cc-tst : %.cc
 	$(test-file-commands)
 
--- a/doc/interpreter/contrib.txi	Mon Apr 29 19:13:40 2013 -0400
+++ b/doc/interpreter/contrib.txi	Sun May 12 21:45:57 2013 -0400
@@ -48,18 +48,10 @@
 @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}).
+listed in @ref{Build Dependencies} you will need Mercurial, a
+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
 
--- a/doc/interpreter/matrix.txi	Mon Apr 29 19:13:40 2013 -0400
+++ b/doc/interpreter/matrix.txi	Sun May 12 21:45:57 2013 -0400
@@ -235,6 +235,8 @@
 
 The following functions return famous matrix forms.
 
+@DOCSTRING(gallery)
+
 @DOCSTRING(hadamard)
 
 @DOCSTRING(hankel)
--- a/doc/interpreter/sparse.txi	Mon Apr 29 19:13:40 2013 -0400
+++ b/doc/interpreter/sparse.txi	Sun May 12 21:45:57 2013 -0400
@@ -89,13 +89,15 @@
 easy to grasp, but requires more storage than is strictly needed.
 
 The storage technique used within Octave is the compressed column
-format.  In this format the position of each element in a row and the
-data are stored as previously.  However, if we assume that all elements
-in the same column are stored adjacent in the computers memory, then
-we only need to store information on the number of non-zero elements
-in each column, rather than their positions.  Thus assuming that the
-matrix has more non-zero elements than there are columns in the
-matrix, we win in terms of the amount of memory used.
+format. It is similar to the Yale format.
+@footnote{@url{http://en.wikipedia.org/wiki/Sparse_matrix#Yale_format}}
+In this format the position of each element in a row and the data are
+stored as previously. However, if we assume that all elements in the
+same column are stored adjacent in the computers memory, then we only
+need to store information on the number of non-zero elements in each
+column, rather than their positions. Thus assuming that the matrix has
+more non-zero elements than there are columns in the matrix, we win in
+terms of the amount of memory used.
 
 In fact, the column index contains one more element than the number of
 columns, with the first element always being zero.  The advantage of
@@ -797,18 +799,19 @@
 http://www.cise.ufl.edu/research/sparse/}.
 @end enumerate
 
-The band density is defined as the number of non-zero values in the matrix
-divided by the number of non-zero values in the matrix.  The banded matrix
-solvers can be entirely disabled by using @dfn{spparms} to set @code{bandden}
-to 1 (i.e., @code{spparms ("bandden", 1)}).
+The band density is defined as the number of non-zero values in the band
+divided by the total number of values in the full band. The banded
+matrix solvers can be entirely disabled by using @dfn{spparms} to set
+@code{bandden} to 1 (i.e., @code{spparms ("bandden", 1)}).
 
-The QR@tie{}solver factorizes the problem with a Dulmage-Mendelsohn, to
-separate the problem into blocks that can be treated as over-determined,
-multiple well determined blocks, and a final over-determined block.  For
-matrices with blocks of strongly connected nodes this is a big win as
-LU@tie{}decomposition can be used for many blocks.  It also significantly
-improves the chance of finding a solution to over-determined problems
-rather than just returning a vector of @dfn{NaN}'s.
+The QR@tie{}solver factorizes the problem with a Dulmage-Mendelsohn
+decomposition, to separate the problem into blocks that can be treated
+as over-determined, multiple well determined blocks, and a final
+over-determined block. For matrices with blocks of strongly connected
+nodes this is a big win as LU@tie{}decomposition can be used for many
+blocks. It also significantly improves the chance of finding a solution
+to over-determined problems rather than just returning a vector of
+@dfn{NaN}'s.
 
 All of the solvers above, can calculate an estimate of the condition
 number.  This can be used to detect numerical stability problems in the
--- a/etc/gdbinit	Mon Apr 29 19:13:40 2013 -0400
+++ b/etc/gdbinit	Sun May 12 21:45:57 2013 -0400
@@ -1,3 +1,8 @@
+## Disable the next line if you really need to see the
+## thread create/exit messages.
+
+set print thread-events off
+
 ## Helpful macros for debugging Octave.
 
 ############################################################
--- a/libgui/qterminal-module.mk	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal-module.mk	Sun May 12 21:45:57 2013 -0400
@@ -3,7 +3,6 @@
 
 noinst_HEADERS += \
   qterminal/libqterminal/QTerminal.h \
-  qterminal/libqterminal/QTerminalInterface.h \
   qterminal/libqterminal/win32/QTerminalColors.h \
   qterminal/libqterminal/win32/QWinTerminalImpl.h \
   qterminal/libqterminal/unix/BlockArray.h \
@@ -28,8 +27,7 @@
   qterminal/libqterminal/unix/TerminalView.h
 
 qterminal_libqterminal_la_MOC = \
-  qterminal/libqterminal/moc-QTerminal.cc \
-  qterminal/libqterminal/moc-QTerminalInterface.cc
+  qterminal/libqterminal/moc-QTerminal.cc
 
 nodist_qterminal_libqterminal_la_SOURCES = $(qterminal_libqterminal_la_MOC)
 
--- a/libgui/qterminal/libqterminal/QTerminal.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/QTerminal.cc	Sun May 12 21:45:57 2013 -0400
@@ -22,23 +22,100 @@
 
 #include "QTerminal.h"
 
+#if defined (Q_OS_WIN32)
+# include "win32/QWinTerminalImpl.h"
+#else
+# include "unix/QUnixTerminalImpl.h"
+#endif
+
+QTerminal *
+QTerminal::create (QWidget *xparent)
+{
+#if defined (Q_OS_WIN32)
+  return new QWinTerminalImpl (xparent);
+#else
+  return new QUnixTerminalImpl (xparent);
+#endif
+}
+
+QList<QColor>
+QTerminal::default_colors (void)
+{
+  static QList<QColor> colors;
+
+  if (colors.isEmpty ())
+    {
+      colors << QColor(0,0,0)
+             << QColor(255,255,255)
+             << QColor(192,192,192)
+             << QColor(128,128,128);
+    }
+
+  return colors;
+}
+
+QStringList
+QTerminal::color_names (void)
+{
+  static QStringList names;
+
+  if (names.isEmpty ())
+    {
+      names << QObject::tr ("foreground")
+            << QObject::tr ("background")
+            << QObject::tr ("selection")
+            << QObject::tr ("cursor");
+    }
+
+  return names;
+}
+
 void
 QTerminal::notice_settings (const QSettings *settings)
 {
   // QSettings pointer is checked before emitting.
 
   // Set terminal font:
-  QFont term_font = QFont();
-  term_font.setFamily(settings->value("terminal/fontName","Courier New").toString());
-  term_font.setPointSize(settings->value("terminal/fontSize",10).toInt ());
+  QFont term_font = QFont ();
+  term_font.setFamily
+    (settings->value ("terminal/fontName", "Courier New").toString ());
+
+  term_font.setPointSize (settings->value ("terminal/fontSize", 10).toInt ());
+
   setTerminalFont (term_font);
 
-  QString cursorType = settings->value ("terminal/cursorType","ibeam").toString ();
-  bool cursorBlinking = settings->value ("terminal/cursorBlinking",true).toBool ();
+  QString cursorType
+    = settings->value ("terminal/cursorType", "ibeam").toString ();
+
+  bool cursorBlinking
+    = settings->value ("terminal/cursorBlinking", true).toBool ();
+
   if (cursorType == "ibeam")
-    setCursorType(QTerminalInterface::IBeamCursor, cursorBlinking);
+    setCursorType (QTerminal::IBeamCursor, cursorBlinking);
   else if (cursorType == "block")
-    setCursorType(QTerminalInterface::BlockCursor, cursorBlinking);
+    setCursorType (QTerminal::BlockCursor, cursorBlinking);
   else if (cursorType == "underline")
-    setCursorType(QTerminalInterface::UnderlineCursor, cursorBlinking);
+    setCursorType (QTerminal::UnderlineCursor, cursorBlinking);
+
+  bool cursorUseForegroundColor
+    = settings->value ("terminal/cursorUseForegroundColor", true).toBool ();
+
+  QList<QColor> colors = default_colors ();
+
+  setForegroundColor
+    (settings->value ("terminal/color_f",
+                      QVariant (colors.at (0))).value<QColor> ());
+
+  setBackgroundColor
+    (settings->value ("terminal/color_b",
+                      QVariant (colors.at (1))).value<QColor> ());
+
+  setSelectionColor
+    (settings->value ("terminal/color_s",
+                      QVariant (colors.at (2))).value<QColor> ());
+
+  setCursorColor
+    (cursorUseForegroundColor,
+     settings->value ("terminal/color_c",
+                      QVariant (colors.at (3))).value<QColor> ());
 }
--- a/libgui/qterminal/libqterminal/QTerminal.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/QTerminal.h	Sun May 12 21:45:57 2013 -0400
@@ -25,33 +25,92 @@
 
 #include <QSettings>
 #include <QtGlobal>
+#include <QWidget>
+#include <QStringList>
+#include <QColor>
+#include <QList>
+#include <QMenu>
 
-#ifdef Q_OS_WIN32
-    #include "win32/QWinTerminalImpl.h"
-    class QTerminal : public QWinTerminalImpl
+class QTerminal : public QWidget
+{
+  Q_OBJECT
+
+public:
+
+  static QTerminal *create (QWidget *xparent = 0);
+
+  static QList<QColor> default_colors (void);
+
+  static QStringList color_names (void);
+
+  virtual ~QTerminal (void) { }
+
+  virtual void setTerminalFont(const QFont& font) = 0;
+
+  virtual void setSize(int h, int v) = 0;
+
+  virtual void sendText(const QString& text) = 0;
+
+  enum CursorType
     {
-        Q_OBJECT
-    public:
-        QTerminal(QWidget *xparent = 0)
-            : QWinTerminalImpl(xparent) { }
-        ~QTerminal() { }
-
-    public slots:
-        void notice_settings (const QSettings *settings);
+      UnderlineCursor,
+      BlockCursor,
+      IBeamCursor
     };
-#else
-    #include "unix/QUnixTerminalImpl.h"
-    class QTerminal : public QUnixTerminalImpl
-    {
-        Q_OBJECT
-    public:
-        QTerminal(QWidget *xparent = 0)
-            : QUnixTerminalImpl(xparent) { }
-        ~QTerminal() { }
+
+  virtual void setCursorType (CursorType type, bool blinking)
+  {
+    // Provide empty default impl in order to avoid conflicts with the
+    // win impl.
+
+    Q_UNUSED (type);
+    Q_UNUSED (blinking);
+  }
+
+  virtual void setBackgroundColor (const QColor& color) = 0;
+
+  virtual void setForegroundColor (const QColor& color) = 0;
+
+  virtual void setSelectionColor (const QColor& color) = 0;
+
+  virtual void setCursorColor (bool useForegroundColor,
+                               const QColor& color) = 0;
+
+public slots:
+
+  virtual void copyClipboard (void) = 0;
+
+  virtual void pasteClipboard (void) = 0;
 
-    public slots:
-        void notice_settings (const QSettings *settings);
-    };
-#endif
+  virtual void handleCustomContextMenuRequested (const QPoint& at)
+  {
+    _contextMenu->move (mapToGlobal (at));
+    _contextMenu->show ();
+  }
+
+  void notice_settings (const QSettings *settings);
+
+protected:
+
+  QTerminal (QWidget *xparent = 0) : QWidget (xparent)
+  {
+    connect (this, SIGNAL (customContextMenuRequested (QPoint)),
+             this, SLOT (handleCustomContextMenuRequested (QPoint)));
+
+    setContextMenuPolicy (Qt::CustomContextMenu);
+
+    _contextMenu = new QMenu (this);
+
+    QAction *copyAction  = _contextMenu->addAction ("Copy");
+    QAction *pasteAction = _contextMenu->addAction ("Paste");
+
+    connect (copyAction, SIGNAL (triggered()), this, SLOT (copyClipboard()));
+    connect (pasteAction, SIGNAL (triggered()), this, SLOT (pasteClipboard()));
+  }
+
+private:
+
+    QMenu *_contextMenu;
+};
 
 #endif // QTERMINAL_H
--- a/libgui/qterminal/libqterminal/QTerminalInterface.h	Mon Apr 29 19:13:40 2013 -0400
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,77 +0,0 @@
-/*
-
-Copyright (C) 2012 Michael Goffioul.
-Copyright (C) 2012 Jacob Dawid.
-
-This file is part of QTerminal.
-
-Foobar 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.
-
-QTerminal 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 Foobar.  If not, see <http://www.gnu.org/licenses/>.
-
-*/
-
-#ifndef QTERMINALINTERFACE_H
-#define QTERMINALINTERFACE_H
-
-#include <QWidget>
-#include <QMenu>
-
-class QTerminalInterface : public QWidget
-{
-    Q_OBJECT
-public:
-    QTerminalInterface(QWidget *xparent = 0) : QWidget(xparent) {
-      connect (this, SIGNAL(customContextMenuRequested(QPoint)),
-               this, SLOT(handleCustomContextMenuRequested(QPoint)));
-
-      setContextMenuPolicy (Qt::CustomContextMenu);
-
-      _contextMenu = new QMenu (this);
-      QAction *copyAction  = _contextMenu->addAction ("Copy");
-      QAction *pasteAction = _contextMenu->addAction ("Paste");
-
-      connect (copyAction, SIGNAL (triggered()), this, SLOT (copyClipboard()));
-      connect (pasteAction, SIGNAL (triggered()), this, SLOT (pasteClipboard()));
-    }
-    virtual ~QTerminalInterface() { }
-
-    virtual void setTerminalFont(const QFont& font) = 0;
-    virtual void setSize(int h, int v) = 0;
-    virtual void sendText(const QString& text) = 0;
-
-    enum CursorType {
-      UnderlineCursor,
-      BlockCursor,
-      IBeamCursor
-    };
-
-    virtual void setCursorType(CursorType type, bool blinking) {
-        // Provide empty default impl in order to avoid conflicts with the win impl.
-        Q_UNUSED(type);
-        Q_UNUSED(blinking);
-    }
-
-public slots:
-    virtual void copyClipboard() = 0;
-    virtual void pasteClipboard() = 0;
-
-    virtual void handleCustomContextMenuRequested(QPoint at) {
-      _contextMenu->move (mapToGlobal(at));
-      _contextMenu->show ();
-    }
-
-private:
-    QMenu *_contextMenu;
-};
-
-#endif // QTERMINALINTERFACE_H
--- a/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.cpp	Sun May 12 21:45:57 2013 -0400
@@ -25,7 +25,7 @@
 #include <termios.h>
 
 QUnixTerminalImpl::QUnixTerminalImpl(QWidget *parent)
-    : QTerminalInterface(parent) {
+    : QTerminal(parent) {
     setMinimumSize(300, 200);
     initialize();
 }
@@ -135,12 +135,16 @@
     m_terminalView->setBlinkingCursor(blinking);
 }
 
-void QUnixTerminalImpl::focusInEvent(QFocusEvent *focusEvent)
+// FIXME -- not sure how to make these work properly given the way the
+// Unix terminal handles colors.
+void QUnixTerminalImpl::setBackgroundColor (const QColor& color) { }
+void QUnixTerminalImpl::setForegroundColor (const QColor& color) { }
+void QUnixTerminalImpl::setSelectionColor (const QColor& color) { }
+
+void QUnixTerminalImpl::setCursorColor (bool useForegroundColor,
+                                        const QColor& color)
 {
-    Q_UNUSED(focusEvent);
-    m_terminalView->updateImage();
-    m_terminalView->repaint();
-    m_terminalView->update();
+  m_terminalView->setKeyboardCursorColor (useForegroundColor, color);
 }
 
 void QUnixTerminalImpl::showEvent(QShowEvent *)
--- a/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/unix/QUnixTerminalImpl.h	Sun May 12 21:45:57 2013 -0400
@@ -25,9 +25,9 @@
 #include "unix/kpty.h"
 #include "unix/TerminalModel.h"
 #include "unix/TerminalView.h"
-#include "QTerminalInterface.h"
+#include "QTerminal.h"
 
-class QUnixTerminalImpl : public QTerminalInterface
+class QUnixTerminalImpl : public QTerminal
 {
     Q_OBJECT
 
@@ -43,12 +43,16 @@
 
     void setCursorType(CursorType type, bool blinking);
 
+    void setBackgroundColor (const QColor& color);
+    void setForegroundColor (const QColor& color);
+    void setSelectionColor (const QColor& color);
+    void setCursorColor (bool useForegroundColor, const QColor& color);
+
 public slots:
     void copyClipboard();
     void pasteClipboard();
 
 protected:
-    void focusInEvent(QFocusEvent *focusEvent);
     void showEvent(QShowEvent *);
     virtual void resizeEvent(QResizeEvent *);   
 
--- a/libgui/qterminal/libqterminal/unix/TerminalView.cpp	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.cpp	Sun May 12 21:45:57 2013 -0400
@@ -1021,6 +1021,11 @@
 {
   _hasBlinkingCursor=blink;
 
+  setBlinkingCursorState(blink);
+}
+
+void TerminalView::setBlinkingCursorState(bool blink)
+{
   if (blink && !_blinkCursorTimer->isActive())
     _blinkCursorTimer->start(BLINK_DELAY);
 
@@ -1029,8 +1034,6 @@
       _blinkCursorTimer->stop();
       if (_cursorBlinking)
         blinkCursorEvent();
-      else
-        _cursorBlinking = false;
     }
 }
 
@@ -1053,6 +1056,25 @@
   paint.end();
 }
 
+void TerminalView::focusInEvent(QFocusEvent *focusEvent)
+{
+  setBlinkingCursorState(true);
+  updateImage();
+  repaint();
+  update();
+
+  QWidget::focusInEvent(focusEvent);
+}
+
+void TerminalView::focusOutEvent(QFocusEvent *focusEvent)
+{
+  // Force the cursor to be redrawn.
+  _cursorBlinking = true;
+  setBlinkingCursorState(false);
+
+  QWidget::focusOutEvent(focusEvent);
+}
+
 QPoint TerminalView::cursorPosition() const
 {
   if (_screenWindow)
@@ -1343,7 +1365,10 @@
 
 void TerminalView::blinkCursorEvent()
 {
-  _cursorBlinking = !_cursorBlinking;
+  if (_hasBlinkingCursor)
+    _cursorBlinking = !_cursorBlinking;
+  else
+    _cursorBlinking = false;
 
   QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) );
 
--- a/libgui/qterminal/libqterminal/unix/TerminalView.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/unix/TerminalView.h	Sun May 12 21:45:57 2013 -0400
@@ -150,6 +150,7 @@
     bool blinkingCursor() { return _hasBlinkingCursor; }
     /** Specifies whether or not the cursor blinks. */
     void setBlinkingCursor(bool blink);
+    void setBlinkingCursorState(bool blink);
 
     void setCtrlDrag(bool enable) { _ctrlDrag=enable; }
     bool ctrlDrag() { return _ctrlDrag; }
@@ -478,6 +479,9 @@
 
     virtual void paintEvent( QPaintEvent * );
 
+    void focusInEvent(QFocusEvent *focusEvent);
+    void focusOutEvent(QFocusEvent *focusEvent);
+
     virtual void showEvent(QShowEvent*);
     virtual void hideEvent(QHideEvent*);
     virtual void resizeEvent(QResizeEvent*);
--- a/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.cpp	Sun May 12 21:45:57 2013 -0400
@@ -20,6 +20,7 @@
 */
 
 #include <QApplication>
+#include <QClipboard>
 #include <QColor>
 #include <QFont>
 #include <QHBoxLayout>
@@ -30,6 +31,9 @@
 #include <QtDebug>
 #include <QThread>
 #include <QTimer>
+#include <QToolTip>
+#include <QCursor>
+#include <QMessageBox>
 
 #include <fcntl.h>
 #include <io.h>
@@ -39,6 +43,7 @@
 #define _WIN32_WINNT 0x0500 
 #include <windows.h>
 #include <cstring>
+#include <limits>
 
 #include "QWinTerminalImpl.h"
 #include "QTerminalColors.h"
@@ -91,6 +96,14 @@
   friend class QWinTerminalImpl;
 
 public:
+
+  enum KeyboardCursorType
+    {
+      BlockCursor,
+      UnderlineCursor,
+      IBeamCursor
+    };
+
   QConsolePrivate (QWinTerminalImpl* parent, const QString& cmd = QString ());
   ~QConsolePrivate (void);
 
@@ -103,6 +116,7 @@
   void monitorConsole (void);
   void startCommand (void);
   void sendConsoleText (const QString& s);
+  QRect cursorRect (void);
 
   void log (const char* fmt, ...);
 
@@ -110,13 +124,37 @@
   void setupStandardIO (DWORD stdHandleId, int fd, const char* name,
                         const char* devName);
 
+  QPoint posToCell (const QPoint& pt);
+  QString getSelection (void);
+  void updateSelection (void);
+  void clearSelection (void);
+
+  QColor backgroundColor (void) const;
+  QColor foregroundColor (void) const;
+  QColor selectionColor (void) const;
+  QColor cursorColor (void) const;
+
+  void setBackgroundColor (const QColor& color);
+  void setForegroundColor (const QColor& color);
+  void setSelectionColor (const QColor& color);
+  void setCursorColor (bool useForegroundColor, const QColor& color);
+
+  void drawTextBackground (QPainter& p, int cx1, int cy1, int cx2, int cy2,
+                           int cw, int ch);
+
+  void drawSelection (QPainter& p, int cx1, int cy1, int cx2, int cy2,
+                      int cw, int ch);
+
+  void drawCursor (QPainter& p);
+
+  void drawText (QPainter& p, int cx1, int cy1, int cx2, int cy2,
+                 int cw, int ch);
+
 private:
   QWinTerminalImpl* q;
 
 private:
   QFont m_font;
-  QColor m_backgroundColor;
-  QColor m_foregroundColor;
   QString m_command;
   QConsoleColors m_colors;
   bool m_inWheelEvent;
@@ -126,6 +164,16 @@
   QSize m_bufferSize;
   QRect m_consoleRect;
   QPoint m_cursorPos;
+  bool m_cursorBlinking;
+  bool m_hasBlinkingCursor;
+  QTimer *m_blinkCursorTimer;
+  KeyboardCursorType m_cursorType;
+
+  QPoint m_beginSelection;
+  QPoint m_endSelection;
+
+  QColor m_selectionColor;
+  QColor m_cursorColor;
 
   HANDLE m_stdOut;
   HWND m_consoleWindow;
@@ -137,12 +185,24 @@
   QScrollBar* m_scrollBar;
   QTimer* m_consoleWatcher;
   QConsoleThread *m_consoleThread;
+
+  // The delay in milliseconds between redrawing blinking text.
+  static const int BLINK_DELAY = 500;
 };
 
+static void maybeSwapPoints (QPoint& begin, QPoint& end)
+{
+  if (end.y () < begin.y ()
+      || (end.y () == begin.y () && end.x () < begin.x ()))
+    qSwap (begin, end);
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 QConsolePrivate::QConsolePrivate (QWinTerminalImpl* parent, const QString& cmd)
-    : q (parent), m_command (cmd), m_process (NULL), m_inWheelEvent (false)
+  : q (parent), m_command (cmd), m_hasBlinkingCursor (true),
+    m_cursorType (BlockCursor), m_beginSelection (0, 0),
+    m_endSelection (0, 0), m_process (NULL), m_inWheelEvent (false)
 {
   log (NULL);
 
@@ -225,10 +285,6 @@
   GetConsoleTitleW (titleBuf, sizeof (titleBuf));
   q->setWindowTitle (QString::fromWCharArray (titleBuf));
 
-  m_backgroundColor = Qt::white;
-  m_foregroundColor = Qt::black;
-  SetConsoleTextAttribute (m_stdOut, 0xF0);
-
   m_font.setFamily ("Lucida Console");
   m_font.setPointSize (9);
   m_font.setStyleHint (QFont::TypeWriter);
@@ -244,8 +300,26 @@
   l->addWidget (m_consoleView, 1);
   l->addWidget (m_scrollBar, 0);
 
-  m_consoleView->setPalette (QPalette (m_backgroundColor));
+  // Choose 15 (0xF) as index into the Windows console color map for the
+  // background and 0 (0x0) as the index for the foreground.  This
+  // selection corresponds to the indices used in the foregroundColor,
+  // setForegroundColor, backgroundColor, and SetBackgroundColor
+  // functions.
+
+  SetConsoleTextAttribute (m_stdOut, 0xF0);
+
+  // Defaults.
+  setBackgroundColor (Qt::white);
+  setForegroundColor (Qt::black);
+  setSelectionColor (Qt::lightGray);
+  setCursorColor (false, Qt::darkGray);
+
+  // FIXME -- should we set the palette?
+  QPalette palette (backgroundColor ());
+  m_consoleView->setPalette (palette);
+
   m_consoleView->setAutoFillBackground (true);
+
   m_consoleView->setFont (m_font);
   parent->setFocusPolicy (Qt::StrongFocus);
   parent->winId ();
@@ -255,7 +329,11 @@
   m_consoleWatcher = new QTimer (parent);
   m_consoleWatcher->setInterval (10);
   m_consoleWatcher->setSingleShot (false);
-  
+
+  m_blinkCursorTimer = new QTimer (parent);
+  QObject::connect (m_blinkCursorTimer, SIGNAL (timeout()),
+                    q, SLOT (blinkCursorEvent ()));  
+
   QObject::connect (m_scrollBar, SIGNAL (valueChanged (int)),
                     q, SLOT (scrollValueChanged (int)));
   QObject::connect (m_consoleWatcher, SIGNAL (timeout (void)),
@@ -319,7 +397,372 @@
     log ("Failed to open %s: errno=%d.\n", devName, errno);
 }
 
-//////////////////////////////////////////////////////////////////////////////
+QPoint QConsolePrivate::posToCell (const QPoint& p)
+{
+  return QPoint (m_consoleRect.left () + p.x () / m_charSize.width (),
+                 m_consoleRect.top () + p.y () / m_charSize.height ());
+}
+
+QString QConsolePrivate::getSelection (void)
+{
+  QString selection;
+
+  QPoint begin = m_beginSelection;
+  QPoint end = m_endSelection;
+
+  maybeSwapPoints (begin, end);
+
+  if (begin != end)
+    {
+      CHAR_INFO* buf;
+      COORD bufSize, bufCoord;
+      SMALL_RECT bufRect;
+      int nr;
+
+      nr = end.y () - begin.y () + 1;
+      buf =  new CHAR_INFO[m_bufferSize.width () * nr];
+      bufSize.X = m_bufferSize.width ();
+      bufSize.Y = nr;
+      bufCoord.X = 0;
+      bufCoord.Y = 0;
+
+      bufRect.Left = 0;
+      bufRect.Right = m_bufferSize.width ();
+      bufRect.Top = begin.y ();
+      bufRect.Bottom = end.y ();
+
+      if (ReadConsoleOutput (m_stdOut, buf, bufSize, bufCoord, &bufRect))
+        {
+          int start_pos = begin.x ();
+          int end_pos = (nr - 1) * m_bufferSize.width () + end.x ();
+          int lastNonSpace = -1;
+
+          for (int i = start_pos; i <= end_pos; i++)
+            {
+              if (i && (i % m_bufferSize.width ()) == 0)
+                {
+                  if (lastNonSpace >= 0)
+                    selection.truncate (lastNonSpace);
+                  selection.append ('\n');
+                  lastNonSpace = selection.length ();
+                }
+
+              QChar c (buf[i].Char.UnicodeChar);
+
+              selection.append (c);
+              if (! c.isSpace ())
+                lastNonSpace = selection.length ();
+            }
+
+          if (lastNonSpace >= 0)
+            selection.truncate (lastNonSpace);
+        }
+    }
+
+  return selection;
+}
+
+void QConsolePrivate::updateSelection (void)
+{
+  QPoint begin = m_beginSelection;
+  QPoint end = m_endSelection;
+
+  maybeSwapPoints (begin, end);
+
+  begin.rx () = 0;
+  end.rx () = m_consoleRect.width ();
+
+  m_consoleView->update ();
+}
+
+void QConsolePrivate::clearSelection (void)
+{
+  m_beginSelection = m_endSelection = QPoint ();
+
+  m_consoleView->update ();
+}
+
+QColor QConsolePrivate::backgroundColor (void) const
+{
+  return m_colors[15];
+}
+
+QColor QConsolePrivate::foregroundColor (void) const
+{
+  return m_colors[0];
+}
+
+QColor QConsolePrivate::selectionColor (void) const
+{
+  return m_selectionColor;
+}
+
+QColor QConsolePrivate::cursorColor (void) const
+{
+  return m_cursorColor.isValid () ? m_cursorColor : foregroundColor ();
+}
+
+void QConsolePrivate::setBackgroundColor (const QColor& color)
+{
+  m_colors[15] = color;
+}
+
+void QConsolePrivate::setForegroundColor (const QColor& color)
+{
+  m_colors[0] = color;
+}
+
+void QConsolePrivate::setSelectionColor (const QColor& color)
+{
+  m_selectionColor = color;
+}
+
+void QConsolePrivate::setCursorColor (bool useForegroundColor,
+                                      const QColor& color)
+{
+  m_cursorColor = useForegroundColor ? QColor () : color;
+}
+
+void QConsolePrivate::drawTextBackground (QPainter& p, int cx1, int cy1,
+                                          int cx2, int cy2, int cw, int ch)
+{
+  p.save ();
+
+  int ascent = p.fontMetrics ().ascent ();
+  int stride = m_consoleRect.width ();
+  int y = ascent + cy1 * ch;;
+
+  for (int j = cy1; j <= cy2; j++, y += ch)
+    {
+      int len = 0;
+      bool hasChar = false;
+      int x = cx1 * cw;
+      WORD attr = 0;
+
+      for (int i = cx1; i <= cx2; i++)
+        {
+          CHAR_INFO* ci = &(m_buffer[stride*j+i]);
+
+          if ((ci->Attributes & 0x00ff) != attr)
+            {
+              // Character attributes changed
+              if (len != 0)
+                {
+                  // String buffer not empty -> draw it
+                  if (hasChar || (attr & 0x00f0))
+                    {
+                      if (attr & 0x00f0)
+                        p.fillRect (x, y-ascent, len * cw, ch, p.brush ());
+                    }
+
+                  x += (len * cw);
+                  len = 0;
+                  hasChar = false;
+                }
+              // Update current brush and store current attributes
+              attr = (ci->Attributes & 0x00ff);
+              p.setBrush (m_colors[(attr >> 4) & 0x000f]);
+            }
+
+          // Append current character to the string buffer
+          len++;
+          if (ci->Char.UnicodeChar != L' ')
+            hasChar = true;
+        }
+
+      if (len != 0 && (hasChar || (attr & 0x00f0)))
+        {
+          // Line end reached, but string buffer not empty -> draw it
+          // No need to update s or x, they will be reset on the next
+          // for-loop iteration
+
+          if (attr & 0x00f0)
+            p.fillRect (x, y-ascent, len * cw, ch, p.brush ());
+        }
+    }
+
+  p.restore ();
+}
+
+void QConsolePrivate::drawSelection (QPainter& p, int cx1, int cy1,
+                                     int cx2, int cy2, int cw, int ch)
+{
+  p.save ();
+
+  QPoint begin = m_beginSelection;
+  QPoint end = m_endSelection;
+
+  bool haveSelection = (begin != end);
+
+  if (haveSelection)
+    maybeSwapPoints (begin, end);
+
+  int scrollOffset = m_consoleRect.top ();
+
+  begin.ry () -= scrollOffset;
+  end.ry () -= scrollOffset;
+
+  int ascent = p.fontMetrics ().ascent ();
+  int stride = m_consoleRect.width ();
+
+  int y = ascent + cy1 * ch;;
+  for (int j = cy1; j <= cy2; j++, y += ch)
+    {
+      int charsThisLine = 0;
+      int len = 0;
+      bool hasChar = false;
+      WORD attr = 0;
+
+      for (int i = cx1; i <= cx2; i++)
+        {
+          CHAR_INFO* ci = &(m_buffer[stride*j+i]);
+
+          if ((ci->Attributes & 0x00ff) != attr)
+            {
+              // Character attributes changed
+              if (len != 0)
+                {
+                  charsThisLine += len;
+                  len = 0;
+                  hasChar = false;
+                }
+
+              // Store current attributes
+              attr = (ci->Attributes & 0x00ff);
+            }
+
+          // Append current character to the string buffer
+          len++;
+          if (ci->Char.UnicodeChar != L' ')
+            hasChar = true;
+        }
+
+      if (len != 0 && (hasChar || (attr & 0x00f0)))
+        charsThisLine += len;
+
+      if (haveSelection && j >= begin.y () && j <= end.y ())
+        {
+          int selectionBegin = j == begin.y () ? begin.x (): 0;
+
+          int len = ((j == end.y () && end.x () < charsThisLine)
+                     ? end.x () - selectionBegin + 1
+                     : stride - selectionBegin);
+
+          p.fillRect (selectionBegin * cw, y-ascent, len * cw, ch,
+                      selectionColor ());
+        }
+    }
+
+  p.restore ();
+}
+
+void QConsolePrivate::drawCursor (QPainter& p)
+{
+  if (! m_cursorBlinking)
+    {
+      p.save ();
+
+      QRect rect = cursorRect ();
+      QColor color = cursorColor ();
+
+      p.setPen (color);
+
+      if (m_cursorType == QConsolePrivate::BlockCursor)
+        {
+          if (q->hasFocus ())
+            p.fillRect (rect, color);
+          else
+            {
+              // draw the cursor outline, adjusting the area so that
+              // it is draw entirely inside 'rect'
+ 
+              int penWidth = qMax (1, p.pen().width());
+ 
+              p.drawRect (rect.adjusted (penWidth/2, penWidth/2,
+                                         - penWidth/2 - penWidth%2,
+                                         - penWidth/2 - penWidth%2));
+            }
+        }
+      else if (m_cursorType == QConsolePrivate::UnderlineCursor)
+        {
+          p.drawLine (rect.left (), rect.bottom (),
+                      rect.right (), rect.bottom ());
+        }
+      else if (m_cursorType == QConsolePrivate::IBeamCursor)
+        {
+          p.drawLine (rect.left (), rect.top (),
+                      rect.left (), rect.bottom ());
+        }
+
+      p.restore ();
+    }
+}
+
+void QConsolePrivate::drawText (QPainter& p, int cx1, int cy1,
+                                int cx2, int cy2, int cw, int ch)
+{
+  p.save ();
+
+  p.setFont (m_font);
+  p.setPen (foregroundColor ());
+
+  QString s;
+  s.reserve (cx2 - cx1 + 1);
+
+  int ascent = p.fontMetrics ().ascent ();
+  int stride = m_consoleRect.width ();
+
+  int y = ascent + cy1 * ch;;
+  for (int j = cy1; j <= cy2; j++, y += ch)
+    {
+      // Reset string buffer and starting X coordinate
+      s.clear ();
+      bool hasChar = false;
+      int x = cx1 * cw;
+      WORD attr = 0;
+
+      for (int i = cx1; i <= cx2; i++)
+        {
+          CHAR_INFO* ci = &(m_buffer[stride*j+i]);
+
+          if ((ci->Attributes & 0x00ff) != attr)
+            {
+              // Character attributes changed
+              if (! s.isEmpty ())
+                {
+                  // String buffer not empty -> draw it
+                  if (hasChar || (attr & 0x00f0))
+                    p.drawText (x, y, s);
+
+                  x += (s.length () * cw);
+                  s.clear ();
+                  hasChar = false;
+                }
+              // Update current pen and store current attributes
+              attr = (ci->Attributes & 0x00ff);
+              p.setPen (m_colors[attr & 0x000f]);
+            }
+
+          // Append current character to the string buffer
+          s.append (ci->Char.UnicodeChar);
+          if (ci->Char.UnicodeChar != L' ')
+            hasChar = true;
+        }
+
+      if (! s.isEmpty () && (hasChar || (attr & 0x00f0)))
+        {
+          // Line end reached, but string buffer not empty -> draw it
+          // No need to update s or x, they will be reset on the next
+          // for-loop iteration
+
+          p.drawText (x, y, s);
+        }
+    }
+
+  p.restore ();
+}
+
+/////////////////////////////////////////////////////////////////////////////
 
 void QConsolePrivate::closeStandardIO (int fd, DWORD stdHandleId,
                                        const char* name)
@@ -363,10 +806,10 @@
   QFontMetrics fm (m_font);
   QSize winSize = m_consoleView->size ();
 
-  m_charSize.rwidth () = fm.maxWidth ();
+  m_charSize.rwidth () = fm.averageCharWidth ();
   m_charSize.rheight () = fm.lineSpacing ();
 
-  m_consoleRect.setWidth (winSize.width () / fm.maxWidth ());
+  m_consoleRect.setWidth (winSize.width () / fm.averageCharWidth ());
   m_consoleRect.setHeight (winSize.height () / fm.lineSpacing ());
 
   m_bufferSize.rwidth () = m_consoleRect.width ();
@@ -700,17 +1143,28 @@
     }
 }
 
+QRect
+QConsolePrivate::cursorRect (void)
+{
+  int cw = m_charSize.width ();
+  int ch = m_charSize.height ();
+
+  return QRect ((m_cursorPos.x () - m_consoleRect.x ()) * cw,
+                (m_cursorPos.y () - m_consoleRect.y ()) * ch,
+                cw, ch);
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 QWinTerminalImpl::QWinTerminalImpl (QWidget* parent)
-    : QTerminalInterface (parent), d (new QConsolePrivate (this))
+    : QTerminal (parent), d (new QConsolePrivate (this))
 {
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
 QWinTerminalImpl::QWinTerminalImpl (const QString& cmd, QWidget* parent)
-    : QTerminalInterface (parent), d (new QConsolePrivate (this, cmd))
+    : QTerminal (parent), d (new QConsolePrivate (this, cmd))
 {
 }
 
@@ -721,6 +1175,29 @@
   delete d;
 }
 
+void QWinTerminalImpl::mouseMoveEvent (QMouseEvent *event)
+{
+  d->m_endSelection = d->posToCell (event->pos ());
+
+  updateSelection ();
+}
+
+void QWinTerminalImpl::mousePressEvent (QMouseEvent *event)
+{
+  if (event->button () == Qt::LeftButton)
+    d->m_beginSelection = d->posToCell (event->pos ());
+}
+
+void QWinTerminalImpl::mouseReleaseEvent (QMouseEvent *event)
+{
+  if (event->button () == Qt::LeftButton)
+    {
+      d->m_endSelection = d->posToCell (event->pos ());
+
+      updateSelection ();
+    }
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 void QWinTerminalImpl::viewResizeEvent (QConsoleView*, QResizeEvent*)
@@ -734,89 +1211,56 @@
 void QWinTerminalImpl::viewPaintEvent (QConsoleView* w, QPaintEvent* event)
 {
   QPainter p (w);
-  int cw = d->m_charSize.width (), ch = d->m_charSize.height ();
-  int ascent, stride, cx1, cy1, cx2, cy2, x, y;
-  WORD attr = 0;
-  QString s;
-  bool hasChar = false;
+
+  int cw = d->m_charSize.width ();
+  int ch = d->m_charSize.height ();
 
   QRect updateRect = event->rect ();
 
-  cx1 = updateRect.left () / cw;
-  cy1 = updateRect.top () / ch;
-  cx2 = qMin (d->m_consoleRect.width () - 1, updateRect.right () / cw);
-  cy2 = qMin (d->m_consoleRect.height () - 1, updateRect.bottom () / ch);
+  int cx1 = updateRect.left () / cw;
+  int cy1 = updateRect.top () / ch;
+  int cx2 = qMin (d->m_consoleRect.width () - 1, updateRect.right () / cw);
+  int cy2 = qMin (d->m_consoleRect.height () - 1, updateRect.bottom () / ch);
 
   if (cx1 > d->m_consoleRect.width () - 1
       || cy1 > d->m_consoleRect.height () - 1)
     return;
 
-  p.setFont (d->m_font);
-  p.setPen (d->m_foregroundColor);
-
-  ascent = p.fontMetrics ().ascent ();
-  stride = d->m_consoleRect.width ();
-
-  s.reserve (cx2 - cx1 + 1);
-  y = ascent + cy1 * ch;;
+  d->drawTextBackground (p, cx1, cy1, cx2, cy2, cw, ch);
+  d->drawSelection (p, cx1, cy1, cx2, cy2, cw, ch);
+  d->drawCursor (p);
+  d->drawText (p, cx1, cy1, cx2, cy2, cw, ch);
+}
 
-  for (int j = cy1; j <= cy2; j++, y += ch)
-    {
-      // Reset string buffer and starting X coordinate
-      s.clear ();
-      hasChar = false;
-      x = cx1 * cw;
+void QWinTerminalImpl::blinkCursorEvent (void)
+{
+  if (d->m_hasBlinkingCursor)
+    d->m_cursorBlinking = ! d->m_cursorBlinking;
+  else
+    d->m_cursorBlinking = false;
 
-      for (int i = cx1; i <= cx2; i++)
-        {
-          CHAR_INFO* ci = &(d->m_buffer[stride*j+i]);
+  d->m_consoleView->update (d->cursorRect ());
+}
 
-          if ((ci->Attributes & 0x00ff) != attr)
-            {
-              // Character attributes changed
-              if (! s.isEmpty ())
-                {
-                  // String buffer not empty -> draw it
-                  if (hasChar || (attr & 0x00f0))
-                    {
-                      if (attr & 0x00f0)
-                        p.fillRect (x, y-ascent, s.length () * cw, ch,
-                                    p.brush ());
-                      p.drawText (x, y, s);
-                    }
-                  x += (s.length () * cw);
-                  s.clear ();
-                  hasChar = false;
-                }
-              // Update current pen and store current attributes
-              // FIXME: what about background?
-              attr = (ci->Attributes & 0x00ff);
-              p.setPen (d->m_colors[attr & 0x000f]);
-              p.setBrush (d->m_colors[(attr >> 4) & 0x000f]);
-            }
+void QWinTerminalImpl::setBlinkingCursor (bool blink)
+{
+  d->m_hasBlinkingCursor = blink;
+
+  setBlinkingCursorState (blink);
+}
 
-          // Append current character to the string buffer
-          s.append (ci->Char.UnicodeChar);
-          if (ci->Char.UnicodeChar != L' ')
-            hasChar = true;
-        }
+void QWinTerminalImpl::setBlinkingCursorState (bool blink)
+{
+  if (blink && ! d->m_blinkCursorTimer->isActive ())
+    d->m_blinkCursorTimer->start (d->BLINK_DELAY);
 
-      if (! s.isEmpty () && (hasChar || (attr & 0x00f0)))
-        {
-          // Line end reached, but string buffer not empty -> draw it
-          // No need to update s or x, they will be reset on the next
-          // for-loop iteration
-          if (attr & 0x00f0)
-            p.fillRect (x, y-ascent, s.length () * cw, ch, p.brush ());
-          p.drawText (x, y, s);
-        }
+  if (! blink && d->m_blinkCursorTimer->isActive ())
+    {
+      d->m_blinkCursorTimer->stop ();
+
+      if (d->m_cursorBlinking)
+        blinkCursorEvent ();
     }
-
-  // Draw cursor
-  p.setCompositionMode (QPainter::RasterOp_SourceXorDestination);
-  p.fillRect ((d->m_cursorPos.x () - d->m_consoleRect.x ()) * cw,
-              (d->m_cursorPos.y () - d->m_consoleRect.y ()) * ch,
-              cw, ch, d->m_colors[7]);
 }
 
 //////////////////////////////////////////////////////////////////////////////
@@ -867,13 +1311,43 @@
   d->monitorConsole ();
 }
 
+void QWinTerminalImpl::updateSelection (void)
+{
+  d->updateSelection ();
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 void QWinTerminalImpl::focusInEvent (QFocusEvent* event)
 {
+  setBlinkingCursorState (true);
+
   QWidget::focusInEvent (event);
 }
 
+void QWinTerminalImpl::focusOutEvent (QFocusEvent* event)
+{
+  // Force the cursor to be redrawn.
+  d->m_cursorBlinking = true;
+
+  setBlinkingCursorState (false);
+
+  QWidget::focusOutEvent (event);
+}
+
+void QWinTerminalImpl::keyPressEvent (QKeyEvent* event)
+{
+  if (d->m_hasBlinkingCursor)
+    {
+      d->m_blinkCursorTimer->start (d->BLINK_DELAY);
+
+      if (d->m_cursorBlinking)
+        blinkCursorEvent ();
+    }
+
+  QWidget::keyPressEvent (event);
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 void QWinTerminalImpl::start (void)
@@ -888,6 +1362,47 @@
   d->sendConsoleText (s);
 }
 
+void QWinTerminalImpl::setCursorType (CursorType type, bool blinking)
+{
+  switch (type)
+    {
+    case UnderlineCursor:
+      d->m_cursorType = QConsolePrivate::UnderlineCursor;
+      break;
+
+    case BlockCursor:
+      d->m_cursorType = QConsolePrivate::BlockCursor;
+      break;
+
+    case IBeamCursor:
+      d->m_cursorType = QConsolePrivate::IBeamCursor;
+      break;
+    }
+
+  setBlinkingCursor (blinking);
+}
+
+void QWinTerminalImpl::setBackgroundColor (const QColor& color)
+{
+  d->setBackgroundColor (color);
+}
+
+void QWinTerminalImpl::setForegroundColor (const QColor& color)
+{
+  d->setForegroundColor (color);
+}
+
+void QWinTerminalImpl::setSelectionColor (const QColor& color)
+{
+  d->setSelectionColor (color);
+}
+
+void QWinTerminalImpl::setCursorColor (bool useForegroundColor,
+                                       const QColor& color)
+{
+  d->setCursorColor (useForegroundColor, color);
+}
+
 //////////////////////////////////////////////////////////////////////////////
 
 void QWinTerminalImpl::setTerminalFont (const QFont& f)
@@ -909,10 +1424,17 @@
 
 void QWinTerminalImpl::copyClipboard (void)
 {
+  QClipboard *clipboard = QApplication::clipboard ();
+
+  clipboard->setText (d->getSelection ());
 }
 
 //////////////////////////////////////////////////////////////////////////////
 
 void QWinTerminalImpl::pasteClipboard (void)
 {
+  QString text = QApplication::clipboard()->text (QClipboard::Clipboard);
+
+  if (! text.isEmpty ())
+    sendText (text);
 }
--- a/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/qterminal/libqterminal/win32/QWinTerminalImpl.h	Sun May 12 21:45:57 2013 -0400
@@ -23,12 +23,14 @@
 #define __QConsole_h__ 1
 
 #include <QWidget>
-#include "QTerminalInterface.h"
+#include "QTerminal.h"
 class QFocusEvent;
 class QKeyEvent;
+class QPainter;
 class QPaintEvent;
 class QResizeEvent;
 class QWheelEvent;
+class QPoint;
 
 class QConsolePrivate;
 class QConsoleThread;
@@ -36,7 +38,7 @@
 
 //////////////////////////////////////////////////////////////////////////////
 
-class QWinTerminalImpl : public QTerminalInterface
+class QWinTerminalImpl : public QTerminal
 {
   Q_OBJECT
   friend class QConsolePrivate;
@@ -51,10 +53,17 @@
   void setTerminalFont (const QFont& font);
   void setSize (int columns, int lines);
   void sendText (const QString& s);
+  void setCursorType (CursorType type, bool blinking);
+
+  void setBackgroundColor (const QColor& color);
+  void setForegroundColor (const QColor& color);
+  void setSelectionColor (const QColor& color);
+  void setCursorColor (bool useForegoundColor, const QColor& color);
 
 public slots:
   void copyClipboard (void);
   void pasteClipboard (void);
+  void blinkCursorEvent (void);
 
 signals:
   void terminated (void);
@@ -62,15 +71,23 @@
 
 protected:
   void viewPaintEvent (QConsoleView*, QPaintEvent*);
+  void setBlinkingCursor (bool blink);
+  void setBlinkingCursorState (bool blink);
   void viewResizeEvent (QConsoleView*, QResizeEvent*);
   void wheelEvent (QWheelEvent*);
   void focusInEvent (QFocusEvent*);
+  void focusOutEvent (QFocusEvent*);
+  void keyPressEvent (QKeyEvent*);
   bool winEvent (MSG*, long*);
   virtual void start (void);
+  void mouseMoveEvent (QMouseEvent *event);
+  void mousePressEvent (QMouseEvent *event);
+  void mouseReleaseEvent (QMouseEvent *event);
 
 private slots:
   void scrollValueChanged (int value);
   void monitorConsole (void);
+  void updateSelection (void);
 
 private:
   QConsolePrivate* d;
--- a/libgui/src/color-picker.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/color-picker.cc	Sun May 12 21:45:57 2013 -0400
@@ -29,6 +29,7 @@
 {
   _color = old_color;
   setFlat (true);
+  setFocusPolicy(Qt::NoFocus);  // no focus, would changes the color
   update_button ();
   connect(this, SIGNAL (clicked ()), SLOT (select_color ()));
 }
@@ -48,8 +49,17 @@
 // draw the button with the actual color (using a stylesheet)
 void color_picker::update_button ()
 {
-  QString css = QString("background-color: %1; border: none;" )
-                        .arg(_color.name());
+  // Is this the right place to look for a "foreground" color that would
+  // provide a reasonable border for the color swatches?
+  QWidget *p = parentWidget ();
+
+  QString bordercolor
+    = p ? p->palette().text().color().name() : QString ("#000000");
+
+  QString css = QString("background-color: %1; border: 1px solid %2;")
+                        .arg(_color.name())
+                        .arg(bordercolor);
+
   setStyleSheet(css);
   repaint ();
 }
--- a/libgui/src/dialog.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/dialog.cc	Sun May 12 21:45:57 2013 -0400
@@ -163,7 +163,7 @@
           // Make the last button the button pressed when <esc> key activated.
           if (i == N-1)
             {
-#define ACTIVE_ESCAPE true
+#define ACTIVE_ESCAPE 1
 #if ACTIVE_ESCAPE
               setEscapeButton (pbutton);
 #else
@@ -231,7 +231,7 @@
       for (int j = 0; j < prompt.length (); j++)
         {
           if (j > 0)
-#define RICH_TEXT true
+#define RICH_TEXT 1
 #if RICH_TEXT
             prompt_string.append ("<br>");
 #else
@@ -327,7 +327,7 @@
   : QDialog ()
 {
 
-#define LINE_EDIT_FOLLOWS_PROMPT false
+#define LINE_EDIT_FOLLOWS_PROMPT 0
 
 #if LINE_EDIT_FOLLOWS_PROMPT
     // Prompt on left followed by input on right.
--- a/libgui/src/files-dock-widget.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/files-dock-widget.cc	Sun May 12 21:45:57 2013 -0400
@@ -28,9 +28,9 @@
 #include "files-dock-widget.h"
 
 #include <QApplication>
+#include <QClipboard>
 #include <QFileInfo>
 #include <QCompleter>
-#include <QSettings>
 #include <QProcess>
 #include <QDebug>
 #include <QHeaderView>
@@ -42,9 +42,23 @@
 #include <QToolButton>
 #include <QUrl>
 #include <QDesktopServices>
+#include <QFileDialog>
 
 #include "load-save.h"
 
+class FileTreeViewer : public QTreeView
+{
+public:
+
+  FileTreeViewer (QWidget *p) : QTreeView (p) { }
+
+  void mousePressEvent (QMouseEvent *e)
+  {
+    if (e->button () != Qt::RightButton)
+      QTreeView::mousePressEvent (e);
+  }
+};
+
 files_dock_widget::files_dock_widget (QWidget *p)
   : octave_dock_widget (p)
 {
@@ -63,9 +77,6 @@
   connect (this, SIGNAL (displayed_directory_changed (const QString&)),
            parent (), SLOT (set_current_working_directory (const QString&)));
 
-  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
-           this, SLOT (notice_settings (const QSettings *)));
-
   // Create a toolbar
   _navigation_tool_bar = new QToolBar ("", container);
   _navigation_tool_bar->setAllowedAreas (Qt::TopToolBarArea);
@@ -104,6 +115,10 @@
   popdown_button->setDefaultAction(new QAction(QIcon(":/actions/icons/gear.png"),"", _navigation_tool_bar));
 
   popdown_menu->addSeparator();
+  popdown_menu->addAction (QIcon (":/actions/icons/search.png"),
+                           tr ("Search directory"),
+                           this, SLOT (popdownmenu_search_dir (bool)));
+  popdown_menu->addSeparator();
   popdown_menu->addAction(QIcon(":/actions/icons/filenew.png"),
                           tr ("New File"),
                           this, SLOT(popdownmenu_newfile(bool)));
@@ -130,7 +145,8 @@
                                                   curr_dir.absolutePath ());
 
   // Attach the model to the QTreeView and set the root index
-  _file_tree_view = new QTreeView (container);
+  _file_tree_view = new FileTreeViewer (container);
+  _file_tree_view->setSelectionMode (QAbstractItemView::ExtendedSelection);
   _file_tree_view->setModel (_file_system_model);
   _file_tree_view->setRootIndex (rootPathIndex);
   _file_tree_view->setSortingEnabled (true);
@@ -178,8 +194,8 @@
   connect (_current_directory, SIGNAL (activated (const QString &)),
            this, SLOT (set_current_directory (const QString &)));
 
-  connect (this, SIGNAL (run_file_signal (const QString&)),
-           parent (), SLOT (execute_command_in_terminal (const QString&)));
+  connect (this, SIGNAL (run_file_signal (const QFileInfo&)),
+           parent (), SLOT (run_file_in_terminal (const QFileInfo&)));
 
   QCompleter *completer = new QCompleter (_file_system_model, this);
   _current_directory->setCompleter (completer);
@@ -327,6 +343,9 @@
       menu.addAction (tr("Open in Default Application"),
                       this, SLOT (contextmenu_open_in_app (bool)));
 
+      menu.addAction (tr("Copy Selection to Clipboard"),
+                      this, SLOT (contextmenu_copy_selection (bool)));
+
       if (info.isFile () && info.suffix () == "m")
         menu.addAction (QIcon (":/actions/icons/artsbuilderexecute.png"),
                         tr("Run"), this, SLOT(contextmenu_run(bool)));
@@ -387,6 +406,26 @@
 }
 
 void
+files_dock_widget::contextmenu_copy_selection (bool)
+{
+  QItemSelectionModel *m = _file_tree_view->selectionModel ();
+  QModelIndexList rows = m->selectedRows ();
+
+  QStringList selection;
+
+  for (QModelIndexList::iterator it = rows.begin (); it != rows.end (); it++)
+    {
+      QFileInfo info = _file_system_model->fileInfo (*it);
+
+      selection << info.fileName ();
+    }
+
+  QClipboard *clipboard = QApplication::clipboard ();
+
+  clipboard->setText (selection.join ("\n"));
+}
+
+void
 files_dock_widget::contextmenu_load (bool)
 {
   QItemSelectionModel *m = _file_tree_view->selectionModel ();
@@ -413,12 +452,7 @@
       QModelIndex index = rows[0];
 
       QFileInfo info = _file_system_model->fileInfo(index);
-
-      QString function_name = info.fileName ();
-      // We have to cut off the suffix, because octave appends it.
-      function_name.chop (info.suffix ().length () + 1);
-      emit run_file_signal (QString ("cd \'%1\'\n%2\n")
-                            .arg(info.absolutePath ()).arg (function_name));
+      emit run_file_signal (info);
     }
 }
 
@@ -573,6 +607,14 @@
 }
 
 void
+files_dock_widget::popdownmenu_search_dir (bool)
+{
+  QString dir
+    = QFileDialog::getExistingDirectory (this, tr ("Set directory of file browser"));
+  process_set_current_dir (dir);
+}
+
+void
 files_dock_widget::popdownmenu_newdir (bool)
 {
       process_new_dir(_file_system_model->rootPath());
@@ -620,4 +662,3 @@
 {
   emit displayed_directory_changed (dir);
 }
-
--- a/libgui/src/files-dock-widget.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/files-dock-widget.h	Sun May 12 21:45:57 2013 -0400
@@ -34,7 +34,7 @@
 #include <QVBoxLayout>
 #include <QAction>
 #include <QTreeView>
-#include <QSettings>
+#include <QMouseEvent>
 
 #include <QComboBox>
 #include "octave-dock-widget.h"
@@ -86,6 +86,7 @@
   /* context menu actions */
   void contextmenu_open (bool);
   void contextmenu_open_in_app (bool);
+  void contextmenu_copy_selection (bool);
   void contextmenu_run (bool);
   void contextmenu_load (bool);
   void contextmenu_rename (bool);
@@ -97,6 +98,7 @@
   /* popdown menu options */
   void popdownmenu_newfile(bool);
   void popdownmenu_newdir(bool);
+  void popdownmenu_search_dir (bool);
 
 signals:
 
@@ -110,7 +112,7 @@
   void load_file_signal (const QString& fileName);
 
   /** Emitted, whenever the user requested to run a file. */
-  void run_file_signal (const QString& fileName);
+  void run_file_signal (const QFileInfo& info);
 
 private:
   void process_new_file(const QString &parent_name);
Binary file libgui/src/icons/fileclose.png has changed
--- a/libgui/src/m-editor/file-editor-tab.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/file-editor-tab.cc	Sun May 12 21:45:57 2013 -0400
@@ -48,14 +48,8 @@
 #include "file-editor-tab.h"
 #include "file-editor.h"
 
-#include "cmd-edit.h"
-
-#include "builtin-defun-decls.h"
 #include "debug.h"
-#include "load-path.h"
-#include "octave-link.h"
-#include "oct-env.h"
-#include "utils.h"
+#include "octave-qt-link.h"
 
 // Make parent null for the file editor tab so that warning
 // WindowModal messages don't affect grandparents.
@@ -63,6 +57,8 @@
 {
   QString directory = directory_arg;
 
+  _app_closing = false;
+
   // Make sure there is a slash at the end of the directory name
   // for identification when saved later.
   if (directory.count () && directory.at (directory.count () - 1) != '/')
@@ -355,25 +351,6 @@
   delete printer;
 }
 
-
-void
-file_editor_tab::run_file_callback (const bp_info& info)
-{
-  if (file_in_path (info.file, info.dir))
-    {
-      std::string pending_input = command_editor::get_current_line ();
-
-      command_editor::set_initial_input (pending_input);
-
-      command_editor::replace_line (info.function_name);
-      command_editor::redisplay ();
-
-      // We are executing inside the command editor event loop.  Force
-      // the current line to be returned for processing.
-      command_editor::interrupt ();
-    }
-}
-
 void
 file_editor_tab::run_file (const QWidget *ID)
 {
@@ -383,14 +360,8 @@
   if (_edit_area->isModified ())
     save_file (_file_name);
 
-  QFileInfo file_info (_file_name);
-  QString dir = file_info.absolutePath ();
-  QString function_name = file_info.fileName ();
-  function_name.chop (file_info.suffix ().length () + 1);
-
-  bp_info info (_file_name, dir, function_name, 1);
-
-  octave_link::post_event (this, &file_editor_tab::run_file_callback, info);
+  QFileInfo info (_file_name);
+  emit run_file_signal (info);
 }
 
 void
@@ -451,77 +422,13 @@
   _edit_area->markerDeleteAll (bookmark);
 }
 
-bool
-file_editor_tab::file_in_path (const std::string& file, const std::string& dir)
-{
-  bool ok = false;
-  bool addpath_option = true;
-
-  std::string curr_dir = octave_env::get_current_directory ();
-
-  if (same_file (curr_dir, dir))
-    ok = true;
-  else
-    {
-      bool dir_in_load_path = load_path::contains_canonical (dir);
-
-      std::string base_file = octave_env::base_pathname (file);
-      std::string lp_file = load_path::find_file (base_file);
-
-      if (dir_in_load_path)
-        {
-          if (same_file (lp_file, file))
-            ok = true;
-        }
-      else
-        {
-          // File directory is not in path.  Is the file in the path in
-          // the current directory?  If so, then changing the current
-          // directory will be needed.  Adding directory to path is
-          // not enough because the file in the current directory would
-          // still be found.
-
-          if (same_file (lp_file, base_file))
-            {
-              if (same_file (curr_dir, dir))
-                ok = true;
-              else
-                addpath_option = false;
-            }
-        }
-    }
-
-  if (! ok)
-    {
-      int action
-        = octave_link::debug_cd_or_addpath_error (file, dir, addpath_option);
-      switch (action)
-        {
-        case 1:
-          Fcd (ovl (dir));
-          ok = true;
-          break;
-
-        case 2:
-          load_path::prepend (dir);
-          ok = true;
-          break;
-
-        default:
-          break;
-        }
-    }
-
-  return ok;
-}
-
 void
 file_editor_tab::add_breakpoint_callback (const bp_info& info)
 {
   bp_table::intmap line_info;
   line_info[0] = info.line;
 
-  if (file_in_path (info.file, info.dir))
+  if (octave_qt_link::file_in_path (info.file, info.dir))
     bp_table::add_breakpoint (info.function_name, line_info);
 }
 
@@ -531,14 +438,14 @@
   bp_table::intmap line_info;
   line_info[0] = info.line;
 
-  if (file_in_path (info.file, info.dir))
+  if (octave_qt_link::file_in_path (info.file, info.dir))
     bp_table::remove_breakpoint (info.function_name, line_info);
 }
 
 void
 file_editor_tab::remove_all_breakpoints_callback (const bp_info& info)
 {
-  if (file_in_path (info.file, info.dir))
+  if (octave_qt_link::file_in_path (info.file, info.dir))
     bp_table::remove_all_breakpoints_in_file (info.function_name, true);
 }
 
@@ -803,22 +710,40 @@
       // File is modified but not saved, ask user what to do.  The file
       // editor tab can't be made parent because it may be deleted depending
       // upon the response.  Instead, change the _edit_area to read only.
+      QMessageBox::StandardButtons buttons = QMessageBox::Save |
+                                             QMessageBox::Discard;
+      QString available_actions;
+
+      if (_app_closing)
+          available_actions = tr ("Do you want to save or discard the changes?");
+      else
+        {
+          buttons = buttons | QMessageBox::Cancel;  // cancel is allowed
+          available_actions
+            = tr ("Do you want to cancel closing, save or discard the changes?");
+        }
+
       QMessageBox* msgBox
         = new QMessageBox (QMessageBox::Warning, tr ("Octave Editor"),
                            tr ("The file\n"
                                "%1\n"
                                "is about to be closed but has been modified.\n"
-                               "Do you want to cancel closing, save or discard the changes?").
-                           arg (_file_name),
-                           QMessageBox::Save | QMessageBox::Cancel | QMessageBox::Discard, 0);
+                               "%2").
+                           arg (_file_name). arg (available_actions),
+                           buttons, qobject_cast<QWidget *> (parent ()));
 
       msgBox->setDefaultButton (QMessageBox::Save);
       _edit_area->setReadOnly (true);
       connect (msgBox, SIGNAL (finished (int)),
                this, SLOT (handle_file_modified_answer (int)));
-      msgBox->setWindowModality (Qt::NonModal);
       msgBox->setAttribute (Qt::WA_DeleteOnClose);
-      msgBox->show ();
+      if (_app_closing)  // app is closing, a non modal dialogs prevent
+        msgBox->exec (); // the app of being closed before an answer from user
+      else
+        {
+          msgBox->setWindowModality (Qt::NonModal);
+          msgBox->show ();
+        }
 
       return QMessageBox::Cancel;
     }
@@ -1157,11 +1082,12 @@
 }
 
 void
-file_editor_tab::conditional_close (const QWidget *ID)
+file_editor_tab::conditional_close (const QWidget *ID, bool app_closing)
 {
   if (ID != this)
     return;
 
+  _app_closing = app_closing;
   close ();
 }
 
--- a/libgui/src/m-editor/file-editor-tab.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/file-editor-tab.h	Sun May 12 21:45:57 2013 -0400
@@ -27,7 +27,7 @@
 #include <QCloseEvent>
 #include <QFileSystemWatcher>
 #include <QSettings>
-
+#include <QFileInfo>
 #include <Qsci/qsciscintilla.h>
 
 #include "find-dialog.h"
@@ -55,7 +55,7 @@
   void notice_settings (const QSettings *settings);
 
   // Will initiate close if associated with the identifier tag.
-  void conditional_close (const QWidget *ID);
+  void conditional_close (const QWidget *ID, bool app_closing = false);
 
   // Change to a different editor tab by identifier tag.
   void change_editor_state (const QWidget *ID);
@@ -111,7 +111,7 @@
   void mru_add_file (const QString& file_name);
   void editor_check_conflict_save (const QString& saveFileName,
                                    bool remove_on_success);
-  void process_octave_code (const QString& command);
+  void run_file_signal (const QFileInfo& info);
 
 protected:
 
@@ -170,10 +170,6 @@
   int check_file_modified ();
   void do_comment_selected_text (bool comment);
 
-  void run_file_callback (const bp_info& info);
-
-  bool file_in_path (const std::string& file, const std::string& dir);
-
   void add_breakpoint_callback (const bp_info& info);
   void remove_breakpoint_callback (const bp_info& info);
   void remove_all_breakpoints_callback (const bp_info& info);
@@ -186,6 +182,7 @@
 
   bool _long_title;
   bool _copy_available;
+  bool _app_closing;
 
   QFileSystemWatcher _file_system_watcher;
 
--- a/libgui/src/m-editor/file-editor.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/file-editor.cc	Sun May 12 21:45:57 2013 -0400
@@ -72,6 +72,9 @@
   settings->setValue ("editor/savedSessionTabs", fetFileNames);
   settings->sync ();
 
+  for (int index = _tab_widget->count ()-1; index >= 0; index--)
+    emit fetab_close_request (_tab_widget->widget (index),true); // true: app closing
+
   if (_mru_file_menu)
     delete _mru_file_menu;
 }
@@ -319,9 +322,8 @@
 
 // open a file from the mru list
 void
-file_editor::request_mru_open_file (void)
+file_editor::request_mru_open_file (QAction *action)
 {
-  QAction *action = qobject_cast<QAction *> (sender ());
   if (action)
     {
       request_open_file (action->data ().toString ());
@@ -625,6 +627,33 @@
 }
 
 void
+file_editor::request_close_file (bool)
+{
+  emit fetab_close_request (_tab_widget->currentWidget ());
+}
+
+void
+file_editor::request_close_all_files (bool)
+{
+  // loop over all tabs starting from last one otherwise deletion changes index
+  for (int index = _tab_widget->count ()-1; index >= 0; index--)
+    emit fetab_close_request (_tab_widget->widget (index));
+}
+
+void
+file_editor::request_close_other_files (bool)
+{
+  QWidget *tabID = _tab_widget->currentWidget ();
+  // loop over all tabs starting from last one otherwise deletion changes index
+  for (int index = _tab_widget->count ()-1; index >= 0; index--)
+    {
+      if (tabID != _tab_widget->widget (index))
+        emit fetab_close_request (_tab_widget->widget (index));
+    }
+}
+
+
+void
 file_editor::handle_tab_close_request (int index)
 {
   // Signal to the tabs a request to close whomever matches the identifying
@@ -848,22 +877,40 @@
 
   // menu bar
   QMenu *fileMenu = new QMenu (tr ("&File"), _menu_bar);
-  fileMenu->addAction (new_action);
-  fileMenu->addAction (open_action);
-  fileMenu->addAction (save_action);
-  fileMenu->addAction (save_as_action);
-  fileMenu->addSeparator ();
+
   _mru_file_menu = new QMenu (tr ("&Recent Editor Files"), fileMenu);
-
   for (int i = 0; i < MaxMRUFiles; ++i)
     _mru_file_menu->addAction (_mru_file_actions[i]);
 
+  fileMenu->addAction (new_action);
+  fileMenu->addAction (open_action);
   fileMenu->addMenu (_mru_file_menu);
-  _menu_bar->addMenu (fileMenu);
+
+  fileMenu->addSeparator ();
+  fileMenu->addAction (save_action);
+  fileMenu->addAction (save_as_action);
+
+  fileMenu->addSeparator ();
+  fileMenu->addAction (QIcon::fromTheme("window-close",
+                                      QIcon (":/actions/icons/fileclose.png")),
+                       tr ("&Close"),
+                       this, SLOT (request_close_file (bool)),
+                             QKeySequence::Close);
+  fileMenu->addAction (QIcon::fromTheme("window-close",
+                                      QIcon (":/actions/icons/fileclose.png")),
+                       tr ("Close All"),
+                       this, SLOT (request_close_all_files (bool)));
+  fileMenu->addAction (QIcon::fromTheme("window-close",
+                                      QIcon (":/actions/icons/fileclose.png")),
+                       tr ("Close Other Files"),
+                       this, SLOT (request_close_other_files (bool)));
 
   fileMenu->addSeparator ();
   fileMenu->addAction (print_action);
 
+  _menu_bar->addMenu (fileMenu);
+
+
   QMenu *editMenu = new QMenu (tr ("&Edit"), _menu_bar);
   editMenu->addAction (undo_action);
   editMenu->addAction (redo_action);
@@ -906,9 +953,6 @@
   editor_widget->setLayout (vbox_layout);
   setWidget (editor_widget);
 
-  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
-           this, SLOT (notice_settings (const QSettings *)));
-
   connect (parent (), SIGNAL (new_file_signal (const QString&)),
            this, SLOT (request_new_file (const QString&)));
 
@@ -984,12 +1028,8 @@
   connect (goto_line_action, SIGNAL (triggered ()),
            this, SLOT (request_goto_line ()));
 
-  // The actions of the mru file menu
-  for (int i = 0; i < MaxMRUFiles; ++i)
-    {
-      connect (_mru_file_actions[i], SIGNAL (triggered ()),
-               this, SLOT (request_mru_open_file ()));
-    }
+  connect (_mru_file_menu, SIGNAL (triggered (QAction *)),
+           this, SLOT (request_mru_open_file (QAction *)));
 
   mru_menu_update ();
 
@@ -1039,15 +1079,15 @@
   connect (f, SIGNAL (mru_add_file (const QString&)),
            this, SLOT (handle_mru_add_file (const QString&)));
 
-  connect (f, SIGNAL (process_octave_code (const QString&)),
-           parent (), SLOT (execute_command_in_terminal (const QString&)));
+  connect (f, SIGNAL (run_file_signal (const QFileInfo&)),
+           parent (), SLOT (run_file_in_terminal (const QFileInfo&)));
   
   // Signals from the file_editor non-trivial operations
   connect (this, SIGNAL (fetab_settings_changed (const QSettings *)),
            f, SLOT (notice_settings (const QSettings *)));
 
-  connect (this, SIGNAL (fetab_close_request (const QWidget*)),
-           f, SLOT (conditional_close (const QWidget*)));
+  connect (this, SIGNAL (fetab_close_request (const QWidget*,bool)),
+           f, SLOT (conditional_close (const QWidget*,bool)));
 
   connect (this, SIGNAL (fetab_change_request (const QWidget*)),
            f, SLOT (change_editor_state (const QWidget*)));
--- a/libgui/src/m-editor/file-editor.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/file-editor.h	Sun May 12 21:45:57 2013 -0400
@@ -29,7 +29,6 @@
 #include <QStatusBar>
 #include <QCloseEvent>
 #include <QTabWidget>
-#include <QSettings>
 
 #include <map>
 
@@ -63,7 +62,7 @@
 signals:
 
   void fetab_settings_changed (const QSettings *settings);
-  void fetab_close_request (const QWidget* ID);
+  void fetab_close_request (const QWidget* ID, bool app_closing = false);
   void fetab_change_request (const QWidget* ID);
   void fetab_file_name_query (const QWidget* ID);
   // Save is a ping-pong type of communication
@@ -106,7 +105,10 @@
   void request_new_script (const QString& commands);
   void request_new_function (const QString& commands);
   void request_open_file (void);
-  void request_mru_open_file (void);
+  void request_close_file (bool);
+  void request_close_all_files (bool);
+  void request_close_other_files (bool);
+  void request_mru_open_file (QAction *action);
   void request_print_file (void);
 
   void request_undo (void);
--- a/libgui/src/m-editor/lexer-octave-gui.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/lexer-octave-gui.cc	Sun May 12 21:45:57 2013 -0400
@@ -145,20 +145,29 @@
 QFont
 lexer_octave_gui::defaultFont (int style) const
 {
-  QFont font;
+  QFont f;
 
   switch (style)
     {
       case Keyword:
-        font = QsciLexer::defaultFont (style);
-        font.setBold(true);
+        f = QsciLexer::defaultFont (style);
+        f.setBold(true);
         break;
 
       default:
-        font = QsciLexer::defaultFont (style);
+        f = QsciLexer::defaultFont (style);
     }
 
-  return font;
+  return f;
+}
+
+// -----------------------------------------------------
+//  The style used for braces
+// -----------------------------------------------------
+int
+lexer_octave_gui::braceStyle() const
+{
+    return Operator;
 }
 
 // -----------------------------------------------------
--- a/libgui/src/m-editor/lexer-octave-gui.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/m-editor/lexer-octave-gui.h	Sun May 12 21:45:57 2013 -0400
@@ -56,6 +56,7 @@
   QString description (int style) const;
   QColor defaultColor (int style) const;
   QFont defaultFont (int style) const;
+  int braceStyle() const;
 
 private:
   lexer_octave_gui (const lexer_octave_gui &);
--- a/libgui/src/main-window.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/main-window.cc	Sun May 12 21:45:57 2013 -0400
@@ -87,9 +87,9 @@
   // Destroy the terminal first so that STDERR stream is redirected back
   // to its original pipe to capture error messages at exit.
 
+  delete editor_window;     // first one for dialogs of modified editor-tabs
   delete command_window;
   delete workspace_window;
-  delete editor_window;
   delete doc_browser_window;
   delete file_browser_window;
   delete history_window;
@@ -203,19 +203,18 @@
 }
 
 void
+main_window::run_file_in_terminal (const QFileInfo& info)
+{
+  octave_link::post_event (this, &main_window::run_file_callback, info);
+}
+
+void
 main_window::handle_new_figure_request (void)
 {
   octave_link::post_event (this, &main_window::new_figure_callback);
 }
 
 void
-main_window::handle_new_variable_request (void)
-{
-  QMessageBox::about (this, tr ("New Variable"),
-                      tr ("The new variable action is not implemented."));
-}
-
-void
 main_window::open_online_documentation_page (void)
 {
   QDesktopServices::openUrl (QUrl ("http://gnu.org/software/octave/doc/interpreter"));
@@ -1004,9 +1003,6 @@
   QAction *new_figure_action = new_menu->addAction (tr ("Figure"));
   new_figure_action->setEnabled (true);
 
-  QAction *new_variable_action = new_menu->addAction (tr ("Variable"));
-  new_variable_action->setEnabled (true);
-
   connect (_new_script_action, SIGNAL (triggered ()),
            editor_window, SLOT (request_new_script ()));
 
@@ -1015,9 +1011,6 @@
 
   connect (new_figure_action, SIGNAL (triggered ()),
            this, SLOT (handle_new_figure_request ()));
-
-  connect (new_variable_action, SIGNAL (triggered ()),
-           this, SLOT (handle_new_variable_request ()));
 }
 
 void
@@ -1459,6 +1452,17 @@
 }
 
 void
+main_window::run_file_callback (const QFileInfo& info)
+{
+  QString dir = info.absolutePath ();
+  QString function_name = info.fileName ();
+  function_name.chop (info.suffix ().length () + 1);
+  if (octave_qt_link::file_in_path (info.absoluteFilePath ().toStdString (),
+                                    dir.toStdString ()))
+    execute_command_callback (function_name.toStdString ());
+}
+
+void
 main_window::new_figure_callback (void)
 {
   Fbuiltin (ovl ("figure"));
@@ -1561,3 +1565,4 @@
 
 }
 
+
--- a/libgui/src/main-window.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/main-window.h	Sun May 12 21:45:57 2013 -0400
@@ -116,11 +116,10 @@
   void accept_directory_line_edit (void);
 
   void execute_command_in_terminal(const QString& dir);
+  void run_file_in_terminal(const QFileInfo& info);
 
   void handle_new_figure_request (void);
 
-  void handle_new_variable_request (void);
-
   void handle_enter_debugger (void);
   void handle_exit_debugger (void);
   void debug_continue (void);
@@ -213,6 +212,7 @@
   void clear_history_callback (void);
 
   void execute_command_callback (const std::string& command);
+  void run_file_callback (const QFileInfo& info);
 
   void new_figure_callback (void);
 
--- a/libgui/src/module.mk	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/module.mk	Sun May 12 21:45:57 2013 -0400
@@ -23,6 +23,7 @@
   src/icons/editcut.png \
   src/icons/editdelete.png \
   src/icons/editpaste.png \
+  src/icons/fileclose.png \
   src/icons/filenew.png \
   src/icons/fileopen.png \
   src/icons/fileprint.png \
--- a/libgui/src/octave-dock-widget.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/octave-dock-widget.h	Sun May 12 21:45:57 2013 -0400
@@ -24,6 +24,7 @@
 #define octave_dock_widget_h 1
 
 #include <QDockWidget>
+#include <QSettings>
 
 class octave_dock_widget : public QDockWidget
 {
@@ -39,6 +40,9 @@
 
     connect (this, SIGNAL (topLevelChanged (bool)),
              this, SLOT (top_level_changed (bool)));
+
+    connect (p, SIGNAL (settings_changed (const QSettings*)),
+             this, SLOT (notice_settings (const QSettings*)));
   }
 
   virtual ~octave_dock_widget () { }
@@ -49,6 +53,7 @@
              this, SLOT (handle_visibility (bool)));
   }
 
+
 signals:
 
   /** Custom signal that tells whether a user has clicked away
@@ -82,6 +87,10 @@
       focus ();
   }
 
+  virtual void notice_settings (const QSettings*)
+  {
+  }
+
 protected slots:
 
   /** Slot to steer changing visibility from outside. */
--- a/libgui/src/octave-gui.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/octave-gui.cc	Sun May 12 21:45:57 2013 -0400
@@ -29,6 +29,12 @@
 
 #include <iostream>
 
+#include <fcntl.h>
+
+#if defined (HAVE_SYS_IOCTL_H)
+#include <sys/ioctl.h>
+#endif
+
 #include "lo-utils.h"
 #include "oct-env.h"
 #include "syswait.h"
@@ -43,8 +49,13 @@
 static void
 dissociate_terminal (void)
 {
-#if ! defined (Q_OS_WIN32) || defined (Q_OS_CYGWIN)
+#if ! defined (__WIN32__) || defined (__CYGWIN__)
+# if defined (HAVE_SYS_IOCTL_H) && defined (TIOCNOTTY)
 
+  ioctl (0, TIOCNOTTY);
+
+# else
+ 
   pid_t pid = fork ();
 
   if (pid < 0)
@@ -74,6 +85,7 @@
             ? octave_wait::exitstatus (status) : 127);
     }
 
+# endif
 #endif
 }
 
@@ -103,6 +115,17 @@
           // update network-settings
           resource_manager::update_network_settings ();
 
+#if ! defined (__WIN32__) || defined (__CYGWIN__)
+          // If we were started from a launcher, TERM might not be
+          // defined, but we provide a terminal with xterm
+          // capabilities.
+
+          std::string term = octave_env::getenv ("TERM");
+
+          if (term.empty ())
+            octave_env::putenv ("TERM", "xterm");
+#endif
+
           // create main window, read settings, and show window
           main_window w;
           w.read_settings ();  // get widget settings after construction
--- a/libgui/src/octave-qt-link.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/octave-qt-link.cc	Sun May 12 21:45:57 2013 -0400
@@ -29,10 +29,13 @@
 #include <QStringList>
 
 #include "str-vec.h"
-
 #include "dialog.h"
 #include "error.h"
 #include "workspace-element.h"
+#include "builtin-defun-decls.h"
+#include "load-path.h"
+#include "oct-env.h"
+#include "utils.h"
 
 #include "octave-qt-link.h"
 
@@ -423,3 +426,68 @@
 {
   emit delete_debugger_pointer_signal (QString::fromStdString (file), line);
 }
+
+
+bool
+octave_qt_link::file_in_path (const std::string& file, const std::string& dir)
+{
+
+  bool ok = false;
+  bool addpath_option = true;
+
+  std::string curr_dir = octave_env::get_current_directory ();
+
+  if (same_file (curr_dir, dir))
+    ok = true;
+  else
+    {
+      bool dir_in_load_path = load_path::contains_canonical (dir);
+
+      std::string base_file = octave_env::base_pathname (file);
+      std::string lp_file = load_path::find_file (base_file);
+
+      if (dir_in_load_path)
+        {
+          if (same_file (lp_file, file))
+            ok = true;
+        }
+      else
+        {
+          // File directory is not in path.  Is the file in the path in
+          // the current directory?  If so, then changing the current
+          // directory will be needed.  Adding directory to path is
+          // not enough because the file in the current directory would
+          // still be found.
+
+          if (same_file (lp_file, base_file))
+            {
+              if (same_file (curr_dir, dir))
+                ok = true;
+              else
+                addpath_option = false;
+            }
+        }
+    }
+
+  if (! ok)
+    {
+      int action = debug_cd_or_addpath_error (file, dir, addpath_option);
+      switch (action)
+        {
+        case 1:
+          Fcd (ovl (dir));
+          ok = true;
+          break;
+
+        case 2:
+          load_path::prepend (dir);
+          ok = true;
+          break;
+
+        default:
+          break;
+        }
+    }
+
+  return ok;
+}
--- a/libgui/src/octave-qt-link.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/octave-qt-link.h	Sun May 12 21:45:57 2013 -0400
@@ -119,6 +119,7 @@
   void do_set_default_prompts (std::string& ps1, std::string& ps2,
                                std::string& ps4);
 
+  static bool file_in_path (const std::string& file, const std::string& dir);
 
 private:
 
--- a/libgui/src/resource-manager.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/resource-manager.cc	Sun May 12 21:45:57 2013 -0400
@@ -33,11 +33,14 @@
 
 #include "error.h"
 #include "file-ops.h"
+#include "help.h"
 #include "oct-env.h"
 #include "singleton-cleanup.h"
 
 #include "defaults.h"
 
+#include "QTerminal.h"
+#include "workspace-model.h"
 #include "resource-manager.h"
 
 resource_manager *resource_manager::instance = 0;
@@ -195,6 +198,30 @@
   QNetworkProxy::setApplicationProxy (proxy);
 }
 
+QStringList 
+resource_manager::storage_class_names (void)
+{
+  return workspace_model::storage_class_names ();
+}
+
+QList<QColor>
+resource_manager::storage_class_default_colors (void)
+{
+  return workspace_model::storage_class_default_colors ();
+}
+
+QStringList 
+resource_manager::terminal_color_names (void)
+{
+  return QTerminal::color_names ();
+}
+
+QList<QColor>
+resource_manager::terminal_default_colors (void)
+{
+  return QTerminal::default_colors ();
+}
+
 const char*
 resource_manager::octave_keywords (void)
 {
--- a/libgui/src/resource-manager.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/resource-manager.h	Sun May 12 21:45:57 2013 -0400
@@ -82,6 +82,14 @@
   }
 
   static const char *octave_keywords (void);
+  
+  static QString storage_class_chars (void) { return "afghip"; }
+  static QStringList storage_class_names (void);
+  static QList<QColor> storage_class_default_colors (void);
+
+  static QString terminal_color_chars (void) { return "fbsc"; }
+  static QStringList terminal_color_names (void);
+  static QList<QColor> terminal_default_colors (void);
 
 private:
 
--- a/libgui/src/resource.qrc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/resource.qrc	Sun May 12 21:45:57 2013 -0400
@@ -5,6 +5,7 @@
         <file>icons/editcut.png</file>
         <file>icons/editdelete.png</file>
         <file>icons/editpaste.png</file>
+        <file>icons/fileclose.png</file>
         <file>icons/filenew.png</file>
         <file>icons/fileopen.png</file>
         <file>icons/filesave.png</file>
--- a/libgui/src/settings-dialog.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/settings-dialog.cc	Sun May 12 21:45:57 2013 -0400
@@ -24,16 +24,17 @@
 #include <config.h>
 #endif
 
+#include "color-picker.h"
 #include "resource-manager.h"
+#include "workspace-model.h"
 #include "settings-dialog.h"
 #include "ui-settings-dialog.h"
-#include <QSettings>
 #include <QDir>
 #include <QFileInfo>
+#include <QVector>
 
 #ifdef HAVE_QSCINTILLA
 #include <QScrollArea>
-#include "color-picker.h"
 #include <Qsci/qscilexercpp.h>
 #include <Qsci/qscilexerbash.h>
 #include <Qsci/qscilexerperl.h>
@@ -96,6 +97,7 @@
   ui->useProxyServer->setChecked (settings->value ("useProxyServer",false).toBool ());
   ui->proxyHostName->setText (settings->value ("proxyHostName").toString ());
   ui->terminal_cursorBlinking->setChecked (settings->value ("terminal/cursorBlinking",true).toBool ());
+  ui->terminal_cursorUseForegroundColor->setChecked (settings->value ("terminal/cursorUseForegroundColor",true).toBool ());
 
   QString cursorType = settings->value ("terminal/cursorType","ibeam").toString ();
 
@@ -125,6 +127,12 @@
   ui->proxyUserName->setText (settings->value ("proxyUserName").toString ());
   ui->proxyPassword->setText (settings->value ("proxyPassword").toString ());
 
+  // qorkspace colors
+  read_workspace_colors (settings);
+
+  // terminal colors
+  read_terminal_colors (settings);
+
 #ifdef HAVE_QSCINTILLA
   // editor styles: create lexer, read settings, and create dialog elements
   QsciLexer *lexer;
@@ -146,7 +154,9 @@
   lexer = new QsciLexerBash ();
   read_lexer_settings (lexer,settings);
   delete lexer;
-#endif    
+#endif
+
+  ui->tabWidget->setCurrentIndex (settings->value("settings/last_tab",0).toInt ());
 }
 
 settings_dialog::~settings_dialog ()
@@ -177,11 +187,11 @@
   int styles[MaxLexerStyles];  // array for saving valid styles (enum is not continuous)
   int max_style = get_valid_lexer_styles (lexer, styles);
   QGridLayout *style_grid = new QGridLayout ();
-  QLabel *description[max_style];
-  QFontComboBox *select_font[max_style];
-  QSpinBox *font_size[max_style];
-  QCheckBox *attrib_font[3][max_style];
-  color_picker *color[max_style];
+  QVector<QLabel*> description (max_style);
+  QVector<QFontComboBox*> select_font (max_style);
+  QVector<QSpinBox*> font_size (max_style);
+  QVector<QCheckBox*> attrib_font (3 * max_style);
+  QVector<color_picker*> color (max_style);
   int default_size = 10;
   QFont default_font = QFont ();
   for (int i = 0; i < max_style; i++)  // create dialog elements for all styles
@@ -213,25 +223,25 @@
           font_size[i]->setValue (actual_font.pointSize ()-default_size);
           font_size[i]->setToolTip ("Difference to the defalt size");
         }
-      attrib_font[0][i] = new QCheckBox (tr("b"));
-      attrib_font[1][i] = new QCheckBox (tr("i"));
-      attrib_font[2][i] = new QCheckBox (tr("u"));
-      attrib_font[0][i]->setChecked(Qt::Checked && actual_font.bold ());
-      attrib_font[0][i]->setObjectName (actual_name+"_bold");
-      attrib_font[1][i]->setChecked(Qt::Checked && actual_font.italic ());
-      attrib_font[1][i]->setObjectName (actual_name+"_italic");
-      attrib_font[2][i]->setChecked(Qt::Checked && actual_font.underline ());
-      attrib_font[2][i]->setObjectName (actual_name+"_underline");
+      attrib_font[0+3*i] = new QCheckBox (tr("b"));
+      attrib_font[1+3*i] = new QCheckBox (tr("i"));
+      attrib_font[2+3*i] = new QCheckBox (tr("u"));
+      attrib_font[0+3*i]->setChecked(Qt::Checked && actual_font.bold ());
+      attrib_font[0+3*i]->setObjectName (actual_name+"_bold");
+      attrib_font[1+3*i]->setChecked(Qt::Checked && actual_font.italic ());
+      attrib_font[1+3*i]->setObjectName (actual_name+"_italic");
+      attrib_font[2+3*i]->setChecked(Qt::Checked && actual_font.underline ());
+      attrib_font[2+3*i]->setObjectName (actual_name+"_underline");
       color[i] = new color_picker (lexer->color (styles[i]));
       color[i]->setObjectName (actual_name+"_color");
       int column = 1;
-      style_grid->addWidget (description[i],   i,column++);
-      style_grid->addWidget (select_font[i],   i,column++);
-      style_grid->addWidget (font_size[i],     i,column++);
-      style_grid->addWidget (attrib_font[0][i],i,column++);
-      style_grid->addWidget (attrib_font[1][i],i,column++);
-      style_grid->addWidget (attrib_font[2][i],i,column++);
-      style_grid->addWidget (color[i],         i,column++);
+      style_grid->addWidget (description[i],     i, column++);
+      style_grid->addWidget (select_font[i],     i, column++);
+      style_grid->addWidget (font_size[i],       i, column++);
+      style_grid->addWidget (attrib_font[0+3*i], i, column++);
+      style_grid->addWidget (attrib_font[1+3*i], i, column++);
+      style_grid->addWidget (attrib_font[2+3*i], i, column++);
+      style_grid->addWidget (color[i],           i, column++);
     }
   // place grid with elements into the tab
   QScrollArea *scroll_area = new QScrollArea ();
@@ -240,9 +250,87 @@
   scroll_area_contents->setLayout (style_grid);
   scroll_area->setWidget (scroll_area_contents);
   ui->tabs_editor_styles->addTab (scroll_area,lexer->language ());
+
+  ui->tabs_editor_styles->setCurrentIndex (
+          settings->value("settings/last_editor_styles_tab",0).toInt ());
 }
 #endif  
 
+void
+settings_dialog::read_workspace_colors (QSettings *settings)
+{
+
+  QList<QColor> default_colors = resource_manager::storage_class_default_colors ();
+  QStringList class_names = resource_manager::storage_class_names ();
+  QString class_chars = resource_manager::storage_class_chars ();
+  int nr_of_classes = class_chars.length ();
+
+  QGridLayout *style_grid = new QGridLayout ();
+  QVector<QLabel*> description (nr_of_classes);
+  QVector<color_picker*> color (nr_of_classes);
+
+  int column = 0;
+  int row = 0;
+  for (int i = 0; i < nr_of_classes; i++)
+    {
+      description[i] = new QLabel (class_names.at (i));
+      description[i]->setAlignment (Qt::AlignRight);
+      QVariant default_var = default_colors.at (i);
+      QColor setting_color = settings->value ("workspaceview/color_"+class_chars.mid (i,1),
+                                              default_var).value<QColor> ();
+      color[i] = new color_picker (setting_color);
+      color[i]->setObjectName ("color_"+class_chars.mid (i,1));
+      color[i]->setMinimumSize (30,10);
+      style_grid->addWidget (description[i], row,3*column);
+      style_grid->addWidget (color[i],       row,3*column+1);
+      if (++column == 3)
+        {
+          row++;
+          column = 0;
+        }
+    }
+
+  // place grid with elements into the tab
+  ui->workspace_colors_box->setLayout (style_grid);
+}
+
+void
+settings_dialog::read_terminal_colors (QSettings *settings)
+{
+
+  QList<QColor> default_colors = resource_manager::terminal_default_colors ();
+  QStringList class_names = resource_manager::terminal_color_names ();
+  QString class_chars = resource_manager::terminal_color_chars ();
+  int nr_of_classes = class_chars.length ();
+
+  QGridLayout *style_grid = new QGridLayout ();
+  QVector<QLabel*> description (nr_of_classes);
+  QVector<color_picker*> color (nr_of_classes);
+
+  int column = 0;
+  int row = 0;
+  for (int i = 0; i < nr_of_classes; i++)
+    {
+      description[i] = new QLabel (class_names.at (i));
+      description[i]->setAlignment (Qt::AlignRight);
+      QVariant default_var = default_colors.at (i);
+      QColor setting_color = settings->value ("terminal/color_"+class_chars.mid (i,1),
+                                              default_var).value<QColor> ();
+      color[i] = new color_picker (setting_color);
+      color[i]->setObjectName ("terminal_color_"+class_chars.mid (i,1));
+      color[i]->setMinimumSize (30,10);
+      style_grid->addWidget (description[i], row,2*column);
+      style_grid->addWidget (color[i],       row,2*column+1);
+      if (++column == 2)
+        {
+          row++;
+          column = 0;
+        }
+    }
+
+  // place grid with elements into the tab
+  ui->terminal_colors_box->setLayout (style_grid);
+}
 
 void
 settings_dialog::write_changed_settings ()
@@ -288,6 +376,7 @@
   settings->setValue ("proxyUserName", ui->proxyUserName->text ());
   settings->setValue ("proxyPassword", ui->proxyPassword->text ());
   settings->setValue ("terminal/cursorBlinking", ui->terminal_cursorBlinking->isChecked ());
+  settings->setValue ("terminal/cursorUseForegroundColor", ui->terminal_cursorUseForegroundColor->isChecked ());
 
   // the cursor
   QString cursorType;
@@ -322,6 +411,12 @@
   write_lexer_settings (lexer,settings);
   delete lexer;
 #endif
+
+  write_workspace_colors (settings);
+
+  write_terminal_colors (settings);
+
+  settings->setValue("settings/last_tab",ui->tabWidget->currentIndex ());
 }
 
 #ifdef HAVE_QSCINTILLA
@@ -380,5 +475,43 @@
         lexer->setColor (color->color (),styles[i]);
     }
   lexer->writeSettings (*settings);
+
+  settings->setValue (
+    "settings/last_editor_styles_tab",ui->tabs_editor_styles->currentIndex ());
 }
 #endif
+
+void
+settings_dialog::write_workspace_colors (QSettings *settings)
+{
+
+  QString class_chars = resource_manager::storage_class_chars ();
+  color_picker *color;
+
+  for (int i = 0; i < class_chars.length (); i++)
+    {
+      color = ui->workspace_colors_box->findChild <color_picker *>(
+                            "color_"+class_chars.mid (i,1));
+      if (color)
+        settings->setValue ("workspaceview/color_"+class_chars.mid (i,1),
+                            color->color ());
+    }
+  settings->sync ();
+}
+
+void
+settings_dialog::write_terminal_colors (QSettings *settings)
+{
+  QString class_chars = resource_manager::terminal_color_chars ();
+  color_picker *color;
+
+  for (int i = 0; i < class_chars.length (); i++)
+    {
+      color = ui->terminal_colors_box->findChild <color_picker *>(
+                            "terminal_color_"+class_chars.mid (i,1));
+      if (color)
+        settings->setValue ("terminal/color_"+class_chars.mid (i,1),
+                            color->color ());
+    }
+  settings->sync ();
+}
--- a/libgui/src/settings-dialog.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/settings-dialog.h	Sun May 12 21:45:57 2013 -0400
@@ -24,6 +24,7 @@
 #define SETTINGSDIALOG_H
 
 #include <QDialog>
+#include <QSettings>
 #ifdef HAVE_QSCINTILLA
 #include "lexer-octave-gui.h"
 #endif
@@ -49,6 +50,12 @@
   enum { MaxLexerStyles = 64,
          MaxStyleNumber = 128 };
 #endif
+
+  void read_workspace_colors (QSettings *settings);
+  void write_workspace_colors (QSettings *settings);
+
+  void read_terminal_colors (QSettings *settings);
+  void write_terminal_colors (QSettings *settings);
 };
 
 #endif // SETTINGSDIALOG_H
--- a/libgui/src/settings-dialog.ui	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/settings-dialog.ui	Sun May 12 21:45:57 2013 -0400
@@ -32,7 +32,7 @@
    <item>
     <widget class="QTabWidget" name="tabWidget">
      <property name="currentIndex">
-      <number>0</number>
+      <number>3</number>
      </property>
      <widget class="QWidget" name="tab_4">
       <property name="enabled">
@@ -317,126 +317,167 @@
       <attribute name="title">
        <string>Terminal</string>
       </attribute>
-      <layout class="QVBoxLayout" name="verticalLayout">
-       <item>
-        <layout class="QHBoxLayout" name="horizontalLayout_5">
-         <item>
-          <widget class="QLabel" name="label_11">
-           <property name="text">
-            <string>Font</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QFontComboBox" name="terminal_fontName">
-           <property name="editable">
-            <bool>false</bool>
-           </property>
-           <property name="fontFilters">
-            <set>QFontComboBox::MonospacedFonts</set>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QLabel" name="label_12">
-           <property name="text">
-            <string>Font Size</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QSpinBox" name="terminal_fontSize">
-           <property name="minimum">
-            <number>2</number>
-           </property>
-           <property name="maximum">
-            <number>96</number>
-           </property>
-           <property name="value">
-            <number>10</number>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer_5">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item>
-        <layout class="QHBoxLayout" name="horizontalLayout_3">
-         <item>
-          <widget class="QLabel" name="label">
-           <property name="text">
-            <string>Cursor type:</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <widget class="QComboBox" name="terminal_cursorType"/>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item>
-        <layout class="QHBoxLayout" name="horizontalLayout_2">
-         <item>
-          <widget class="QCheckBox" name="terminal_cursorBlinking">
-           <property name="text">
-            <string>Cursor blinking</string>
-           </property>
-          </widget>
-         </item>
-         <item>
-          <spacer name="horizontalSpacer_2">
-           <property name="orientation">
-            <enum>Qt::Horizontal</enum>
-           </property>
-           <property name="sizeHint" stdset="0">
-            <size>
-             <width>40</width>
-             <height>20</height>
-            </size>
-           </property>
-          </spacer>
-         </item>
-        </layout>
-       </item>
-       <item>
-        <spacer name="verticalSpacer_3">
-         <property name="orientation">
-          <enum>Qt::Vertical</enum>
-         </property>
-         <property name="sizeHint" stdset="0">
-          <size>
-           <width>20</width>
-           <height>321</height>
-          </size>
-         </property>
-        </spacer>
-       </item>
-      </layout>
+      <widget class="QWidget" name="horizontalLayoutWidget">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>50</y>
+         <width>631</width>
+         <height>31</height>
+        </rect>
+       </property>
+       <layout class="QHBoxLayout" name="horizontalLayout_3">
+        <item>
+         <widget class="QLabel" name="label">
+          <property name="text">
+           <string>Cursor type:</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QComboBox" name="terminal_cursorType"/>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+        <item>
+         <widget class="QCheckBox" name="terminal_cursorBlinking">
+          <property name="text">
+           <string>Cursor blinking</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QCheckBox" name="terminal_cursorUseForegroundColor">
+          <property name="text">
+           <string>Use Foreground Color</string>
+          </property>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="verticalLayoutWidget_2">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>90</y>
+         <width>631</width>
+         <height>164</height>
+        </rect>
+       </property>
+       <layout class="QVBoxLayout" name="verticalLayout">
+        <item>
+         <widget class="QGroupBox" name="terminal_colors_box">
+          <property name="minimumSize">
+           <size>
+            <width>0</width>
+            <height>162</height>
+           </size>
+          </property>
+          <property name="title">
+           <string>Terminal Colors</string>
+          </property>
+         </widget>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="verticalLayoutWidget_3">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>260</y>
+         <width>631</width>
+         <height>121</height>
+        </rect>
+       </property>
+       <layout class="QVBoxLayout" name="verticalLayout_8">
+        <item>
+         <spacer name="verticalSpacer_3">
+          <property name="orientation">
+           <enum>Qt::Vertical</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>20</width>
+            <height>40</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
+      <widget class="QWidget" name="layoutWidget">
+       <property name="geometry">
+        <rect>
+         <x>10</x>
+         <y>10</y>
+         <width>631</width>
+         <height>30</height>
+        </rect>
+       </property>
+       <layout class="QHBoxLayout" name="horizontalLayout_5">
+        <item>
+         <widget class="QLabel" name="label_11">
+          <property name="text">
+           <string>Font</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QFontComboBox" name="terminal_fontName">
+          <property name="editable">
+           <bool>false</bool>
+          </property>
+          <property name="fontFilters">
+           <set>QFontComboBox::MonospacedFonts</set>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QLabel" name="label_12">
+          <property name="text">
+           <string>Font Size</string>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <widget class="QSpinBox" name="terminal_fontSize">
+          <property name="minimum">
+           <number>2</number>
+          </property>
+          <property name="maximum">
+           <number>96</number>
+          </property>
+          <property name="value">
+           <number>10</number>
+          </property>
+         </widget>
+        </item>
+        <item>
+         <spacer name="horizontalSpacer_5">
+          <property name="orientation">
+           <enum>Qt::Horizontal</enum>
+          </property>
+          <property name="sizeHint" stdset="0">
+           <size>
+            <width>40</width>
+            <height>20</height>
+           </size>
+          </property>
+         </spacer>
+        </item>
+       </layout>
+      </widget>
      </widget>
      <widget class="QWidget" name="tab_2">
       <attribute name="title">
@@ -500,6 +541,30 @@
        </item>
       </layout>
      </widget>
+     <widget class="QWidget" name="tab_workspace">
+      <attribute name="title">
+       <string>Workspace</string>
+      </attribute>
+      <widget class="QGroupBox" name="workspace_colors_box">
+       <property name="geometry">
+        <rect>
+         <x>19</x>
+         <y>19</y>
+         <width>631</width>
+         <height>81</height>
+        </rect>
+       </property>
+       <property name="minimumSize">
+        <size>
+         <width>0</width>
+         <height>81</height>
+        </size>
+       </property>
+       <property name="title">
+        <string>Storage Class Colors</string>
+       </property>
+      </widget>
+     </widget>
      <widget class="QWidget" name="tab_3">
       <attribute name="title">
        <string>Network</string>
--- a/libgui/src/terminal-dock-widget.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/terminal-dock-widget.cc	Sun May 12 21:45:57 2013 -0400
@@ -28,7 +28,7 @@
 #include "terminal-dock-widget.h"
 
 terminal_dock_widget::terminal_dock_widget (QWidget *p)
-  : octave_dock_widget (p), terminal (new QTerminal (p))
+  : octave_dock_widget (p), terminal (QTerminal::create (p))
 {
   terminal->setObjectName ("OctaveTerminal");
   terminal->setFocusPolicy (Qt::StrongFocus);
@@ -38,9 +38,6 @@
   setWindowTitle (tr ("Command Window"));
   setWidget (terminal);
 
-  connect (parent (), SIGNAL (settings_changed (const QSettings *)),
-           this, SLOT (notice_settings (const QSettings *)));
-
   connect (this, SIGNAL (visibilityChanged (bool)),
            this, SLOT (handle_visibility (bool)));
 
--- a/libgui/src/workspace-model.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/workspace-model.cc	Sun May 12 21:45:57 2013 -0400
@@ -26,9 +26,10 @@
 #endif
 
 #include <QTreeWidget>
+#include <QSettings>
 
 #include "utils.h"
-
+#include "resource-manager.h"
 #include "workspace-model.h"
 
 workspace_model::workspace_model (QObject *p)
@@ -39,16 +40,57 @@
   _columnNames.append (tr ("Dimension"));
   _columnNames.append (tr ("Value"));
   _columnNames.append (tr ("Storage Class"));
+
+  for (int i = 0; i < resource_manager::storage_class_chars ().length (); i++)
+    _storage_class_colors.append (QColor (Qt::white));
+
+}
+
+QList<QColor>
+workspace_model::storage_class_default_colors (void)
+{
+  QList<QColor> colors;
+
+  if (colors.isEmpty ())
+    {
+      colors << QColor (190,255,255)
+             << QColor (220,255,220)
+             << QColor (220,220,255)
+             << QColor (255,255,190)
+             << QColor (255,220,220)
+             << QColor (255,190,255);
+    }
+
+  return colors;
+}
+
+
+QStringList
+workspace_model::storage_class_names (void)
+{
+  QStringList names;
+
+  if (names.isEmpty ())
+    {
+      names << QObject::tr ("automatic")
+            << QObject::tr ("function")
+            << QObject::tr ("global")
+            << QObject::tr ("hidden")
+            << QObject::tr ("inherited")
+            << QObject::tr ("persistent");
+    }
+
+  return names;
 }
 
 int
-workspace_model::rowCount(const QModelIndex& p) const
+workspace_model::rowCount (const QModelIndex&) const
 {
   return _symbols.size ();
 }
 
 int
-workspace_model::columnCount (const QModelIndex& p) const
+workspace_model::columnCount (const QModelIndex&) const
 {
   return _columnNames.size ();
 }
@@ -84,53 +126,56 @@
 {
   QVariant retval;
 
-  if (idx.isValid ()
-      && (role == Qt::DisplayRole
-          || (idx.column () == 0 && (role == Qt::EditRole
-                                     || role == Qt::ToolTipRole))))
+  if (idx.isValid ())
     {
-      switch (idx.column ())
+      if (role == Qt::BackgroundColorRole)
         {
-        case 0:
-          if (role == Qt::ToolTipRole)
-            retval = QVariant (tr ("Right click to copy, rename, or display"));
+          QString class_chars = resource_manager::storage_class_chars ();
+          int actual_class = class_chars.indexOf (_scopes[idx.row()].toAscii ());
+          if (actual_class >= 0)
+            return QVariant (_storage_class_colors.at (actual_class));
           else
-            retval = QVariant (_symbols[idx.row()]);
-          break;
+            return retval;
+        }
 
-        case 1:
-          retval = QVariant (_class_names[idx.row()]);
-          break;
-
-        case 2:
-          retval = QVariant (_dimensions[idx.row()]);
-          break;
+      if (role == Qt::DisplayRole
+          || (idx.column () == 0 && role == Qt::EditRole)
+          || (idx.column () == 0 && role == Qt::ToolTipRole) )
+        {
+          switch (idx.column ())
+            {
+            case 0:
+              if (role == Qt::ToolTipRole)
+                retval = QVariant (tr ("Right click to copy, rename, or display"));
+              else
+                retval = QVariant (_symbols[idx.row()]);
+              break;
 
-        case 3:
-          retval = QVariant (_values[idx.row()]);
-          break;
+            case 1:
+              retval = QVariant (_class_names[idx.row()]);
+              break;
 
-        case 4:
-          {
-            QChar c = _scopes[idx.row()];
+            case 2:
+              retval = QVariant (_dimensions[idx.row()]);
+              break;
+
+            case 3:
+              retval = QVariant (_values[idx.row()]);
+              break;
 
-            if (c == 'g')
-              retval = QVariant (tr ("global"));
-            else if (c == 'p')
-              retval = QVariant (tr ("persistent"));
-            else if (c == 'a')
-              retval = QVariant (tr ("automatic"));
-            else if (c == 'f')
-              retval = QVariant (tr ("function parameter"));
-            else if (c == 'h')
-              retval = QVariant (tr ("hidden"));
-            else if (c == 'i')
-              retval = QVariant (tr ("inherited"));
+            case 4:
+              retval = QVariant ();
+              QString class_chars = resource_manager::storage_class_chars ();
+              int actual_class = class_chars.indexOf (_scopes[idx.row()].toAscii ());
+              if (actual_class >= 0)
+                {
+                  QStringList class_names = resource_manager::storage_class_names ();
+                  retval = QVariant (class_names.at (actual_class));
+                }
+              break;
+
           }
-
-        default:
-          break;
-        }
+      }
     }
 
   return retval;
@@ -213,3 +258,18 @@
 
   emit model_changed ();
 }
+
+void
+workspace_model::notice_settings (const QSettings *settings)
+{
+  QList<QColor> default_colors = resource_manager::storage_class_default_colors ();
+  QString class_chars = resource_manager::storage_class_chars ();
+
+  for (int i = 0; i < class_chars.length (); i++)
+    {
+      QVariant default_var = default_colors.at (i);
+      QColor setting_color = settings->value ("workspaceview/color_"+class_chars.mid (i,1),
+                                             default_var).value<QColor> ();
+      _storage_class_colors.replace (i,setting_color);
+    }
+}
--- a/libgui/src/workspace-model.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/workspace-model.h	Sun May 12 21:45:57 2013 -0400
@@ -28,6 +28,10 @@
 #include <QVector>
 #include <QSemaphore>
 #include <QStringList>
+#include <QChar>
+#include <QList>
+#include <QColor>
+#include <QSettings>
 
 class workspace_model
   : public QAbstractTableModel
@@ -40,6 +44,10 @@
 
   ~workspace_model (void) { }
 
+  static QList<QColor> storage_class_default_colors (void);
+
+  static QStringList storage_class_names (void);
+
   QVariant data (const QModelIndex& index, int role) const;
 
   bool setData (const QModelIndex& index, const QVariant& value,
@@ -56,6 +64,8 @@
 
   bool is_top_level (void) const { return _top_level; }
 
+  QColor storage_class_color (int s_class) { return _storage_class_colors.at (s_class); }
+
 public slots:
 
   void set_workspace (bool top_level,
@@ -67,6 +77,8 @@
 
   void clear_workspace (void);
 
+  void notice_settings (const QSettings *);
+
 signals:
 
   void model_changed (void);
@@ -86,6 +98,9 @@
   QStringList _values;
 
   QStringList _columnNames;
+
+  QList<QColor>  _storage_class_colors;
+
 };
 
 #endif
--- a/libgui/src/workspace-view.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/workspace-view.cc	Sun May 12 21:45:57 2013 -0400
@@ -77,6 +77,7 @@
 
   connect (this, SIGNAL (command_requested (const QString&)),
            p, SLOT (execute_command_in_terminal (const QString&)));
+
 }
 
 workspace_view::~workspace_view (void)
@@ -89,6 +90,12 @@
   settings->sync ();
 }
 
+void workspace_view::setModel (workspace_model *model)
+{
+  view->setModel (model);
+  _model = model;
+}
+
 void
 workspace_view::closeEvent (QCloseEvent *e)
 {
@@ -242,3 +249,20 @@
     view->setRowHeight (i, row_height);
   view_previous_row_count = new_row_count;
 }
+
+void
+workspace_view::notice_settings (const QSettings *settings)
+{
+  _model->notice_settings (settings); // update colors of model first
+
+  QString tool_tip;
+  tool_tip  =  QString (tr ("View the variables in the active workspace.<br>"));
+  tool_tip +=  QString (tr ("Colors for the storage class:"));
+  for (int i = 0; i < resource_manager::storage_class_chars ().length (); i++)
+    {
+      tool_tip +=  QString ("<div style=\"background-color:%1;color:#000000\">%2</div>")
+               .arg (_model->storage_class_color (i).name ())
+               .arg (resource_manager::storage_class_names ().at (i));
+    }
+  setToolTip (tool_tip);
+}
--- a/libgui/src/workspace-view.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libgui/src/workspace-view.h	Sun May 12 21:45:57 2013 -0400
@@ -41,9 +41,11 @@
 
   ~workspace_view (void);
 
-public:
+public slots:
 
-  void setModel (workspace_model *model) { view->setModel (model); }
+  void notice_settings (const QSettings *);
+
+  void setModel (workspace_model *model);
 
 signals:
 
@@ -73,6 +75,7 @@
 
   QTableView *view;
   int view_previous_row_count;
+  workspace_model *_model;
 };
 
 #endif
--- a/libinterp/interpfcn/debug.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/debug.cc	Sun May 12 21:45:57 2013 -0400
@@ -274,6 +274,36 @@
   return retval;
 }
 
+bool
+bp_table::do_add_breakpoint_1 (octave_user_code *fcn,
+                               const std::string& fname,
+                               const bp_table::intmap& line,
+                               bp_table::intmap& retval)
+{
+  bool found = false;
+
+  tree_statement_list *cmds = fcn->body ();
+
+  std::string file = fcn->fcn_file_name ();
+
+  if (cmds)
+    {
+      retval = cmds->add_breakpoint (file, line);
+
+      for (intmap_iterator p = retval.begin (); p != retval.end (); p++)
+        {
+          if (p->second != 0)
+            {
+              bp_set.insert (fname);
+              found = true;
+              break;
+            }
+        }
+    }
+
+  return found;
+}
+
 bp_table::intmap
 bp_table::do_add_breakpoint (const std::string& fname,
                              const bp_table::intmap& line)
@@ -284,20 +314,28 @@
 
   if (dbg_fcn)
     {
-      tree_statement_list *cmds = dbg_fcn->body ();
-
-      std::string file = dbg_fcn->fcn_file_name ();
-
-      if (cmds)
+      if (! do_add_breakpoint_1 (dbg_fcn, fname, line, retval))
         {
-          retval = cmds->add_breakpoint (file, line);
+          // Search subfunctions in the order they appear in the file.
+
+          const std::list<std::string> subfcn_names
+            = dbg_fcn->subfunction_names ();
 
-          for (intmap_iterator p = retval.begin (); p != retval.end (); p++)
+          std::map<std::string, octave_value> subfcns
+            = dbg_fcn->subfunctions ();
+
+          for (std::list<std::string>::const_iterator p = subfcn_names.begin ();
+               p != subfcn_names.end (); p++)
             {
-              if (p->second != 0)
+              std::map<std::string, octave_value>::const_iterator
+                q = subfcns.find (*p);
+
+              if (q != subfcns.end ())
                 {
-                  bp_set.insert (fname);
-                  break;
+                  octave_user_code *dbg_subfcn = q->second.user_code_value ();
+
+                  if (do_add_breakpoint_1 (dbg_subfcn, fname, line, retval))
+                    break;
                 }
             }
         }
@@ -312,6 +350,56 @@
 
 
 int
+bp_table::do_remove_breakpoint_1 (octave_user_code *fcn,
+                                  const std::string& fname,
+                                  const bp_table::intmap& line)
+{
+  int retval = 0;
+
+  std::string file = fcn->fcn_file_name ();
+
+  tree_statement_list *cmds = fcn->body ();
+
+  // FIXME -- move the operation on cmds to the
+  // tree_statement_list class?
+
+  if (cmds)
+    {
+      octave_value_list results = cmds->list_breakpoints ();
+
+      if (results.length () > 0)
+        {
+          octave_idx_type len = line.size ();
+
+          for (int i = 0; i < len; i++)
+            {
+              const_intmap_iterator p = line.find (i);
+
+              if (p != line.end ())
+                {
+                  int lineno = p->second;
+
+                  cmds->delete_breakpoint (lineno);
+
+                  if (! file.empty ())
+                    octave_link::update_breakpoint (false, file, lineno);
+                }
+            }
+
+          results = cmds->list_breakpoints ();
+
+          bp_set_iterator it = bp_set.find (fname);
+          if (results.length () == 0 && it != bp_set.end ())
+            bp_set.erase (it);
+        }
+
+      retval = results.length ();
+    }
+
+  return retval;
+}
+
+int
 bp_table::do_remove_breakpoint (const std::string& fname,
                                 const bp_table::intmap& line)
 {
@@ -330,41 +418,28 @@
 
       if (dbg_fcn)
         {
-          std::string file = dbg_fcn->fcn_file_name ();
+          retval = do_remove_breakpoint_1 (dbg_fcn, fname, line);
 
-          tree_statement_list *cmds = dbg_fcn->body ();
+          // Search subfunctions in the order they appear in the file.
 
-          // FIXME -- move the operation on cmds to the
-          // tree_statement_list class?
-          if (cmds)
-            {
-              octave_value_list results = cmds->list_breakpoints ();
+          const std::list<std::string> subfcn_names
+            = dbg_fcn->subfunction_names ();
 
-              if (results.length () > 0)
-                {
-                  for (int i = 0; i < len; i++)
-                    {
-                      const_intmap_iterator p = line.find (i);
+          std::map<std::string, octave_value> subfcns
+            = dbg_fcn->subfunctions ();
 
-                      if (p != line.end ())
-                        {
-                          int lineno = p->second;
-
-                          cmds->delete_breakpoint (lineno);
+          for (std::list<std::string>::const_iterator p = subfcn_names.begin ();
+               p != subfcn_names.end (); p++)
+            {
+              std::map<std::string, octave_value>::const_iterator
+                q = subfcns.find (*p);
 
-                          if (! file.empty ())
-                            octave_link::update_breakpoint (false, file, lineno);
-                        }
-                    }
-
-                  results = cmds->list_breakpoints ();
+              if (q != subfcns.end ())
+                {
+                  octave_user_code *dbg_subfcn = q->second.user_code_value ();
 
-                  bp_set_iterator it = bp_set.find (fname);
-                  if (results.length () == 0 && it != bp_set.end ())
-                    bp_set.erase (it);
+                  retval += do_remove_breakpoint_1 (dbg_subfcn, fname, line);
                 }
-
-              retval = results.length ();
             }
         }
       else
@@ -376,6 +451,27 @@
   return retval;
 }
 
+bp_table::intmap
+bp_table::do_remove_all_breakpoints_in_file_1 (octave_user_code *fcn,
+                                               const std::string& fname)
+{
+  intmap retval;
+
+  std::string file = fcn->fcn_file_name ();
+
+  tree_statement_list *cmds = fcn->body ();
+
+  if (cmds)
+    {
+      retval = cmds->remove_all_breakpoints (file);
+
+      bp_set_iterator it = bp_set.find (fname);
+      if (it != bp_set.end ())
+        bp_set.erase (it);
+    }
+
+  return retval;
+}
 
 bp_table::intmap
 bp_table::do_remove_all_breakpoints_in_file (const std::string& fname,
@@ -387,17 +483,24 @@
 
   if (dbg_fcn)
     {
-      std::string file = dbg_fcn->fcn_file_name ();
+      retval = do_remove_all_breakpoints_in_file_1 (dbg_fcn, fname);
+
+      // Order is not important here.
 
-      tree_statement_list *cmds = dbg_fcn->body ();
+      typedef std::map<std::string, octave_value>::const_iterator
+        subfcns_const_iterator;
 
-      if (cmds)
+      std::map<std::string, octave_value> subfcns = dbg_fcn->subfunctions ();
+
+      for (subfcns_const_iterator p = subfcns.begin ();
+           p != subfcns.end (); p++)
         {
-          retval = cmds->remove_all_breakpoints (file);
+          octave_user_code *dbg_subfcn = p->second.user_code_value ();
 
-          bp_set_iterator it = bp_set.find (fname);
-          if (it != bp_set.end ())
-            bp_set.erase (it);
+          intmap tmp = do_remove_all_breakpoints_in_file_1 (dbg_subfcn, fname);
+
+          // Merge new list with retval.
+          retval.insert (tmp.begin (), tmp.end ());
         }
     }
   else if (! silent)
--- a/libinterp/interpfcn/debug.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/debug.h	Sun May 12 21:45:57 2013 -0400
@@ -115,10 +115,19 @@
 
   static void cleanup_instance (void) { delete instance; instance = 0; }
 
+  bool do_add_breakpoint_1 (octave_user_code *fcn, const std::string& fname,
+                            const intmap& line, intmap& retval);
+
   intmap do_add_breakpoint (const std::string& fname, const intmap& lines);
 
+  int do_remove_breakpoint_1 (octave_user_code *fcn, const std::string&,
+                              const intmap& lines);
+
   int do_remove_breakpoint (const std::string&, const intmap& lines);
 
+  intmap do_remove_all_breakpoints_in_file_1 (octave_user_code *fcn,
+                                              const std::string& fname);
+
   intmap do_remove_all_breakpoints_in_file (const std::string& fname,
                                             bool silent);
 
--- a/libinterp/interpfcn/load-save.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/load-save.h	Sun May 12 21:45:57 2013 -0400
@@ -83,7 +83,7 @@
          bool list_only, bool swap, bool verbose,
          const string_vector& argv, int argv_idx, int argc, int nargout);
 
-extern bool is_octave_data_file (const std::string& file);
+extern OCTINTERP_API bool is_octave_data_file (const std::string& file);
 
 extern void
 do_save (std::ostream& os, const symbol_table::symbol_record& sr,
--- a/libinterp/interpfcn/octave-link.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/octave-link.h	Sun May 12 21:45:57 2013 -0400
@@ -41,7 +41,9 @@
 // buffering access operations to octave and executing them in the
 // readline event hook, which lives in the octave thread.
 
-class octave_link
+class
+OCTINTERP_API
+octave_link
 {
 protected:
 
--- a/libinterp/interpfcn/symtab.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/symtab.cc	Sun May 12 21:45:57 2013 -0400
@@ -1494,27 +1494,12 @@
 
 void symbol_table::cleanup (void)
 {
-  // Clear variables in top scope.
-  all_instances[xtop_scope]->clear_variables ();
-
-  // Clear function table. This is a hard clear, ignoring mlocked functions.
-  fcn_table.clear ();
-
-  // Clear variables in global scope.
-  // FIXME: are there any?
-  all_instances[xglobal_scope]->clear_variables ();
-
-  // Clear global variables.
-  global_table.clear ();
+  clear_all (true);
 
   // Delete all possibly remaining scopes.
   for (all_instances_iterator iter = all_instances.begin ();
        iter != all_instances.end (); iter++)
     {
-      scope_id scope = iter->first;
-      if (scope != xglobal_scope && scope != xtop_scope)
-        scope_id_cache::free (scope);
-
       // First zero the table entry to avoid possible duplicate delete.
       symbol_table *inst = iter->second;
       iter->second = 0;
@@ -1523,6 +1508,12 @@
       // deleting other scopes.
       delete inst;
     }
+
+  global_table.clear ();
+  fcn_table.clear ();
+  class_precedence_table.clear ();
+  parent_map.clear ();
+  all_instances.clear ();
 }
 
 void
--- a/libinterp/interpfcn/symtab.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/interpfcn/symtab.h	Sun May 12 21:45:57 2013 -0400
@@ -844,37 +844,33 @@
 
       template <class T>
       void
-      clear_unlocked (std::map<T, octave_value>& map)
+      clear_map (std::map<T, octave_value>& map, bool force = false)
       {
         typename std::map<T, octave_value>::iterator p = map.begin ();
 
         while (p != map.end ())
           {
-            if (p->second.islocked ())
+            if (force || ! p->second.islocked ())
+              map.erase (p++);
+            else
               p++;
-            else
-              map.erase (p++);
           }
       }
 
-      void clear_autoload_function (void)
+      void clear_autoload_function (bool force = false)
       {
-        if (! autoload_function.islocked ())
+        if (force || ! autoload_function.islocked ())
           autoload_function = octave_value ();
       }
 
       // We also clear command line functions here, as these are both
       // "user defined"
-      void clear_user_function (void)
+      void clear_user_function (bool force = false)
       {
-        if (! function_on_path.islocked ())
-          {
-            function_on_path.erase_subfunctions ();
-
-            function_on_path = octave_value ();
-          }
-
-        if (! cmdline_function.islocked ())
+        if (force || ! function_on_path.islocked ())
+          function_on_path = octave_value ();
+
+        if (force || ! cmdline_function.islocked ())
           cmdline_function = octave_value ();
       }
 
@@ -884,14 +880,15 @@
           clear_user_function ();
       }
 
-      void clear (void)
+      void clear (bool force = false)
       {
-        clear_unlocked (subfunctions);
-        clear_unlocked (private_functions);
-        clear_unlocked (class_constructors);
-        clear_unlocked (class_methods);
-        clear_autoload_function ();
-        clear_user_function ();
+        clear_map (subfunctions, force);
+        clear_map (private_functions, force);
+        clear_map (class_constructors, force);
+        clear_map (class_methods, force);
+
+        clear_autoload_function (force);
+        clear_user_function (force);
       }
 
       void add_dispatch (const std::string& type, const std::string& fname)
@@ -1079,11 +1076,17 @@
       rep->install_built_in_function (f);
     }
 
-    void clear (void) { rep->clear (); }
-
-    void clear_user_function (void) { rep->clear_user_function (); }
-
-    void clear_autoload_function (void) { rep->clear_autoload_function (); }
+    void clear (bool force = false) { rep->clear (force); }
+
+    void clear_user_function (bool force = false)
+    {
+      rep->clear_user_function (force);
+    }
+
+    void clear_autoload_function (bool force = false)
+    {
+      rep->clear_autoload_function (force);
+    }
 
     void clear_mex_function (void) { rep->clear_mex_function (); }
 
@@ -1182,6 +1185,8 @@
   {
     assert (scope != xglobal_scope);
 
+    erase_subfunctions_in_scope (scope);
+
     all_instances_iterator p = all_instances.find (scope);
 
     if (p != all_instances.end ())
@@ -1532,6 +1537,9 @@
       }
   }
 
+  // Install subfunction FCN named NAME.  SCOPE is the scope of the
+  // primary function corresponding to this subfunction.
+
   static void install_subfunction (const std::string& name,
                                    const octave_value& fcn,
                                    scope_id scope)
@@ -1612,13 +1620,13 @@
     clear_variable (name);
   }
 
-  static void clear_all (void)
+  static void clear_all (bool force = false)
   {
     clear_variables ();
 
     clear_global_pattern ("*");
 
-    clear_functions ();
+    clear_functions (force);
   }
 
   static void clear_variables (scope_id scope)
@@ -1643,10 +1651,10 @@
       inst->do_clear_objects ();
   }
 
-  static void clear_functions (void)
+  static void clear_functions (bool force = false)
   {
     for (fcn_table_iterator p = fcn_table.begin (); p != fcn_table.end (); p++)
-      p->second.clear ();
+      p->second.clear (force);
   }
 
   static void clear_function (const std::string& name)
@@ -2175,6 +2183,26 @@
       p->second.unlock_subfunction (scope);
   }
 
+  static std::map<std::string, octave_value>
+  subfunctions_defined_in_scope (scope_id scope = xcurrent_scope)
+  {
+    std::map<std::string, octave_value> retval;
+
+    for (fcn_table_const_iterator p = fcn_table.begin ();
+         p != fcn_table.end (); p++)
+      {
+        std::pair<std::string, octave_value> tmp
+          = p->second.subfunction_defined_in_scope (scope);
+
+        std::string nm = tmp.first;
+
+        if (! nm.empty ())
+          retval[nm] = tmp.second;
+      }
+
+    return retval;
+  }
+
   static void free_scope (scope_id scope)
   {
     if (scope == xglobal_scope || scope == xtop_scope)
@@ -2589,10 +2617,12 @@
 
   void do_pop_context (void)
   {
-    for (table_iterator p = table.begin (); p != table.end (); )
+    table_iterator p = table.begin ();
+
+    while (p != table.end ())
       {
         if (p->second.pop_context (my_scope) == 0)
-            table.erase (p++);
+          table.erase (p++);
         else
           p++;
       }
@@ -2654,13 +2684,12 @@
           sr.unmark_global ();
       }
 
-
-    for (global_table_iterator q = global_table.begin ();
-         q != global_table.end ();)
+    global_table_iterator q = global_table.begin ();
+
+    while (q != global_table.end ())
       {
         if (pattern.match (q->first))
-          global_table.erase (q++); //Gotta be careful to not
-                                    //invalidate iterators
+          global_table.erase (q++);
         else
           q++;
       }
@@ -2796,26 +2825,6 @@
     return retval;
   }
 
-  static std::map<std::string, octave_value>
-  subfunctions_defined_in_scope (scope_id scope = xcurrent_scope)
-  {
-    std::map<std::string, octave_value> retval;
-
-    for (fcn_table_const_iterator p = fcn_table.begin ();
-         p != fcn_table.end (); p++)
-      {
-        std::pair<std::string, octave_value> tmp
-          = p->second.subfunction_defined_in_scope (scope);
-
-        std::string nm = tmp.first;
-
-        if (! nm.empty ())
-          retval[nm] = tmp.second;
-      }
-
-    return retval;
-  }
-
   bool do_is_local_variable (const std::string& name) const
   {
     table_const_iterator p = table.find (name);
--- a/libinterp/octave-value/ov-fcn.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/octave-value/ov-fcn.h	Sun May 12 21:45:57 2013 -0400
@@ -138,6 +138,18 @@
 
   virtual void unlock_subfunctions (void) { }
 
+  virtual void maybe_relocate_end (void) { }
+
+  // Not valid until after the function is completley parsed.
+  virtual bool has_subfunctions (void) const { return false; }
+
+  virtual void stash_subfunction_names (const std::list<std::string>&) { }
+
+  virtual std::list<std::string> subfunction_names (void) const
+  {
+    return std::list<std::string> ();
+  }
+
   void mark_relative (void) { relative = true; }
 
   bool is_relative (void) const { return relative; }
--- a/libinterp/octave-value/ov-usr-fcn.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/octave-value/ov-usr-fcn.cc	Sun May 12 21:45:57 2013 -0400
@@ -58,6 +58,13 @@
 // Whether to optimize subsasgn method calls.
 static bool Voptimize_subsasgn_calls = true;
 
+
+std::map<std::string, octave_value>
+octave_user_code::subfunctions (void) const
+{
+  return std::map<std::string, octave_value> ();
+}
+
 // User defined scripts.
 
 DEFINE_OCTAVE_ALLOCATOR (octave_user_script);
@@ -223,6 +230,7 @@
   delete jit_info;
 #endif
 
+  // FIXME -- this is really playing with fire.
   symbol_table::erase_scope (local_scope);
 }
 
@@ -240,6 +248,70 @@
   file_name = nm;
 }
 
+// If there is no explicit end statement at the end of the function,
+// relocate the no_op that was generated for the end of file condition
+// to appear on the next line after the last statement in the file, or
+// the next line after the function keyword if there are no statements.
+// More precisely, the new location should probably be on the next line
+// after the end of the parameter list, but we aren't tracking that
+// information (yet).
+
+void
+octave_user_function::maybe_relocate_end_internal (void)
+{
+  if (cmd_list && ! cmd_list->empty ())
+    {
+      tree_statement *last_stmt = cmd_list->back ();
+
+      if (last_stmt && last_stmt->is_end_of_fcn_or_script ()
+          && last_stmt->is_end_of_file ())
+        {
+          tree_statement_list::reverse_iterator
+            next_to_last_elt = cmd_list->rbegin ();
+
+          next_to_last_elt++;
+
+          int new_eof_line;
+          int new_eof_col;
+
+          if (next_to_last_elt == cmd_list->rend ())
+            {
+              new_eof_line = beginning_line ();
+              new_eof_col = beginning_column ();
+            }
+          else
+            {
+              tree_statement *next_to_last_stmt = *next_to_last_elt;
+
+              new_eof_line = next_to_last_stmt->line ();
+              new_eof_col = next_to_last_stmt->column ();
+            }
+
+          last_stmt->set_location (new_eof_line + 1, new_eof_col);
+        }
+    }
+}
+
+void
+octave_user_function::maybe_relocate_end (void)
+{
+  std::map<std::string, octave_value> fcns = subfunctions ();
+
+  if (! fcns.empty ())
+    {
+      for (std::map<std::string, octave_value>::iterator p = fcns.begin ();
+           p != fcns.end (); p++)
+        {
+          octave_user_function *f = (p->second).user_function_value ();
+
+          if (f)
+            f->maybe_relocate_end_internal ();
+        }
+    }
+
+  maybe_relocate_end_internal ();
+}
+
 std::string
 octave_user_function::profiler_name (void) const
 {
@@ -306,6 +378,25 @@
   symbol_table::unlock_subfunctions (local_scope);
 }
 
+std::map<std::string, octave_value>
+octave_user_function::subfunctions (void) const
+{
+  return symbol_table::subfunctions_defined_in_scope (local_scope);
+}
+
+bool
+octave_user_function::has_subfunctions (void) const
+{
+  return ! subfcn_names.empty ();
+}
+
+void
+octave_user_function::stash_subfunction_names
+  (const std::list<std::string>& names)
+{
+  subfcn_names = names;
+}
+
 octave_value_list
 octave_user_function::all_va_args (const octave_value_list& args)
 {
--- a/libinterp/octave-value/ov-usr-fcn.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/octave-value/ov-usr-fcn.h	Sun May 12 21:45:57 2013 -0400
@@ -59,6 +59,8 @@
 
   bool is_user_code (void) const { return true; }
 
+  virtual std::map<std::string, octave_value> subfunctions (void) const;
+
   virtual tree_statement_list *body (void) = 0;
 
 protected:
@@ -206,6 +208,20 @@
       location_column = col;
     }
 
+  int beginning_line (void) const { return location_line; }
+  int beginning_column (void) const { return location_column; }
+
+  void stash_fcn_end_location (int line, int col)
+    {
+      end_location_line = line;
+      end_location_column = col;
+    }
+
+  int ending_line (void) const { return end_location_line; }
+  int ending_column (void) const { return end_location_column; }
+
+  void maybe_relocate_end (void);
+
   void stash_parent_fcn_name (const std::string& p) { parent_name = p; }
 
   void stash_parent_fcn_scope (symbol_table::scope_id ps) { parent_scope = ps; }
@@ -262,6 +278,17 @@
 
   void unlock_subfunctions (void);
 
+  std::map<std::string, octave_value> subfunctions (void) const;
+
+  bool has_subfunctions (void) const;
+
+  void stash_subfunction_names (const std::list<std::string>& names);
+
+  std::list<std::string> subfunction_names (void) const
+  {
+    return subfcn_names;
+  }
+
   octave_value_list all_va_args (const octave_value_list& args);
 
   void stash_function_name (const std::string& s) { my_name = s; }
@@ -417,10 +444,16 @@
   // Location where this function was defined.
   int location_line;
   int location_column;
+  int end_location_line;
+  int end_location_column;
 
   // The name of the parent function, if any.
   std::string parent_name;
 
+  // The list of subfunctions (if any) in the order they appear in the
+  // file.
+  std::list<std::string> subfcn_names;
+
   // The time the file was parsed.
   octave_time t_parsed;
 
@@ -469,6 +502,8 @@
   jit_function_info *jit_info;
 #endif
 
+  void maybe_relocate_end_internal (void);
+
   void print_code_function_header (void);
 
   void print_code_function_trailer (void);
--- a/libinterp/parse-tree/lex.ll	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/lex.ll	Sun May 12 21:45:57 2013 -0400
@@ -3024,7 +3024,7 @@
   looking_for_object_index = false;
   at_beginning_of_statement = bos;
 
-  return count_token (tok);
+  return count_token_internal (tok);
 }
 
 int
--- a/libinterp/parse-tree/oct-parse.in.yy	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/oct-parse.in.yy	Sun May 12 21:45:57 2013 -0400
@@ -242,15 +242,16 @@
 %token <tok_val> METAQUERY
 %token <tok_val> SUPERCLASSREF
 %token <tok_val> GET SET
+%token <tok_val> FCN
 
 // Other tokens.
 %token END_OF_INPUT LEXICAL_ERROR
-%token FCN INPUT_FILE
+%token INPUT_FILE
 // %token VARARGIN VARARGOUT
 
 // Nonterminals we construct.
-%type <comment_type> stash_comment function_beg
-%type <tok_type> classdef_beg
+%type <comment_type> stash_comment
+%type <tok_type> function_beg classdef_beg
 %type <sep_type> sep_no_nl opt_sep_no_nl nl opt_nl sep opt_sep
 %type <tree_type> input
 %type <tree_constant_type> string constant magic_colon
@@ -1157,9 +1158,9 @@
                     if (! lexer.reading_fcn_file)
                       {
                         tree_statement *end_of_script
-                          = parser.make_end ("endscript",
-                                                  lexer.input_line_number,
-                                                  lexer.current_input_column);
+                          = parser.make_end ("endscript", true,
+                                             lexer.input_line_number,
+                                             lexer.current_input_column);
 
                         parser.make_script ($3, end_of_script);
                       }
@@ -1179,23 +1180,25 @@
 // Function definition
 // ===================
 
-function_beg    : push_fcn_symtab FCN stash_comment
+function_beg    : push_fcn_symtab FCN
                   {
-                    $$ = $3;
+                    $$ = $2;
                     if (lexer.reading_classdef_file
                         || lexer.parsing_classdef)
                       lexer.maybe_classdef_get_set_method = true;
                   }
                 ;
 
-function        : function_beg function1
+function        : function_beg stash_comment function1
                   {
-                    $$ = parser.finish_function (0, $2, $1);
+                    $$ = parser.finish_function (0, $3, $2, $1->line (),
+                                                 $1->column ());
                     parser.recover_from_parsing_function ();
                   }
-                | function_beg return_list '=' function1
+                | function_beg stash_comment return_list '=' function1
                   {
-                    $$ = parser.finish_function ($2, $4, $1);
+                    $$ = parser.finish_function ($3, $5, $2, $1->line (),
+                                                 $1->column ());
                     parser.recover_from_parsing_function ();
                   }
                 ;
@@ -1246,7 +1249,8 @@
                   {
                     parser.endfunction_found = true;
                     if (parser.end_token_ok ($1, token::function_end))
-                      $$ = parser.make_end ("endfunction", $1->line (), $1->column ());
+                      $$ = parser.make_end ("endfunction", false,
+                                            $1->line (), $1->column ());
                     else
                       ABORT_PARSE;
                   }
@@ -1280,9 +1284,9 @@
                         YYABORT;
                       }
 
-                    $$ = parser.make_end ("endfunction",
-                                                lexer.input_line_number,
-                                                lexer.current_input_column);
+                    $$ = parser.make_end ("endfunction", true,
+                                          lexer.input_line_number,
+                                          lexer.current_input_column);
                   }
                 ;
 
@@ -1306,6 +1310,7 @@
 classdef        : classdef_beg stash_comment opt_attr_list identifier opt_superclass_list opt_sep class_body opt_sep END
                   {
                     lexer.parsing_classdef = false;
+
                     if (! ($$ = parser.make_classdef ($1, $3, $4, $5, $7, $9, $2)))
                       ABORT_PARSE;
                   }
@@ -1585,6 +1590,7 @@
   curr_class_name = "";
   function_scopes.clear ();
   primary_fcn_ptr  = 0;
+  subfunction_names.clear ();
 
   delete stmt_list;
   stmt_list = 0;
@@ -2689,15 +2695,17 @@
       octave_comment_list *tc = octave_comment_buffer::get_comment ();
 
       fcn->stash_trailing_comment (tc);
+      fcn->stash_fcn_end_location (end_fcn_stmt->line (),
+                                   end_fcn_stmt->column ());
     }
 
   return fcn;
 }
 
 tree_statement *
-octave_base_parser::make_end (const std::string& type, int l, int c)
+octave_base_parser::make_end (const std::string& type, bool eof, int l, int c)
 {
-  return make_statement (new tree_no_op_command (type, l, c));
+  return make_statement (new tree_no_op_command (type, eof, l, c));
 }
 
 // Do most of the work for defining a function.
@@ -2786,8 +2794,6 @@
     }
 
   fcn->stash_function_name (id_name);
-  fcn->stash_fcn_location (lexer.input_line_number,
-                           lexer.current_input_column);
 
   if (! lexer.help_text.empty () && curr_fcn_depth == 1
       && ! parsing_subfunctions)
@@ -2807,7 +2813,8 @@
 tree_function_def *
 octave_base_parser::finish_function (tree_parameter_list *ret_list,
                                      octave_user_function *fcn,
-                                     octave_comment_list *lc)
+                                     octave_comment_list *lc,
+                                     int l, int c)
 {
   tree_function_def *retval = 0;
 
@@ -2833,6 +2840,9 @@
       if (curr_fcn_depth > 1 || parsing_subfunctions)
         {
           fcn->mark_as_subfunction ();
+          fcn->stash_fcn_location (l, c);
+
+          subfunction_names.push_back (nm);
 
           if (endfunction_found && function_scopes.size () > 1)
             {
@@ -3580,6 +3590,18 @@
 
               fcn_ptr = parser.classdef_object->make_meta_class ();
             }
+          else if (fcn_ptr)
+            {
+              fcn_ptr->maybe_relocate_end ();
+
+              if (parser.parsing_subfunctions)
+                {
+                  if (! parser.endfunction_found)
+                    parser.subfunction_names.reverse ();
+
+                  fcn_ptr->stash_subfunction_names (parser.subfunction_names);
+                }
+            }
         }
       else
         error ("parse error while reading file %s", full_file.c_str ());
--- a/libinterp/parse-tree/parse.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/parse.h	Sun May 12 21:45:57 2013 -0400
@@ -149,7 +149,7 @@
       parsing_subfunctions (false), max_fcn_depth (0),
       curr_fcn_depth (0), primary_fcn_scope (-1),
       curr_class_name (), function_scopes (), primary_fcn_ptr (0),
-      classdef_object (0), stmt_list (0),
+      subfunction_names (), classdef_object (0), stmt_list (0),
       lexer (lxr)
   {
     init ();
@@ -283,7 +283,7 @@
                   tree_statement *end_function);
 
   // Create a no-op statement for end_function.
-  tree_statement *make_end (const std::string& type, int l, int c);
+  tree_statement *make_end (const std::string& type, bool eof, int l, int c);
 
   // Do most of the work for defining a function.
   octave_user_function *
@@ -292,7 +292,8 @@
   // Finish defining a function.
   tree_function_def *
   finish_function (tree_parameter_list *ret_list,
-                   octave_user_function *fcn, octave_comment_list *lc);
+                   octave_user_function *fcn, octave_comment_list *lc,
+                   int l, int c);
 
   // Reset state after parsing function.
   void
@@ -431,6 +432,11 @@
   // Pointer to the primary user function or user script function.
   octave_function *primary_fcn_ptr;
 
+  // List of subfunction names, initially in the order they are
+  // installed in the symbol table, then ordered as they appear in the
+  // file.  Eventually stashed in the primary function object.
+  std::list<std::string> subfunction_names;
+
   // Pointer to the classdef object we just parsed, if any.
   tree_classdef *classdef_object;
 
--- a/libinterp/parse-tree/pt-bp.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt-bp.h	Sun May 12 21:45:57 2013 -0400
@@ -136,7 +136,7 @@
 
   octave_value_list get_list (void) { return bp_list; }
 
-  int get_line (void) { return line; }
+  int get_line (void) { return found ? line : 0; }
 
  private:
 
--- a/libinterp/parse-tree/pt-cmd.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt-cmd.cc	Sun May 12 21:45:57 2013 -0400
@@ -33,7 +33,8 @@
 tree_no_op_command::dup (symbol_table::scope_id,
                          symbol_table::context_id) const
 {
-  return new tree_no_op_command (orig_cmd, line (), column ());
+  return new tree_no_op_command (orig_cmd, is_end_of_file (),
+                                 line (), column ());
 }
 
 void
--- a/libinterp/parse-tree/pt-cmd.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt-cmd.h	Sun May 12 21:45:57 2013 -0400
@@ -63,9 +63,9 @@
 {
 public:
 
-  tree_no_op_command (const std::string& cmd = "no_op", int l = -1, int c = -1)
-    : tree_command (l, c), eof (cmd == "endfunction" || cmd == "endscript"),
-      orig_cmd (cmd) { }
+  tree_no_op_command (const std::string& cmd = "no_op", bool e = false,
+                      int l = -1, int c = -1)
+    : tree_command (l, c), eof (e), orig_cmd (cmd) { }
 
   ~tree_no_op_command (void) { }
 
@@ -74,7 +74,12 @@
 
   void accept (tree_walker& tw);
 
-  bool is_end_of_fcn_or_script (void) const { return eof; }
+  bool is_end_of_fcn_or_script (void) const
+  {
+    return (orig_cmd == "endfunction" || orig_cmd == "endscript");
+  }
+
+  bool is_end_of_file (void) const { return eof; }
 
   std::string original_command (void) { return orig_cmd; }
 
--- a/libinterp/parse-tree/pt-stmt.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt-stmt.cc	Sun May 12 21:45:57 2013 -0400
@@ -107,6 +107,15 @@
 }
 
 void
+tree_statement::set_location (int l, int c)
+{
+  if (cmd)
+    cmd->set_location (l, c);
+  else if (expr)
+    expr->set_location (l, c);
+}
+
+void
 tree_statement::echo_code (void)
 {
   tree_print_code tpc (octave_stdout, VPS4);
@@ -131,6 +140,23 @@
   return retval;
 }
 
+bool
+tree_statement::is_end_of_file (void) const
+{
+  bool retval = false;
+
+  if (cmd)
+    {
+      tree_no_op_command *no_op_cmd
+        = dynamic_cast<tree_no_op_command *> (cmd);
+
+      if (no_op_cmd)
+        retval = no_op_cmd->is_end_of_file ();
+    }
+
+  return retval;
+}
+
 tree_statement *
 tree_statement::dup (symbol_table::scope_id scope,
                      symbol_table::context_id context) const
--- a/libinterp/parse-tree/pt-stmt.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt-stmt.h	Sun May 12 21:45:57 2013 -0400
@@ -74,6 +74,8 @@
   int line (void) const;
   int column (void) const;
 
+  void set_location (int l, int c);
+
   void echo_code (void);
 
   tree_command *command (void) { return cmd; }
@@ -86,6 +88,8 @@
 
   bool is_end_of_fcn_or_script (void) const;
 
+  bool is_end_of_file (void) const;
+
   // Allow modification of this statement.  Note that there is no
   // checking.  If you use these, are you sure you knwo what you are
   // doing?
--- a/libinterp/parse-tree/pt.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/libinterp/parse-tree/pt.h	Sun May 12 21:45:57 2013 -0400
@@ -50,6 +50,12 @@
 
   void column (int c) { column_num = c; }
 
+  void set_location (int l, int c)
+  {
+    line_num = l;
+    column_num = c;
+  }
+
   virtual void set_breakpoint (void) { bp = true; }
 
   virtual void delete_breakpoint (void) { bp = false; }
--- a/liboctave/util/base-list.h	Mon Apr 29 19:13:40 2013 -0400
+++ b/liboctave/util/base-list.h	Sun May 12 21:45:57 2013 -0400
@@ -36,6 +36,9 @@
   typedef typename std::list<elt_type>::iterator iterator;
   typedef typename std::list<elt_type>::const_iterator const_iterator;
 
+  typedef typename std::list<elt_type>::reverse_iterator reverse_iterator;
+  typedef typename std::list<elt_type>::const_reverse_iterator const_reverse_iterator;
+
   bool empty (void) const { return lst.empty (); }
 
   size_t size (void) const { return lst.size (); }
@@ -74,6 +77,12 @@
   iterator end (void) { return iterator (lst.end ()); }
   const_iterator end (void) const { return const_iterator (lst.end ()); }
 
+  reverse_iterator rbegin (void) { return reverse_iterator (lst.rbegin ()); }
+  const_reverse_iterator rbegin (void) const { return const_reverse_iterator (lst.rbegin ()); }
+
+  reverse_iterator rend (void) { return reverse_iterator (lst.rend ()); }
+  const_reverse_iterator rend (void) const { return const_reverse_iterator (lst.rend ()); }
+
   elt_type& front (void) { return lst.front (); }
   elt_type& back (void) { return lst.back (); }
 
--- a/scripts/help/__unimplemented__.m	Mon Apr 29 19:13:40 2013 -0400
+++ b/scripts/help/__unimplemented__.m	Sun May 12 21:45:57 2013 -0400
@@ -203,7 +203,6 @@
   "frame2im",
   "freqspace",
   "funm",
-  "gallery",
   "gammaincinv",
   "getframe",
   "getpixelposition",
--- a/scripts/image/rgb2ind.m	Mon Apr 29 19:13:40 2013 -0400
+++ b/scripts/image/rgb2ind.m	Sun May 12 21:45:57 2013 -0400
@@ -1,5 +1,6 @@
 ## Copyright (C) 1994-2012 John W. Eaton
 ## Copyright (C) 2012 Carnë Draug
+## Copyright (C) 2013 Adam H Aitkenhead
 ##
 ## This file is part of Octave.
 ##
@@ -19,50 +20,160 @@
 
 ## -*- texinfo -*-
 ## @deftypefn  {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{map})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{n})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{tol})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{map}, @var{dither_option})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{n}, @var{dither_option})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{rgb}, @var{tol}, @var{dither_option})
 ## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{map})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{n})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{tol})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{map}, @var{dither_option})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{n}, @var{dither_option})
+## @deftypefnx {Function File} {[@var{x}, @var{map}] =} rgb2ind (@var{R}, @var{G}, @var{B}, @var{tol}, @var{dither_option})
 ## Convert an image in red-green-blue (RGB) color space to an indexed image.
+##
+## The input image @var{rgb} must be an N-dimensional RGB image
+## (MxNxO...x3 array) where M,N,O... are the image dimensions, and the
+## final dimension contains the values in the red, green and blue
+## channels. Alternatively, the red, green and blue color channels can
+## be input as separate arrays @var{R}, @var{G} and  @var{B}.
+##
+## The input @var{map} defines the colormap to be used.  Alternatively,
+## @var{n} or @var{tol} may be used to define the maximum number of
+## colors to use in an automatically generated colormap.  @var{n} is
+## related to @var{tol} by:  @var{n} = (floor (1/@var{tol}) + 1)^3;
+## @var{tol} must be >0 and <=1.
+##
+## @var{dither_option} is a string which enables or disables dithering:
+## 'dither' (default) or 'nodither'.
+##
 ## @seealso{ind2rgb, rgb2hsv, rgb2ntsc}
 ## @end deftypefn
 
-## FIXME: This function has a very different syntax than the Matlab
-##        one of the same name.
-##        Octave function does not support N, MAP, DITHER, or TOL arguments.
-
 ## Author: Tony Richardson <arichard@stark.cc.oh.us>
 ## Created: July 1994
 ## Adapted-By: jwe
 
-function [x, map] = rgb2ind (R, G, B)
+function [x, map] = rgb2ind (varargin)
+
+  ## Gather the inputs
+  if (nargin < 1 || nargin > 6)
+    print_usage ();
+  else
+
+    ## Test for dither_option, by checking if the final input is a string
+    if ischar (varargin{end})
+      dither_option = varargin{end};
+      dither_check  = true;
+    else
+      dither_option = "dither";
+      dither_check  = false;
+    endif
+
+    ## Read the rgb input
+    if (nargin-dither_check==1 || nargin-dither_check==2)
+
+      rgb = varargin{1};
+      if (size (rgb)(end) != 3)
+        error ("rgb2ind: The input image must be an RGB image (MxNxO...x3 array).");
+      elseif (min (rgb(:)) < 0 || max (rgb(:)) > 1)
+        error ("rgb2ind: The input image must contain values between 0 and 1.");
+      endif
+      if (nargin-dither_check==2)
+        option = varargin{2};
+      else
+        dither_option = "nodither";
+      endif
+
+      ## Read the R,G,B inputs
+    elseif (nargin - dither_check==3 || nargin - dither_check==4)
+
+      R = varargin{1};
+      G = varargin{2};
+      B = varargin{3};
+      if (! size_equal (R, G, B))
+        error ("rgb2ind: R, G, and B must have the same size");
+      endif
+      if (nargin-dither_check==4)
+        option = varargin{4};
+      else
+        dither_option = "nodither";
+      endif
+      
+      rgb = reshape ([R(:), G(:), B(:)], [size(R), 3]);
 
-  if (nargin != 1 && nargin != 3)
-    print_usage ();
+    endif
+  endif
+      
+  sz = size (rgb);
+
+  ## Apply a limited colormap if required
+  if (exist ("option","var"))
+
+    if (size (option, 1)==1)
+
+      if (option>0 && option<=1)
+        ## option: tol
+        tol = option;
+        n   = (floor (1/option) + 1)^3;
+      else
+        ## option: n
+        n   = option;
+      endif
+      optionstr = sprintf ("-colors %d",n);
+      
+    else
+
+      ## option: map
+      map = option;
+      if (isequal (map(:,1),map(:,2)) || isequal (map(:,1),map(:,3))
+          || isequal (map(:,2),map(:,3)))
+        error ("rgb2ind: The colormap cannot contain matching R,G, or B channels.")
+      endif
+      fnmap = tmpnam;
+      map = reshape (map, size (map, 1), 1, 3);
+      imwrite (map, fnmap, "tiff");
+      optionstr = sprintf ("-map %s", fnmap);
+      
+    endif
+  
+    ## If image is an ND array, convert it to a tiled 2D image
+    ## before processing it with Graphicsmagick
+    if numel (sz)>3
+     rgb = reshape (rgb, [prod(sz(1:end-2)), sz(end-1), 3]);
+    end
+
+    ## Prepare the Graphicsmagick dithering option
+    if strcmp (dither_option, "nodither")
+      ditherstr = "+dither";
+    elseif strcmp (dither_option, "dither")
+      ditherstr = "-dither";
+    endif
+      
+    ## Perform the image processing using Graphicsmagick
+    fna = tmpnam;
+    fnb = tmpnam;
+    imwrite (rgb, fna, "tiff");
+    gmstr = sprintf ("gm convert %s %s %s %s", fna, ditherstr, optionstr, fnb);
+    system (gmstr);
+    rgb = imread (fnb);
+    
   endif
 
-  if (nargin == 1)
-    rgb = R;
-    if (ndims (rgb) != 3 || size (rgb, 3) != 3)
-      error ("rgb2ind: argument is not an RGB image");
-    else
-      R = rgb(:,:,1);
-      G = rgb(:,:,2);
-      B = rgb(:,:,3);
-    endif
-  elseif (! size_equal (R, G, B))
-    error ("rgb2ind: R, G, and B must have the same size");
-  endif
-
-  x = reshape (1:numel (R), size (R));
-
-  map    = unique ([R(:) G(:) B(:)], "rows");
-  [~, x] = ismember ([R(:) G(:) B(:)], map, "rows");
-  x      = reshape (x, size (R));
+  ## Conversion of rgb image to x,map
+  pr = prod (sz(1:end-1));
+  x = zeros (sz(1:end-1));
+  [map,~,x(:)] = unique (reshape(rgb, [pr, 3]), "rows");
 
   ## a colormap is of class double and values between 0 and 1
-  switch (class (R))
+  switch (class (rgb))
     case {"single", "double", "logical"}
       ## do nothing, return the same
     case {"uint8", "uint16"}
-      map = double (map) / double (intmax (class (R)));
+      map = double (map) / double (intmax (class (rgb)));
     case "int16"
       map = (double (im) + 32768) / 65535;
     otherwise
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/scripts/special-matrix/gallery.m	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,2672 @@
+## Copyright (C) 1989-1995 Nicholas .J. Higham
+## Copyright (C) 2013 Carnë Draug
+##
+## 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/>.
+
+## -*- texinfo -*-
+## @deftypefn  {Function File} {} gallery (@var{name})
+## @deftypefnx {Function File} {} gallery (@var{name}, @var{args})
+## Create interesting matrices for testing.
+##
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("cauchy", @var{x})
+## @deftypefnx {Function File} {@var{c} =} gallery ("cauchy", @var{x}, @var{y})
+## Create a Cauchy matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("chebspec", @var{n})
+## @deftypefnx {Function File} {@var{c} =} gallery ("chebspec", @var{n}, @var{k})
+## Create a Chebyshev spectral differentiation matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("chebvand", @var{p})
+## @deftypefnx {Function File} {@var{c} =} gallery ("chebvand", @var{m}, @var{p})
+## Create a Vandermonde-like matrix for the Chebyshev polynomials.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("chow", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("chow", @var{n}, @var{alpha})
+## @deftypefnx {Function File} {@var{a} =} gallery ("chow", @var{n}, @var{alpha}, @var{delta})
+## Create a Chow matrix -- a singular Toeplitz lower Hessenberg matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("circul", @var{v})
+## Create a circulant matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("clement", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("clement", @var{n}, @var{k})
+## Create a tridiagonal matrix with zero diagonal entries.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("compar", @var{a})
+## @deftypefnx {Function File} {@var{c} =} gallery ("compar", @var{a}, @var{k})
+## Create a comparison matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("condex", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("condex", @var{n}, @var{k})
+## @deftypefnx {Function File} {@var{a} =} gallery ("condex", @var{n}, @var{k}, @var{theta})
+## Create a `counterexample' matrix to a condition estimator.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("cycol", [@var{m} @var{n}])
+## @deftypefnx {Function File} {@var{a} =} gallery ("cycol", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery (@dots{}, @var{k})
+## Create a matrix whose columns repeat cyclically.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {[@var{c},@var{d}, @var{e}] =} gallery ("dorr", @var{n})
+## @deftypefnx {Function File} {[@var{c},@var{d}, @var{e}] =} gallery ("dorr", @var{n}, @var{theta})
+## @deftypefnx {Function File} {@var{a} =} gallery ("dorr", @dots{})
+## Create a diagonally dominant, ill conditioned, tridiagonal matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("dramadah", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("dramadah", @var{n}, @var{k})
+## Create a (0, 1) matrix whose inverse has large integer entries.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("fiedler", @var{c})
+## Create a symmetric Fiedler matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("forsythe", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("forsythe", @var{n}, @var{alpha})
+## @deftypefnx {Function File} {@var{a} =} gallery ("forsythe", @var{n}, @var{alpha}, @var{lambda})
+## Create a Forsythe matrix (a perturbed Jordan block).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{f} =} gallery ("frank", @var{n})
+## @deftypefnx {Function File} {@var{f} =} gallery ("frank", @var{n}, @var{k})
+## Create a Frank matrix (ill conditioned eigenvalues).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{c} =} gallery ("gcdmat", @var{n})
+## Create a greatest common divisor matrix.
+##
+## @var{c} is an @var{n}-by-@var{n} matrix whose values correspond to the
+## greatest common divisor of its coordinate values, i.e., @var{c}(i,j)
+## correspond @code{gcd (i, j)}.
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("gearmat", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("gearmat", @var{n}, @var{i})
+## @deftypefnx {Function File} {@var{a} =} gallery ("gearmat", @var{n}, @var{i}, @var{j})
+## Create a Gear matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{g} =} gallery ("grcar", @var{n})
+## @deftypefnx {Function File} {@var{g} =} gallery ("grcar", @var{n}, @var{k})
+## Create a Toeplitz matrix with sensitive eigenvalues.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("hanowa", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("hanowa", @var{n}, @var{d})
+## Create a matrix whose eigenvalues lie on a vertical line in the complex plane.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{v} =} gallery ("house", @var{x})
+## @deftypefnx {Function File} {[@var{v}, @var{beta}] =} gallery ("house", @var{x})
+## Create a householder matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("invhess", @var{x})
+## @deftypefnx {Function File} {@var{a} =} gallery ("invhess", @var{x}, @var{y})
+## Create the inverse of an upper Hessenberg matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("invol", @var{n})
+## Create an involutory matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("ipjfact", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("ipjfact", @var{n}, @var{k})
+## Create an Hankel matrix with factorial elements.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("jordbloc", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("jordbloc", @var{n}, @var{lambda})
+## Create a Jordan block.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{u} =} gallery ("kahan", @var{n})
+## @deftypefnx {Function File} {@var{u} =} gallery ("kahan", @var{n}, @var{theta})
+## @deftypefnx {Function File} {@var{u} =} gallery ("kahan", @var{n}, @var{theta}, @var{pert})
+## Create a Kahan matrix (upper trapezoidal).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("kms", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("kms", @var{n}, @var{rho})
+## Create a Kac-Murdock-Szego Toeplitz matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{b} =} gallery ("krylov", @var{a})
+## @deftypefnx {Function File} {@var{b} =} gallery ("krylov", @var{a}, @var{x})
+## @deftypefnx {Function File} {@var{b} =} gallery ("krylov", @var{a}, @var{x}, @var{j})
+## Create a Krylov matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("lauchli", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("lauchli", @var{n}, @var{mu})
+## Create a Lauchli matrix (rectangular).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("lehmer", @var{n})
+## Create a Lehmer matrix (symmetric positive definite).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{t} =} gallery ("lesp", @var{n})
+## Create a tridiagonal matrix with real, sensitive eigenvalues.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("lotkin", @var{n})
+## Create a Lotkin matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("minij", @var{n})
+## Create a symmetric positive definite matrix MIN(i,j).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("moler", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("moler", @var{n}, @var{alpha})
+## Create a Moler matrix (symmetric positive definite).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {[@var{a}, @var{t}] =} gallery ("neumann", @var{n})
+## Create a singular matrix from the discrete Neumann problem (sparse).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{q} =} gallery ("orthog", @var{n})
+## @deftypefnx {Function File} {@var{q} =} gallery ("orthog", @var{n}, @var{k})
+## Create orthogonal and nearly orthogonal matrices.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("parter", @var{n})
+## Create a Parter matrix (a Toeplitz matrix with singular values near pi).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{p} =} gallery ("pei", @var{n})
+## @deftypefnx {Function File} {@var{p} =} gallery ("pei", @var{n}, @var{alpha})
+## Create a Pei matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("poisson", @var{n})
+## Create a block tridiagonal matrix from Poisson's equation (sparse).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("prolate", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("prolate", @var{n}, @var{w})
+## Create a prolate matrix (symmetric, ill-conditioned Toeplitz matrix).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{h} =} gallery ("randhess", @var{x})
+## Create a random, orthogonal upper Hessenberg matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("rando", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("rando", @var{n}, @var{k})
+## Create a random matrix with elements -1, 0 or 1.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("randsvd", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa})
+## @deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode})
+## @deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode}, @var{kl})
+## @deftypefnx {Function File} {@var{a} =} gallery ("randsvd", @var{n}, @var{kappa}, @var{mode}, @var{kl}, @var{ku})
+## Create a random matrix with pre-assigned singular values.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("redheff", @var{n})
+## Create a zero and ones matrix of Redheffer associated with the Riemann
+## hypothesis.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("riemann", @var{n})
+## Create a matrix associated with the Riemann hypothesis.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("ris", @var{n})
+## Create a symmetric Hankel matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("smoke", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("smoke", @var{n}, @var{k})
+## Create a complex matrix, with a `smoke ring' pseudospectrum.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{t} =} gallery ("toeppd", @var{n})
+## @deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m})
+## @deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m}, @var{w})
+## @deftypefnx {Function File} {@var{t} =} gallery ("toeppd", @var{n}, @var{m}, @var{w}, @var{theta})
+## Create a symmetric positive definite Toeplitz matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{p} =} gallery ("toeppen", @var{n})
+## @deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a})
+## @deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b})
+## @deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c})
+## @deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c}, @var{d})
+## @deftypefnx {Function File} {@var{p} =} gallery ("toeppen", @var{n}, @var{a}, @var{b}, @var{c}, @var{d}, @var{e})
+## Create a pentadiagonal Toeplitz matrix (sparse).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("tridiag", @var{x}, @var{y}, @var{z})
+## @deftypefnx {Function File} {@var{a} =} gallery ("tridiag", @var{n})
+## @deftypefnx {Function File} {@var{a} =} gallery ("tridiag", @var{n}, @var{c}, @var{d}, @var{e})
+## Create a tridiagonal matrix (sparse).
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{t} =} gallery ("triw", @var{n})
+## @deftypefnx {Function File} {@var{t} =} gallery ("triw", @var{n}, @var{alpha})
+## @deftypefnx {Function File} {@var{t} =} gallery ("triw", @var{n}, @var{alpha}, @var{k})
+## Create an upper triangular matrix discussed by Kahan, Golub and Wilkinson.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {@var{a} =} gallery ("wathen", @var{nx}, @var{ny})
+## @deftypefnx {Function File} {@var{a} =} gallery ("wathen", @var{nx}, @var{ny}, @var{k})
+## Create the Wathen matrix.
+##
+## @end deftypefn
+##
+## @deftypefn  {Function File} {[@var{a}, @var{b}] =} gallery ("wilk", @var{n})
+## Create various specific matrices devised/discussed by Wilkinson.
+##
+## @end deftypefn
+
+## Code for most of the individual matrices (except binomial, gcdmat,
+## integerdata, leslie, normaldata, randcolu, randcorr, randjorth, sampling,
+## uniformdata) by Nicholas .J. Higham <Nicholas.J.Higham@manchester.ac.uk>
+## Adapted for Octave and into single gallery function by Carnë Draug
+
+function [varargout] = gallery (name, varargin)
+
+  if (nargin < 1)
+    print_usage ();
+  elseif (! ischar (name))
+    error ("gallery: NAME must be a string.");
+  endif
+
+  ## NOTE: there isn't a lot of input check in the individual functions
+  ## that actually build the functions.  This is by design. The original
+  ## code by Higham did not perform it and was propagated to Matlab, so
+  ## for compatibility, we also don't make it. For example, arguments
+  ## that behave as switches, and in theory accepting a value of 0 or 1,
+  ## will use a value of 0, for any value other than 1 (only check made
+  ## is if the value is equal to 1). It will often also accept string
+  ## values instead of numeric. Only input check added was where it
+  ## would be causing an error anyway.
+
+  ## we will always want to return at least 1 output
+  n_out = nargout;
+  if (n_out == 0)
+    n_out = 1;
+  endif
+
+  switch (tolower (name))
+    case "binomial"
+      error ("gallery: matrix %s not implemented.", name);
+    case "cauchy"     , [varargout{1:n_out}] = cauchy      (varargin{:});
+    case "chebspec"   , [varargout{1:n_out}] = chebspec    (varargin{:});
+    case "chebvand"   , [varargout{1:n_out}] = chebvand    (varargin{:});
+    case "chow"       , [varargout{1:n_out}] = chow        (varargin{:});
+    case "circul"     , [varargout{1:n_out}] = circul      (varargin{:});
+    case "clement"    , [varargout{1:n_out}] = clement     (varargin{:});
+    case "compar"     , [varargout{1:n_out}] = compar      (varargin{:});
+    case "condex"     , [varargout{1:n_out}] = condex      (varargin{:});
+    case "cycol"      , [varargout{1:n_out}] = cycol       (varargin{:});
+    case "dorr"       , [varargout{1:n_out}] = dorr        (varargin{:});
+    case "dramadah"   , [varargout{1:n_out}] = dramadah    (varargin{:});
+    case "fiedler"    , [varargout{1:n_out}] = fiedler     (varargin{:});
+    case "forsythe"   , [varargout{1:n_out}] = forsythe    (varargin{:});
+    case "frank"      , [varargout{1:n_out}] = frank       (varargin{:});
+    case "gearmat"    , [varargout{1:n_out}] = gearmat     (varargin{:});
+    case "gcdmat"     , [varargout{1:n_out}] = gcdmat      (varargin{:});
+    case "grcar"      , [varargout{1:n_out}] = grcar       (varargin{:});
+    case "hanowa"     , [varargout{1:n_out}] = hanowa      (varargin{:});
+    case "house"      , [varargout{1:n_out}] = house       (varargin{:});
+    case "integerdata"
+      error ("gallery: matrix %s not implemented.", name);
+    case "invhess"    , [varargout{1:n_out}] = invhess     (varargin{:});
+    case "invol"      , [varargout{1:n_out}] = invol       (varargin{:});
+    case "ipjfact"    , [varargout{1:n_out}] = ipjfact     (varargin{:});
+    case "jordbloc"   , [varargout{1:n_out}] = jordbloc    (varargin{:});
+    case "kahan"      , [varargout{1:n_out}] = kahan       (varargin{:});
+    case "kms"        , [varargout{1:n_out}] = kms         (varargin{:});
+    case "krylov"     , [varargout{1:n_out}] = krylov      (varargin{:});
+    case "lauchli"    , [varargout{1:n_out}] = lauchli     (varargin{:});
+    case "lehmer"     , [varargout{1:n_out}] = lehmer      (varargin{:});
+    case "leslie"
+      error ("gallery: matrix %s not implemented.", name);
+    case "lesp"       , [varargout{1:n_out}] = lesp        (varargin{:});
+    case "lotkin"     , [varargout{1:n_out}] = lotkin      (varargin{:});
+    case "minij"      , [varargout{1:n_out}] = minij       (varargin{:});
+    case "moler"      , [varargout{1:n_out}] = moler       (varargin{:});
+    case "neumann"    , [varargout{1:n_out}] = neumann     (varargin{:});
+    case "normaldata"
+      error ("gallery: matrix %s not implemented.", name);
+    case "orthog"     , [varargout{1:n_out}] = orthog      (varargin{:});
+    case "parter"     , [varargout{1:n_out}] = parter      (varargin{:});
+    case "pei"        , [varargout{1:n_out}] = pei         (varargin{:});
+    case "poisson"    , [varargout{1:n_out}] = poisson     (varargin{:});
+    case "prolate"    , [varargout{1:n_out}] = prolate     (varargin{:});
+    case "randcolu"
+      error ("gallery: matrix %s not implemented.", name);
+    case "randcorr"
+      error ("gallery: matrix %s not implemented.", name);
+    case "randhess"    , [varargout{1:n_out}] = randhess    (varargin{:});
+    case "randjorth"
+      error ("gallery: matrix %s not implemented.", name);
+    case "rando"       , [varargout{1:n_out}] = rando       (varargin{:});
+    case "randsvd"     , [varargout{1:n_out}] = randsvd     (varargin{:});
+    case "redheff"     , [varargout{1:n_out}] = redheff     (varargin{:});
+    case "riemann"     , [varargout{1:n_out}] = riemann     (varargin{:});
+    case "ris"         , [varargout{1:n_out}] = ris         (varargin{:});
+    case "sampling"
+      error ("gallery: matrix %s not implemented.", name);
+    case "smoke"       , [varargout{1:n_out}] = smoke       (varargin{:});
+    case "toeppd"      , [varargout{1:n_out}] = toeppd      (varargin{:});
+    case "toeppen"     , [varargout{1:n_out}] = toeppen     (varargin{:});
+    case "tridiag"     , [varargout{1:n_out}] = tridiag     (varargin{:});
+    case "triw"        , [varargout{1:n_out}] = triw        (varargin{:});
+    case "uniformdata"
+      error ("gallery: matrix %s not implemented.", name);
+    case "wathen"      , [varargout{1:n_out}] = wathen      (varargin{:});
+    case "wilk"        , [varargout{1:n_out}] = wilk        (varargin{:});
+    otherwise
+      error ("gallery: unknown matrix with NAME %s", name);
+  endswitch
+
+endfunction
+
+function C = cauchy (x, y)
+  ##CAUCHY  Cauchy matrix.
+  ##        C = CAUCHY(X, Y), where X, Y are N-vectors, is the N-by-N matrix
+  ##        with C(i,j) = 1/(X(i)+Y(j)).   By default, Y = X.
+  ##        Special case: if X is a scalar CAUCHY(X) is the same as CAUCHY(1:X).
+  ##        Explicit formulas are known for DET(C) (which is nonzero if X and Y
+  ##        both have distinct elements) and the elements of INV(C).
+  ##        C is totally positive if 0 < X(1) < ... < X(N) and
+  ##        0 < Y(1) < ... < Y(N).
+  ##
+  ##        References:
+  ##        N.J. Higham, Accuracy and Stability of Numerical Algorithms,
+  ##          Society for Industrial and Applied Mathematics, Philadelphia, PA,
+  ##          USA, 1996; sec. 26.1.
+  ##        D.E. Knuth, The Art of Computer Programming, Volume 1,
+  ##          Fundamental Algorithms, second edition, Addison-Wesley, Reading,
+  ##          Massachusetts, 1973, p. 36.
+  ##        E.E. Tyrtyshnikov, Cauchy-Toeplitz matrices and some applications,
+  ##          Linear Algebra and Appl., 149 (1991), pp. 1-18.
+  ##          O. Taussky and M. Marcus, Eigenvalues of finite matrices, in
+  ##          Survey of Numerical Analysis, J. Todd, ed., McGraw-Hill, New York,
+  ##          pp. 279-313, 1962. (States the totally positive property on p. 295.)
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for cauchy matrix.");
+  elseif (! isnumeric (x))
+    error ("gallery: X must be numeric for cauchy matrix.");
+  elseif (nargin == 2 && ! isnumeric (y))
+    error ("gallery: Y must be numeric for cauchy matrix.");
+  endif
+
+  n = numel (x);
+  if (isscalar (x) && fix (x) == x)
+    n = x;
+    x = 1:n;
+  elseif (n > 1 && isvector (x))
+    ## do nothing
+  else
+    error ("gallery: X be an integer or a vector for cauchy matrix.");
+  endif
+
+  if (nargin == 1)
+    y = x;
+  endif
+
+  ## Ensure x and y are column vectors
+  x = x(:);
+  y = y(:);
+  if (numel (x) != numel (y))
+    error ("gallery: X and Y must be vectors of same length for cauchy matrix.");
+  endif
+
+  C = x * ones (1, n) + ones (n, 1) * y.';
+  C = ones (n) ./ C;
+endfunction
+
+function C = chebspec (n, k = 0)
+  ## CHEBSPEC  Chebyshev spectral differentiation matrix.
+  ##           C = CHEBSPEC(N, K) is a Chebyshev spectral differentiation
+  ##           matrix of order N.  K = 0 (the default) or 1.
+  ##           For K = 0 (`no boundary conditions'), C is nilpotent, with
+  ##               C^N = 0 and it has the null vector ONES(N,1).
+  ##               C is similar to a Jordan block of size N with eigenvalue zero.
+  ##           For K = 1, C is nonsingular and well-conditioned, and its eigenvalues
+  ##               have negative real parts.
+  ##           For both K, the computed eigenvector matrix X from EIG is
+  ##               ill-conditioned (MESH(REAL(X)) is interesting).
+  ##
+  ##           References:
+  ##           C. Canuto, M.Y. Hussaini, A. Quarteroni and T.A. Zang, Spectral
+  ##              Methods in Fluid Dynamics, Springer-Verlag, Berlin, 1988; p. 69.
+  ##           L.N. Trefethen and M.R. Trummer, An instability phenomenon in
+  ##              spectral methods, SIAM J. Numer. Anal., 24 (1987), pp. 1008-1023.
+  ##           D. Funaro, Computing the inverse of the Chebyshev collocation
+  ##              derivative, SIAM J. Sci. Stat. Comput., 9 (1988), pp. 1050-1057.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for chebspec matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for chebspec matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a scalar for chebspec matrix.");
+  endif
+
+  ## k = 1 case obtained from k = 0 case with one bigger n.
+  switch (k)
+    case (0), # do nothing
+    case (1), n = n + 1;
+    otherwise
+      error ("gallery: unknown K `%d' for chebspec matrix.", k);
+  endswitch
+
+  n = n-1;
+  C = zeros (n+1);
+
+  one    = ones (n+1, 1);
+  x      = cos ((0:n)' * (pi/n));
+  d      = ones (n+1, 1);
+  d(1)   = 2;
+  d(n+1) = 2;
+
+  ## eye(size(C)) on next line avoids div by zero.
+  C = (d * (one./d)') ./ (x*one'-one*x' + eye (size (C)));
+
+  ##  Now fix diagonal and signs.
+  C(1,1) = (2*n^2+1)/6;
+  for i = 2:n+1
+    if (rem (i, 2) == 0)
+      C(:,i) = -C(:,i);
+      C(i,:) = -C(i,:);
+    endif
+    if (i < n+1)
+      C(i,i) = -x(i)/(2*(1-x(i)^2));
+    else
+      C(n+1,n+1) = -C(1,1);
+    endif
+  endfor
+
+  if (k == 1)
+    C = C(2:n+1,2:n+1);
+  endif
+endfunction
+
+function C = chebvand (m, p)
+  ## CHEBVAND Vandermonde-like matrix for the Chebyshev polynomials.
+  ##          C = CHEBVAND(P), where P is a vector, produces the (primal)
+  ##          Chebyshev Vandermonde matrix based on the points P,
+  ##          i.e., C(i,j) = T_{i-1}(P(j)), where T_{i-1} is the Chebyshev
+  ##          polynomial of degree i-1.
+  ##          CHEBVAND(M,P) is a rectangular version of CHEBVAND(P) with M rows.
+  ##          Special case: If P is a scalar then P equally spaced points on
+  ##                        [0,1] are used.
+  ##
+  ##          Reference:
+  ##          N.J. Higham, Stability analysis of algorithms for solving confluent
+  ##            Vandermonde-like systems, SIAM J. Matrix Anal. Appl., 11 (1990),
+  ##            pp. 23-41.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for chebvand matrix.");
+  endif
+
+  ## because the order of the arguments changes if nargin is 1 or 2 ...
+
+  if (nargin == 1)
+    p = m;
+  endif
+
+  n = numel (p);
+  if (! isnumeric (p))
+    error ("gallery: P must be numeric for chebvand matrix.");
+  elseif (isscalar (p) && fix (p) == p)
+    n = p;
+    p = linspace (0, 1, n);
+  elseif (n > 1 && isvector (p))
+    ## do nothing
+  endif
+  p = p(:).'; # Ensure p is a row vector.
+
+  if (nargin == 1)
+    m = n;
+  elseif (! isnumeric (m) || ! isscalar (m))
+    error ("gallery: M must be a scalar for chebvand matrix.");
+  endif
+
+  C = ones (m, n);
+  if (m != 1)
+    C(2,:) = p;
+    ##      Use Chebyshev polynomial recurrence.
+    for i = 3:m
+      C(i,:) = 2.*p.*C(i-1,:) - C(i-2,:);
+    endfor
+  endif
+endfunction
+
+function A = chow (n, alpha = 1, delta = 0)
+  ## CHOW    Chow matrix - a singular Toeplitz lower Hessenberg matrix.
+  ##         A = CHOW(N, ALPHA, DELTA) is a Toeplitz lower Hessenberg matrix
+  ##         A = H(ALPHA) + DELTA*EYE, where H(i,j) = ALPHA^(i-j+1).
+  ##         H(ALPHA) has p = FLOOR(N/2) zero eigenvalues, the rest being
+  ##         4*ALPHA*COS( k*PI/(N+2) )^2, k=1:N-p.
+  ##         Defaults: ALPHA = 1, DELTA = 0.
+  ##
+  ##         References:
+  ##         T.S. Chow, A class of Hessenberg matrices with known
+  ##            eigenvalues and inverses, SIAM Review, 11 (1969), pp. 391-395.
+  ##         G. Fairweather, On the eigenvalues and eigenvectors of a class of
+  ##            Hessenberg matrices, SIAM Review, 13 (1971), pp. 220-221.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for chow matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for chow matrix.");
+  elseif (! isnumeric (alpha) || ! isscalar (alpha))
+    error ("gallery: ALPHA must be a scalar for chow matrix.");
+  elseif (! isnumeric (delta) || ! isscalar (delta))
+    error ("gallery: DELTA must be a scalar for chow matrix.");
+  endif
+
+  A = toeplitz (alpha.^(1:n), [alpha 1 zeros(1, n-2)]) + delta * eye (n);
+endfunction
+
+function C = circul (v)
+  ## CIRCUL  Circulant matrix.
+  ##         C = CIRCUL(V) is the circulant matrix whose first row is V.
+  ##         (A circulant matrix has the property that each row is obtained
+  ##         from the previous one by cyclically permuting the entries one step
+  ##         forward; it is a special Toeplitz matrix in which the diagonals
+  ##         `wrap round'.)
+  ##         Special case: if V is a scalar then C = CIRCUL(1:V).
+  ##         The eigensystem of C (N-by-N) is known explicitly.   If t is an Nth
+  ##         root of unity, then the inner product of V with W = [1 t t^2 ... t^N]
+  ##         is an eigenvalue of C, and W(N:-1:1) is an eigenvector of C.
+  ##
+  ##         Reference:
+  ##         P.J. Davis, Circulant Matrices, John Wiley, 1977.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for circul matrix.");
+  elseif (! isnumeric (v))
+    error ("gallery: V must be numeric for circul matrix.");
+  endif
+
+  n = numel (x);
+  if (isscalar (x) && fix (x) == x)
+    n = v;
+    v = 1:n;
+  elseif (n > 1 && isvector (x))
+    ## do nothing
+  else
+    error ("gallery: X must be a scalar or a vector for circul matrix.");
+  endif
+
+  v = v(:).';   # Make sure v is a row vector
+  C = toeplitz ([v(1) v(n:-1:2)], v);
+endfunction
+
+function A = clement (n, k = 0)
+  ## CLEMENT   Clement matrix - tridiagonal with zero diagonal entries.
+  ##           CLEMENT(N, K) is a tridiagonal matrix with zero diagonal entries
+  ##           and known eigenvalues.  It is singular if N is odd.  About 64
+  ##           percent of the entries of the inverse are zero.  The eigenvalues
+  ##           are plus and minus the numbers N-1, N-3, N-5, ..., (1 or 0).
+  ##           For K = 0 (the default) the matrix is unsymmetric, while for
+  ##           K = 1 it is symmetric.
+  ##           CLEMENT(N, 1) is diagonally similar to CLEMENT(N).
+  ##
+  ##           Similar properties hold for TRIDIAG(X,Y,Z) where Y = ZEROS(N,1).
+  ##           The eigenvalues still come in plus/minus pairs but they are not
+  ##           known explicitly.
+  ##
+  ##           References:
+  ##           P.A. Clement, A class of triple-diagonal matrices for test
+  ##              purposes, SIAM Review, 1 (1959), pp. 50-52.
+  ##           A. Edelman and E. Kostlan, The road from Kac's matrix to Kac's
+  ##              random polynomials. In John~G. Lewis, editor, Proceedings of
+  ##              the Fifth SIAM Conference on Applied Linear Algebra Society
+  ##              for Industrial and Applied Mathematics, Philadelphia, 1994,
+  ##              pp. 503-507.
+  ##           O. Taussky and J. Todd, Another look at a matrix of Mark Kac,
+  ##              Linear Algebra and Appl., 150 (1991), pp. 341-360.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for clement matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for clement matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for clement matrix.");
+  endif
+
+  n = n-1;
+  x = n:-1:1;
+  z = 1:n;
+
+  if (k == 0)
+    A = diag (x, -1) + diag (z, 1);
+  elseif (k == 1)
+    y = sqrt (x.*z);
+    A = diag (y, -1) + diag (y, 1);
+  else
+    error ("gallery: K must have a value of 0 or 1 for clement matrix.");
+  endif
+endfunction
+
+function C = compar (A, k = 0)
+  ## COMP    Comparison matrices.
+  ##         COMP(A) is DIAG(B) - TRIL(B,-1) - TRIU(B,1), where B = ABS(A).
+  ##         COMP(A, 1) is A with each diagonal element replaced by its
+  ##         absolute value, and each off-diagonal element replaced by minus
+  ##         the absolute value of the largest element in absolute value in
+  ##         its row.  However, if A is triangular COMP(A, 1) is too.
+  ##         COMP(A, 0) is the same as COMP(A).
+  ##         COMP(A) is often denoted by M(A) in the literature.
+  ##
+  ##         Reference (e.g.):
+  ##         N.J. Higham, A survey of condition number estimation for
+  ##         triangular matrices, SIAM Review, 29 (1987), pp. 575-596.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for compar matrix.");
+  elseif (! isnumeric (A) || ndims (A) != 2)
+    error ("gallery: A must be a 2D matrix for compar matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for compar matrix.");
+  endif
+
+  [m, n] = size (A);
+  p = min (m, n);
+
+  if (k == 0)
+    ## This code uses less temporary storage than
+    ## the `high level' definition above.
+    C = -abs (A);
+    for j = 1:p
+      C(j,j) = abs (A(j,j));
+    endfor
+
+  elseif (k == 1)
+    C = A';
+    for j = 1:p
+      C(k,k) = 0;
+    endfor
+    mx = max (abs (C));
+    C  = -mx'*ones (1, n);
+    for j = 1:p
+      C(j,j) = abs (A(j,j));
+    endfor
+    if (all (A == tril (A))), C = tril (C); endif
+    if (all (A == triu (A))), C = triu (C); endif
+
+  else
+    error ("gallery: K must have a value of 0 or 1 for compar matrix.");
+  endif
+
+endfunction
+
+function A = condex (n, k = 4, theta = 100)
+  ## CONDEX   `Counterexamples' to matrix condition number estimators.
+  ##          CONDEX(N, K, THETA) is a `counterexample' matrix to a condition
+  ##          estimator.  It has order N and scalar parameter THETA (default 100).
+  ##          If N is not equal to the `natural' size of the matrix then
+  ##          the matrix is padded out with an identity matrix to order N.
+  ##          The matrix, its natural size, and the estimator to which it applies
+  ##          are specified by K (default K = 4) as follows:
+  ##              K = 1:   4-by-4,     LINPACK (RCOND)
+  ##              K = 2:   3-by-3,     LINPACK (RCOND)
+  ##              K = 3:   arbitrary,  LINPACK (RCOND) (independent of THETA)
+  ##              K = 4:   N >= 4,     SONEST (Higham 1988)
+  ##          (Note that in practice the K = 4 matrix is not usually a
+  ##           counterexample because of the rounding errors in forming it.)
+  ##
+  ##          References:
+  ##          A.K. Cline and R.K. Rew, A set of counter-examples to three
+  ##             condition number estimators, SIAM J. Sci. Stat. Comput.,
+  ##             4 (1983), pp. 602-611.
+  ##          N.J. Higham, FORTRAN codes for estimating the one-norm of a real or
+  ##             complex matrix, with applications to condition estimation
+  ##             (Algorithm 674), ACM Trans. Math. Soft., 14 (1988), pp. 381-396.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for condex matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for condex matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for condex matrix.");
+  elseif (! isnumeric (theta) || ! isscalar (theta))
+    error ("gallery: THETA must be a numeric scalar for condex matrix.");
+  endif
+
+  if (k == 1)       # Cline and Rew (1983), Example B.
+    A = [1  -1  -2*theta     0
+         0   1     theta  -theta
+         0   1   1+theta  -(theta+1)
+         0   0   0         theta];
+
+  elseif (k == 2)   # Cline and Rew (1983), Example C.
+    A = [1   1-2/theta^2  -2
+         0   1/theta      -1/theta
+         0   0             1];
+
+  elseif (k == 3)   # Cline and Rew (1983), Example D.
+    A = gallery ("triw", n, -1)';
+    A(n,n) = -1;
+
+  elseif (k == 4)   # Higham (1988), p. 390.
+    x = ones (n, 3);            #  First col is e
+    x(2:n,2) = zeros (n-1, 1);  #  Second col is e(1)
+
+    ## Third col is special vector b in SONEST
+    x(:, 3) = (-1).^[0:n-1]' .* ( 1 + [0:n-1]'/(n-1) );
+
+    Q = orth (x);  #  Q*Q' is now the orthogonal projector onto span(e(1),e,b)).
+    P = eye (n) - Q*Q';
+    A = eye (n) + theta*P;
+
+  else
+    error ("gallery: unknown estimator K `%d' for condex matrix.", k);
+  endif
+
+  ## Pad out with identity as necessary.
+  m = columns (A);
+  if (m < n)
+    for i = n:-1:m+1
+      A(i,i) = 1;
+    endfor
+  endif
+endfunction
+
+function A = cycol (n, k)
+  ## CYCOL   Matrix whose columns repeat cyclically.
+  ##         A = CYCOL([M N], K) is an M-by-N matrix of the form A = B(1:M,1:N)
+  ##         where B = [C C C...] and C = RANDN(M, K).  Thus A's columns repeat
+  ##         cyclically, and A has rank at most K.   K need not divide N.
+  ##         K defaults to ROUND(N/4).
+  ##         CYCOL(N, K), where N is a scalar, is the same as CYCOL([N N], K).
+  ##
+  ##         This type of matrix can lead to underflow problems for Gaussian
+  ##         elimination: see NA Digest Volume 89, Issue 3 (January 22, 1989).
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for cycol matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]) || fix (n) != n)
+    error ("gallery: N must be a 1 or 2 element integer for cycol matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a scalar for cycol matrix.");
+  endif
+
+  ## Parameter n specifies dimension: m-by-n
+  m = n(1);
+  n = n(end);
+
+  if (nargin < 2)
+    k = max (round (n/4), 1);
+  endif
+
+  A = randn (m, k);
+  for i = 2:ceil (n/k)
+    A = [A A(:,1:k)];
+  endfor
+  A = A(:,1:n);
+endfunction
+
+function [c, d, e] = dorr (n, theta = 0.01)
+  ## DORR  Dorr matrix - diagonally dominant, ill conditioned, tridiagonal.
+  ##       [C, D, E] = DORR(N, THETA) returns the vectors defining a row diagonally
+  ##       dominant, tridiagonal M-matrix that is ill conditioned for small
+  ##       values of the parameter THETA >= 0.
+  ##       If only one output parameter is supplied then
+  ##       C = FULL(TRIDIAG(C,D,E)), i.e., the matrix iself is returned.
+  ##       The columns of INV(C) vary greatly in norm.  THETA defaults to 0.01.
+  ##       The amount of diagonal dominance is given by (ignoring rounding errors):
+  ##             COMP(C)*ONES(N,1) = THETA*(N+1)^2 * [1 0 0 ... 0 1]'.
+  ##
+  ##       Reference:
+  ##       F.W. Dorr, An example of ill-conditioning in the numerical
+  ##       solution of singular perturbation problems, Math. Comp., 25 (1971),
+  ##       pp. 271-283.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 or 2 arguments are required for dorr matrix.");
+  elseif (! isscalar (n) || ! isnumeric (n) || fix (n) != n)
+    error ("gallery: N must be an integer for dorr matrix.");
+  elseif (! isscalar (theta) || ! isnumeric (theta))
+    error ("gallery: THETA must be a numeric scalar for dorr matrix.");
+  endif
+
+  c = zeros (n, 1);
+  e = c;
+  d = c;
+  ##  All length n for convenience.  Make c, e of length n-1 later.
+
+  h = 1/(n+1);
+  m = floor ((n+1)/2);
+  term = theta/h^2;
+
+  i = (1:m)';
+  c(i) = -term * ones (m, 1);
+  e(i) = c(i) - (0.5-i*h)/h;
+  d(i) = -(c(i) + e(i));
+
+  i = (m+1:n)';
+  e(i) = -term * ones (n-m, 1);
+  c(i) = e(i) + (0.5-i*h)/h;
+  d(i) = -(c(i) + e(i));
+
+  c = c(2:n);
+  e = e(1:n-1);
+
+  if (nargout <= 1)
+    c = tridiag (c, d, e);
+  endif
+endfunction
+
+function A = dramadah (n, k = 1)
+  ## DRAMADAH  A (0,1) matrix whose inverse has large integer entries.
+  ##           An anti-Hadamard matrix A is a matrix with elements 0 or 1 for
+  ##           which MU(A) := NORM(INV(A),'FRO') is maximal.
+  ##           A = DRAMADAH(N, K) is an N-by-N (0,1) matrix for which MU(A) is
+  ##           relatively large, although not necessarily maximal.
+  ##           Available types (the default is K = 1):
+  ##           K = 1: A is Toeplitz, with ABS(DET(A)) = 1, and MU(A) > c(1.75)^N,
+  ##                  where c is a constant.
+  ##           K = 2: A is upper triangular and Toeplitz.
+  ##           The inverses of both types have integer entries.
+  ##
+  ##           Another interesting (0,1) matrix:
+  ##           K = 3: A has maximal determinant among (0,1) lower Hessenberg
+  ##           matrices: det(A) = the n'th Fibonacci number.  A is Toeplitz.
+  ##           The eigenvalues have an interesting distribution in the complex
+  ##           plane.
+  ##
+  ##           References:
+  ##           R.L. Graham and N.J.A. Sloane, Anti-Hadamard matrices,
+  ##              Linear Algebra and Appl., 62 (1984), pp. 113-137.
+  ##           L. Ching, The maximum determinant of an nxn lower Hessenberg
+  ##              (0,1) matrix, Linear Algebra and Appl., 183 (1993), pp. 147-153.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for dramadah matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for dramadah matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for dramadah matrix.");
+  endif
+
+  switch (k)
+    case (1)  # Toeplitz
+      c = ones (n, 1);
+      for i = 2:4:n
+        m = min (1, n-i);
+        c(i:i+m) = zeros (m+1, 1);
+      endfor
+      r = zeros (n, 1);
+      r(1:4) = [1 1 0 1];
+      if (n < 4)
+        r = r(1:n);
+      endif
+      A = toeplitz (c, r);
+
+    case (2)  # Upper triangular and Toeplitz
+      c = zeros (n, 1);
+      c(1) = 1;
+      r = ones (n, 1);
+      for i= 3:2:n
+        r(i) = 0;
+      endfor
+      A = toeplitz (c, r);
+
+    case (3)  # Lower Hessenberg
+      c = ones (n, 1);
+      for i= 2:2:n
+        c(i) = 0;
+      endfor
+      A = toeplitz (c, [1 1 zeros(1,n-2)]);
+
+    otherwise
+      error ("gallery: unknown K `%d' for dramadah matrix.", k);
+  endswitch
+endfunction
+
+function A = fiedler (c)
+  ## FIEDLER  Fiedler matrix - symmetric.
+  ##          A = FIEDLER(C), where C is an n-vector, is the n-by-n symmetric
+  ##          matrix with elements ABS(C(i)-C(j)).
+  ##          Special case: if C is a scalar, then A = FIEDLER(1:C)
+  ##                        (i.e. A(i,j) = ABS(i-j)).
+  ##          Properties:
+  ##            FIEDLER(N) has a dominant positive eigenvalue and all the other
+  ##                       eigenvalues are negative (Szego, 1936).
+  ##            Explicit formulas for INV(A) and DET(A) are given by Todd (1977)
+  ##            and attributed to Fiedler.  These indicate that INV(A) is
+  ##            tridiagonal except for nonzero (1,n) and (n,1) elements.
+  ##            [I think these formulas are valid only if the elements of
+  ##            C are in increasing or decreasing order---NJH.]
+  ##
+  ##            References:
+  ##            G. Szego, Solution to problem 3705, Amer. Math. Monthly,
+  ##               43 (1936), pp. 246-259.
+  ##            J. Todd, Basic Numerical Mathematics, Vol. 2: Numerical Algebra,
+  ##               Birkhauser, Basel, and Academic Press, New York, 1977, p. 159.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for fiedler matrix.");
+  elseif (! isnumeric (c))
+    error ("gallery: C must be numeric for fiedler matrix.");
+  endif
+
+  n = numel (c);
+  if (isscalar (c) && fix (c) == c)
+    n = c;
+    c = 1:n;
+  elseif (n > 1 && isvector (c))
+    ## do nothing
+  else
+    error ("gallery: C must be an integer or a vector for fiedler matrix.");
+  endif
+  c = c(:).';           # Ensure c is a row vector.
+
+  A = ones (n, 1) * c;
+  A = abs (A - A.');    # NB. array transpose.
+endfunction
+
+function A = forsythe (n, alpha = sqrt (eps), lambda = 0)
+  ## FORSYTHE  Forsythe matrix - a perturbed Jordan block.
+  ##           FORSYTHE(N, ALPHA, LAMBDA) is the N-by-N matrix equal to
+  ##           JORDBLOC(N, LAMBDA) except it has an ALPHA in the (N,1) position.
+  ##           It has the characteristic polynomial
+  ##                   DET(A-t*EYE) = (LAMBDA-t)^N - (-1)^N ALPHA.
+  ##           ALPHA defaults to SQRT(EPS) and LAMBDA to 0.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for forsythe matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for forsythe matrix.");
+  elseif (! isnumeric (alpha) || ! isscalar (alpha))
+    error ("gallery: ALPHA must be a numeric scalar for forsythe matrix.");
+  elseif (! isnumeric (lambda) || ! isscalar (lambda))
+    error ("gallery: LAMBDA must be a numeric scalar for forsythe matrix.");
+  endif
+
+  A = jordbloc (n, lambda);
+  A(n,1) = alpha;
+endfunction
+
+function F = frank (n, k = 0)
+  ## FRANK   Frank matrix---ill conditioned eigenvalues.
+  ##         F = FRANK(N, K) is the Frank matrix of order N.  It is upper
+  ##         Hessenberg with determinant 1.  K = 0 is the default; if K = 1 the
+  ##         elements are reflected about the anti-diagonal (1,N)--(N,1).
+  ##         F has all positive eigenvalues and they occur in reciprocal pairs
+  ##         (so that 1 is an eigenvalue if N is odd).
+  ##         The eigenvalues of F may be obtained in terms of the zeros of the
+  ##         Hermite polynomials.
+  ##         The FLOOR(N/2) smallest eigenvalues of F are ill conditioned,
+  ##         the more so for bigger N.
+  ##
+  ##         DET(FRANK(N)') comes out far from 1 for large N---see Frank (1958)
+  ##         and Wilkinson (1960) for discussions.
+  ##
+  ##         This version incorporates improvements suggested by W. Kahan.
+  ##
+  ##         References:
+  ##         W.L. Frank, Computing eigenvalues of complex matrices by determinant
+  ##            evaluation and by methods of Danilewski and Wielandt, J. Soc.
+  ##            Indust. Appl. Math., 6 (1958), pp. 378-392 (see pp. 385, 388).
+  ##         G.H. Golub and J.H. Wilkinson, Ill-conditioned eigensystems and the
+  ##            computation of the Jordan canonical form, SIAM Review, 18 (1976),
+  ##              pp. 578-619 (Section 13).
+  ##         H. Rutishauser, On test matrices, Programmation en Mathematiques
+  ##            Numeriques, Editions Centre Nat. Recherche Sci., Paris, 165,
+  ##            1966, pp. 349-365.  Section 9.
+  ##         J.H. Wilkinson, Error analysis of floating-point computation,
+  ##            Numer. Math., 2 (1960), pp. 319-340 (Section 8).
+  ##         J.H. Wilkinson, The Algebraic Eigenvalue Problem, Oxford University
+  ##            Press, 1965 (pp. 92-93).
+  ##         The next two references give details of the eigensystem, as does
+  ##         Rutishauser (see above).
+  ##         P.J. Eberlein, A note on the matrices denoted by B_n, SIAM J. Appl.
+  ##            Math., 20 (1971), pp. 87-92.
+  ##         J.M. Varah, A generalization of the Frank matrix, SIAM J. Sci. Stat.
+  ##            Comput., 7 (1986), pp. 835-839.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for frank matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for frank matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for frank matrix.");
+  endif
+
+  p = n:-1:1;
+  F = triu (p(ones (n, 1), :) - diag (ones (n-1, 1), -1), -1);
+
+  switch (k)
+    case (0), # do nothing
+    case (1), F = F(p,p)';
+    otherwise
+      error ("gallery: K must have a value of 0 or 1 for frank matrix.");
+  endswitch
+endfunction
+
+function c = gcdmat (n)
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for gcdmat matrix.");
+  elseif (! isscalar (n) || ! isnumeric (n) || fix (n) != n)
+    error ("gallery: N must be an integer for gcdmat matrix.");
+  endif
+  c = gcd (repmat ((1:n)', [1 n]), repmat (1:n, [n 1]));
+endfunction
+
+function A = gearmat (n, i = n, j = -n)
+  ## NOTE: this function was named gearm in the original Test Matrix Toolbox
+  ## GEARMAT   Gear matrix.
+  ##         A = GEARMAT(N,I,J) is the N-by-N matrix with ones on the sub- and
+  ##         super-diagonals, SIGN(I) in the (1,ABS(I)) position, SIGN(J)
+  ##         in the (N,N+1-ABS(J)) position, and zeros everywhere else.
+  ##         Defaults: I = N, j = -N.
+  ##         All eigenvalues are of the form 2*COS(a) and the eigenvectors
+  ##         are of the form [SIN(w+a), SIN(w+2a), ..., SIN(w+Na)].
+  ##         The values of a and w are given in the reference below.
+  ##         A can have double and triple eigenvalues and can be defective.
+  ##         GEARMAT(N) is singular.
+  ##
+  ##         (GEAR is a Simulink function, hence GEARMAT for Gear matrix.)
+  ##         Reference:
+  ##         C.W. Gear, A simple set of test matrices for eigenvalue programs,
+  ##         Math. Comp., 23 (1969), pp. 119-125.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for gearmat matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for gearmat matrix.");
+  elseif (! isnumeric (i) || ! isscalar (i) || i == 0 || abs (i) <= n)
+    error ("gallery: I must be a non-zero scalar, and abs (I) <= N for gearmat matrix.");
+  elseif (! isnumeric (j) || ! isscalar (j) || i == 0 || abs (j) <= n)
+    error ("gallery: J must be a non-zero scalar, and abs (J) <= N for gearmat matrix.");
+  endif
+
+  A = diag (ones (n-1, 1), -1) + diag (ones (n-1, 1), 1);
+  A(1, abs (i)) = sign (i);
+  A(n, n+1 - abs (j)) = sign (j);
+endfunction
+
+function G = grcar (n, k = 3)
+  ## GRCAR     Grcar matrix - a Toeplitz matrix with sensitive eigenvalues.
+  ##           GRCAR(N, K) is an N-by-N matrix with -1s on the
+  ##           subdiagonal, 1s on the diagonal, and K superdiagonals of 1s.
+  ##           The default is K = 3.  The eigenvalues of this matrix form an
+  ##           interesting pattern in the complex plane (try PS(GRCAR(32))).
+  ##
+  ##           References:
+  ##           J.F. Grcar, Operator coefficient methods for linear equations,
+  ##                Report SAND89-8691, Sandia National Laboratories, Albuquerque,
+  ##                New Mexico, 1989 (Appendix 2).
+  ##           N.M. Nachtigal, L. Reichel and L.N. Trefethen, A hybrid GMRES
+  ##                algorithm for nonsymmetric linear systems, SIAM J. Matrix Anal.
+  ##                Appl., 13 (1992), pp. 796-825.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for grcar matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for grcar matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for grcar matrix.");
+  endif
+
+  G = tril (triu (ones (n)), k) - diag (ones (n-1, 1), -1);
+endfunction
+
+function A = hanowa (n, d = -1)
+  ## HANOWA  A matrix whose eigenvalues lie on a vertical line in the complex plane.
+  ##         HANOWA(N, d) is the N-by-N block 2x2 matrix (thus N = 2M must be even)
+  ##                       [d*EYE(M)   -DIAG(1:M)
+  ##                        DIAG(1:M)   d*EYE(M)]
+  ##         It has complex eigenvalues lambda(k) = d +/- k*i  (1 <= k <= M).
+  ##         Parameter d defaults to -1.
+  ##
+  ##         Reference:
+  ##         E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
+  ##         Differential Equations I: Nonstiff Problems, Springer-Verlag,
+  ##         Berlin, 1987. (pp. 86-87)
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for hanowa matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for hanowa matrix.");
+  elseif (rem (n, 2) != 0)
+    error ("gallery: N must be even for hanowa matrix.");
+  elseif (! isnumeric (lambda) || ! isscalar (lambda))
+    error ("gallery: D must be a numeric scalar for hanowa matrix.");
+  endif
+
+  m = n/2;
+  A = [ d*eye(m)  -diag(1:m)
+        diag(1:m)  d*eye(m) ];
+endfunction
+
+function [v, beta] = house (x)
+  ## HOUSE   Householder matrix.
+  ##         If [v, beta] = HOUSE(x) then H = EYE - beta*v*v' is a Householder
+  ##         matrix such that Hx = -sign(x(1))*norm(x)*e_1.
+  ##         NB: If x = 0 then v = 0, beta = 1 is returned.
+  ##             x can be real or complex.
+  ##             sign(x) := exp(i*arg(x)) ( = x./abs(x) when x ~= 0).
+  ##
+  ##         Theory: (textbook references Golub & Van Loan 1989, 38-43;
+  ##                  Stewart 1973, 231-234, 262; Wilkinson 1965, 48-50).
+  ##         Hx = y: (I - beta*v*v')x = -s*e_1.
+  ##         Must have |s| = norm(x), v = x+s*e_1, and
+  ##         x'y = x'Hx =(x'Hx)' real => arg(s) = arg(x(1)).
+  ##         So take s = sign(x(1))*norm(x) (which avoids cancellation).
+  ##         v'v = (x(1)+s)^2 + x(2)^2 + ... + x(n)^2
+  ##             = 2*norm(x)*(norm(x) + |x(1)|).
+  ## 
+  ##         References:
+  ##         G.H. Golub and C.F. Van Loan, Matrix Computations, second edition,
+  ##            Johns Hopkins University Press, Baltimore, Maryland, 1989.
+  ##         G.W. Stewart, Introduction to Matrix Computations, Academic Press,
+  ##            New York, 1973,
+  ##         J.H. Wilkinson, The Algebraic Eigenvalue Problem, Oxford University
+  ##            Press, 1965.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for house matrix.");
+  elseif (! isnumeric (x) || ! isvector (x) || numel (x) <= 1)
+    error ("gallery: X must be a vector for house matrix.");
+  endif
+
+  ## must be a column vector
+  x = x(:);
+
+  s = norm (x) * (sign (x(1)) + (x(1) == 0)); # Modification for sign (0) == 1.
+  v = x;
+  if (s == 0)
+    ## Quit if x is the zero vector.
+    beta = 1;
+  else
+    v(1) = v(1) + s;
+    beta = 1/(s'*v(1));                       # NB the conjugated s.
+    ##  beta = 1/(abs (s) * (abs (s) +abs(x(1)) would guarantee beta real.
+    ##  But beta as above can be non-real (due to rounding) only when x is complex.
+  endif
+endfunction
+
+function A = invhess (x, y)
+  ## INVHESS  Inverse of an upper Hessenberg matrix.
+  ##          INVHESS(X, Y), where X is an N-vector and Y an N-1 vector,
+  ##          is the matrix whose lower triangle agrees with that of
+  ##          ONES(N,1)*X' and whose strict upper triangle agrees with
+  ##          that of [1 Y]*ONES(1,N).
+  ##          The matrix is nonsingular if X(1) ~= 0 and X(i+1) ~= Y(i)
+  ##          for all i, and its inverse is an upper Hessenberg matrix.
+  ##          If Y is omitted it defaults to -X(1:N-1).
+  ##          Special case: if X is a scalar INVHESS(X) is the same as
+  ##          INVHESS(1:X).
+  ##
+  ##          References:
+  ##          F.N. Valvi and V.S. Geroyannis, Analytic inverses and
+  ##              determinants for a class of matrices, IMA Journal of Numerical
+  ##              Analysis, 7 (1987), pp. 123-128.
+  ##          W.-L. Cao and W.J. Stewart, A note on inverses of Hessenberg-like
+  ##              matrices, Linear Algebra and Appl., 76 (1986), pp. 233-240.
+  ##          Y. Ikebe, On inverses of Hessenberg matrices, Linear Algebra and
+  ##              Appl., 24 (1979), pp. 93-97.
+  ##          P. Rozsa, On the inverse of band matrices, Integral Equations and
+  ##              Operator Theory, 10 (1987), pp. 82-95.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for invhess matrix.");
+  elseif (! isnumeric (x))
+    error ("gallery: X must be numeric for invhess matrix.");
+  endif
+
+  if (isscalar (x) && fix (x) == x)
+    n = x;
+    x = 1:n;
+  elseif (! isscalar (x) && isvector (x))
+    n = numel (n);
+  else
+    error ("gallery: X must be an integer scalar, or a vector for invhess matrix.");
+  endif
+
+  if (nargin < 2)
+    y = -x(1:end-1);
+  elseif (! isvector (y) || numel (y) != numel (x) -1)
+    error ("gallery: Y must be a vector of length -1 than X for invhess matrix.");
+  endif
+
+  x = x(:);
+  y = y(:);
+
+  ##  On next line, z = x'; A = z(ones(n,1),:) would be more efficient.
+  A = ones (n, 1) * x';
+  for j = 2:n
+    A(1:j-1,j) = y(1:j-1);
+  endfor
+endfunction
+
+function A = invol (n)
+  ## INVOL   An involutory matrix.
+  ##         A = INVOL(N) is an N-by-N involutory (A*A = EYE(N)) and
+  ##         ill-conditioned matrix.
+  ##         It is a diagonally scaled version of HILB(N).
+  ##         NB: B = (EYE(N)-A)/2 and B = (EYE(N)+A)/2 are idempotent (B*B = B).
+  ##
+  ##         Reference:
+  ##         A.S. Householder and J.A. Carpenter, The singular values
+  ##         of involutory and of idempotent matrices, Numer. Math. 5 (1963),
+  ##         pp. 234-237.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for invol matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for invol matrix.");
+  endif
+
+  A = hilb (n);
+
+  d = -n;
+  A(:, 1) = d * A(:, 1);
+
+  for i = 1:n-1
+    d = -(n+i)*(n-i)*d/(i*i);
+    A(i+1,:) = d * A(i+1,:);
+  endfor
+endfunction
+
+function [A, detA] = ipjfact (n, k = 0)
+  ## IPJFACT   A Hankel matrix with factorial elements.
+  ##           A = IPJFACT(N, K) is the matrix with
+  ##                     A(i,j) = (i+j)!    (K = 0, default)
+  ##                     A(i,j) = 1/(i+j)!  (K = 1)
+  ##           Both are Hankel matrices.
+  ##           The determinant and inverse are known explicitly.
+  ##           If a second output argument is present, d = DET(A) is returned:
+  ##           [A, d] = IPJFACT(N, K);
+  ##
+  ##           Suggested by P. R. Graves-Morris.
+  ## 
+  ##           Reference:
+  ##           M.J.C. Gover, The explicit inverse of factorial Hankel matrices,
+  ##           Dept. of Mathematics, University of Bradford, 1993.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for ipjfact matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for ipjfact matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for ipjfact matrix.");
+  endif
+
+  c = cumprod (2:n+1);
+  d = cumprod (n+1:2*n) * c(n-1);
+
+  A = hankel (c, d);
+
+  switch (k)
+    case (0), # do nothing
+    case (1), A = ones (n) ./ A;
+    otherwise
+      error ("gallery: K must have a value of 0 or 1 for ipjfact matrix.");
+  endswitch
+
+  if (nargout == 2)
+    d = 1;
+
+    if (k == 0)
+      for i = 1:n-1
+        d = d * prod (1:i+1) * prod (1:n-i);
+      endfor
+      d = d * prod (1:n+1);
+
+    elseif (k == 1)
+      for i = 0:n-1
+        d = d * prod (1:i) / prod (1:n+1+i);
+      endfor
+      if (rem (n*(n-1)/2, 2))
+        d = -d;
+      endif
+
+    else
+      error ("gallery: K must have a value of 0 or 1 for ipjfact matrix.");
+    endif
+
+    detA = d;
+  endif
+endfunction
+
+function J = jordbloc (n, lambda = 1)
+  ## JORDBLOC  Jordan block.
+  ##           JORDBLOC(N, LAMBDA) is the N-by-N Jordan block with eigenvalue
+  ##           LAMBDA.  LAMBDA = 1 is the default.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for jordbloc matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for jordbloc matrix.");
+  elseif (! isnumeric (lambda) || ! isscalar (lambda))
+    error ("gallery: LAMBDA must be a numeric scalar for jordbloc matrix.");
+  endif
+
+  J = lambda * eye (n) + diag (ones (n-1, 1), 1);
+endfunction
+
+function U = kahan (n, theta = 1.2, pert = 25)
+  ## KAHAN  Kahan matrix - upper trapezoidal.
+  ##        KAHAN(N, THETA) is an upper trapezoidal matrix
+  ##        that has some interesting properties regarding estimation of
+  ##        condition and rank.
+  ##        The matrix is N-by-N unless N is a 2-vector, in which case it
+  ##        is N(1)-by-N(2).
+  ##        The parameter THETA defaults to 1.2.
+  ##        The useful range of THETA is 0 < THETA < PI.
+  ##
+  ##        To ensure that the QR factorization with column pivoting does not
+  ##        interchange columns in the presence of rounding errors, the diagonal
+  ##        is perturbed by PERT*EPS*diag( [N:-1:1] ).
+  ##        The default is PERT = 25, which ensures no interchanges for KAHAN(N)
+  ##        up to at least N = 90 in IEEE arithmetic.
+  ##        KAHAN(N, THETA, PERT) uses the given value of PERT.
+  ##
+  ##        The inverse of KAHAN(N, THETA) is known explicitly: see
+  ##        Higham (1987, p. 588), for example.
+  ##        The diagonal perturbation was suggested by Christian Bischof.
+  ##
+  ##        References:
+  ##        W. Kahan, Numerical linear algebra, Canadian Math. Bulletin,
+  ##           9 (1966), pp. 757-801.
+  ##        N.J. Higham, A survey of condition number estimation for
+  ##           triangular matrices, SIAM Review, 29 (1987), pp. 575-596.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for kahan matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]) || fix (n) != n)
+    error ("gallery: N must be a 1 or 2 element integer for kahan matrix.");
+  elseif (! isnumeric (theta) || ! isscalar (theta))
+    error ("gallery: THETA must be a numeric scalar for kahan matrix.");
+  elseif (! isnumeric (pert) || ! isscalar (pert))
+    error ("gallery: PERT must be a numeric scalar for kahan matrix.");
+  endif
+
+  ## Parameter n specifies dimension: r-by-n
+  r = n(1);
+  n = n(end);
+
+  s = sin (theta);
+  c = cos (theta);
+
+  U = eye (n) - c * triu (ones (n), 1);
+  U = diag (s.^[0:n-1]) * U + pert*eps* diag ([n:-1:1]);
+  if (r > n)
+    U(r,n) = 0;     # Extend to an r-by-n matrix
+  else
+    U = U(1:r,:);   # Reduce to an r-by-n matrix
+  endif
+endfunction
+
+function A = kms (n, rho = 0.5)
+  ## KMS   Kac-Murdock-Szego Toeplitz matrix.
+  ##       A = KMS(N, RHO) is the N-by-N Kac-Murdock-Szego Toeplitz matrix with
+  ##       A(i,j) = RHO^(ABS((i-j))) (for real RHO).
+  ##       If RHO is complex, then the same formula holds except that elements
+  ##       below the diagonal are conjugated.
+  ##       RHO defaults to 0.5.
+  ##       Properties:
+  ##          A has an LDL' factorization with
+  ##                   L = INV(TRIW(N,-RHO,1)'),
+  ##                   D(i,i) = (1-ABS(RHO)^2)*EYE(N) except D(1,1) = 1.
+  ##          A is positive definite if and only if 0 < ABS(RHO) < 1.
+  ##          INV(A) is tridiagonal.
+  ##
+  ##        Reference:
+  ##        W.F. Trench, Numerical solution of the eigenvalue problem
+  ##        for Hermitian Toeplitz matrices, SIAM J. Matrix Analysis and Appl.,
+  ##        10 (1989), pp. 135-146 (and see the references therein).
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for lauchli matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error("gallery: N must be an integer for lauchli matrix.")
+  elseif (! isscalar (mu))
+    error("gallery: MU must be a scalar for lauchli matrix.")
+  endif
+
+  A = (1:n)'*ones(1,n);
+  A = abs(A - A');
+  A = rho .^ A;
+  if imag(rho)
+    A = conj(tril(A,-1)) + triu(A);
+  endif
+endfunction
+
+function B = krylov (A, x, j)
+  ## KRYLOV    Krylov matrix.
+  ##           KRYLOV(A, x, j) is the Krylov matrix
+  ##                [x, Ax, A^2x, ..., A^(j-1)x],
+  ##           where A is an n-by-n matrix and x is an n-vector.
+  ##           Defaults: x = ONES(n,1), j = n.
+  ##           KRYLOV(n) is the same as KRYLOV(RANDN(n)).
+  ##
+  ##           Reference:
+  ##           G.H. Golub and C.F. Van Loan, Matrix Computations, second edition,
+  ##           Johns Hopkins University Press, Baltimore, Maryland, 1989, p. 369.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for krylov matrix.");
+  elseif (! isnumeric (A) || ! issquare (A) || ndims (A) != 2)
+    error ("gallery: A must be a square 2D matrix for krylov matrix.");
+  endif
+
+  n = length (A);
+  if (isscalar (A))
+    n = A;
+    A = randn (n);
+  endif
+
+  if (nargin < 2)
+    x = ones (n, 1);
+  elseif (! isvector (x) || numel (x) != n)
+    error ("gallery: X must be a vector of length equal to A for krylov matrix.");
+  endif
+
+  if (nargin < 3)
+    j = n;
+  elseif (! isnumeric (j) || ! isscalar (j) || fix (j) != j)
+    error ("gallery: J must be an integer for krylov matrix.");
+  endif
+
+  B = ones (n, j);
+  B(:,1) = x(:);
+  for i = 2:j
+    B(:,i) = A*B(:,i-1);
+  endfor
+endfunction
+
+function A = lauchli (n, mu = sqrt (eps))
+  ## LAUCHLI   Lauchli matrix - rectangular.
+  ##           LAUCHLI(N, MU) is the (N+1)-by-N matrix [ONES(1,N); MU*EYE(N))].
+  ##           It is a well-known example in least squares and other problems
+  ##           that indicates the dangers of forming A'*A.
+  ##           MU defaults to SQRT(EPS).
+  ##
+  ##           Reference:
+  ##           P. Lauchli, Jordan-Elimination und Ausgleichung nach
+  ##           kleinsten Quadraten, Numer. Math, 3 (1961), pp. 226-240.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for lauchli matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for lauchli matrix.");
+  elseif (! isscalar (mu))
+    error ("gallery: MU must be a scalar for lauchli matrix.");
+  endif
+
+  A = [ones(1, n)
+       mu*eye(n) ];
+endfunction
+
+function A = lehmer (n)
+  ## LEHMER  Lehmer matrix - symmetric positive definite.
+  ##         A = LEHMER(N) is the symmetric positive definite N-by-N matrix with
+  ##                          A(i,j) = i/j for j >= i.
+  ##         A is totally nonnegative.  INV(A) is tridiagonal, and explicit
+  ##         formulas are known for its entries.
+  ##         N <= COND(A) <= 4*N*N.
+  ##
+  ##         References:
+  ##         M. Newman and J. Todd, The evaluation of matrix inversion
+  ##            programs, J. Soc. Indust. Appl. Math., 6 (1958), pp. 466-476.
+  ##         Solutions to problem E710 (proposed by D.H. Lehmer): The inverse
+  ##            of a matrix, Amer. Math. Monthly, 53 (1946), pp. 534-535.
+  ##         J. Todd, Basic Numerical Mathematics, Vol. 2: Numerical Algebra,
+  ##            Birkhauser, Basel, and Academic Press, New York, 1977, p. 154.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for lehmer matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for lehmer matrix.");
+  endif
+
+  A = ones (n, 1) * (1:n);
+  A = A./A';
+  A = tril (A) + tril (A, -1)';
+endfunction
+
+function T = lesp (n)
+  ## LESP   A tridiagonal matrix with real, sensitive eigenvalues.
+  ##        LESP(N) is an N-by-N matrix whose eigenvalues are real and smoothly
+  ##        distributed in the interval approximately [-2*N-3.5, -4.5].
+  ##        The sensitivities of the eigenvalues increase exponentially as
+  ##        the eigenvalues grow more negative.
+  ##        The matrix is similar to the symmetric tridiagonal matrix with
+  ##        the same diagonal entries and with off-diagonal entries 1,
+  ##        via a similarity transformation with D = diag(1!,2!,...,N!).
+  ##
+  ##        References:
+  ##        H.W.J. Lenferink and M.N. Spijker, On the use of stability regions in
+  ##             the numerical analysis of initial value problems,
+  ##             Math. Comp., 57 (1991), pp. 221-237.
+  ##        L.N. Trefethen, Pseudospectra of matrices, in Numerical Analysis 1991,
+  ##             Proceedings of the 14th Dundee Conference,
+  ##             D.F. Griffiths and G.A. Watson, eds, Pitman Research Notes in
+  ##             Mathematics, volume 260, Longman Scientific and Technical, Essex,
+  ##             UK, 1992, pp. 234-266.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for lesp matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for lesp matrix.");
+  endif
+
+  x = 2:n;
+  T = full (tridiag (ones (size (x)) ./x, -(2*[x n+1]+1), x));
+endfunction
+
+function A = lotkin (n)
+  ## LOTKIN  Lotkin matrix.
+  ##         A = LOTKIN(N) is the Hilbert matrix with its first row altered to
+  ##         all ones.  A is unsymmetric, ill-conditioned, and has many negative
+  ##         eigenvalues of small magnitude.
+  ##         The inverse has integer entries and is known explicitly.
+  ##
+  ##         Reference:
+  ##         M. Lotkin, A set of test matrices, MTAC, 9 (1955), pp. 153-161.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for lotkin matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for lotkin matrix.");
+  endif
+
+  A = hilb (n);
+  A(1,:) = ones (1, n);
+endfunction
+
+function A = minij (n)
+  ## MINIJ   Symmetric positive definite matrix MIN(i,j).
+  ##         A = MINIJ(N) is the N-by-N symmetric positive definite matrix with
+  ##         A(i,j) = MIN(i,j).
+  ##         Properties, variations:
+  ##         INV(A) is tridiagonal: it is minus the second difference matrix
+  ##                     except its (N,N) element is 1.
+  ##         2*A-ONES(N) (Givens' matrix) has tridiagonal inverse and
+  ##                     eigenvalues .5*sec^2([2r-1)PI/4N], r=1:N.
+  ##         (N+1)*ONES(N)-A also has a tridiagonal inverse.
+  ##
+  ##         References:
+  ##         J. Todd, Basic Numerical Mathematics, Vol. 2: Numerical Algebra,
+  ##            Birkhauser, Basel, and Academic Press, New York, 1977, p. 158.
+  ##         D.E. Rutherford, Some continuant determinants arising in physics and
+  ##            chemistry---II, Proc. Royal Soc. Edin., 63, A (1952), pp. 232-241.
+  ##            (For the eigenvalues of Givens' matrix.)
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for minij matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for minij matrix.");
+  endif
+
+  A = min (ones (n, 1) * (1:n), (1:n)' * ones (1, n));
+endfunction
+
+function A = moler (n, alpha = -1)
+  ## MOLER   Moler matrix - symmetric positive definite.
+  ##         A = MOLER(N, ALPHA) is the symmetric positive definite N-by-N matrix
+  ##         U'*U where U = TRIW(N, ALPHA).
+  ##         For ALPHA = -1 (the default) A(i,j) = MIN(i,j)-2, A(i,i) = i.
+  ##         A has one small eigenvalue.
+  ##
+  ##         Nash (1990) attributes the ALPHA = -1 matrix to Moler.
+  ##
+  ##         Reference:
+  ##         J.C. Nash, Compact Numerical Methods for Computers: Linear
+  ##         Algebra and Function Minimisation, second edition, Adam Hilger,
+  ##         Bristol, 1990 (Appendix 1).
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for moler matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for moler matrix.");
+  elseif (! isscalar (alpha))
+    error ("gallery: ALPHA must be a scalar for moler matrix.");
+  endif
+
+  A = triw (n, alpha)' * triw (n, alpha);
+endfunction
+
+function [A, T] = neumann (n)
+  ## NEUMANN  Singular matrix from the discrete Neumann problem (sparse).
+  ##          NEUMANN(N) is the singular, row diagonally dominant matrix resulting
+  ##          from discretizing the Neumann problem with the usual five point
+  ##          operator on a regular mesh.
+  ##          It has a one-dimensional null space with null vector ONES(N,1).
+  ##          The dimension N should be a perfect square, or else a 2-vector,
+  ##          in which case the dimension of the matrix is N(1)*N(2).
+  ##
+  ##          Reference:
+  ##          R.J. Plemmons, Regular splittings and the discrete Neumann
+  ##          problem, Numer. Math., 25 (1976), pp. 153-161.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for neumann matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]) || fix (n) != n)
+    error ("gallery: N must be a 1 or 2 element integer for neumann matrix.");
+  endif
+
+  if (isscalar (n))
+    m = sqrt (n);
+    if (m^2 != n)
+      error ("gallery: N must be a perfect square for neumann matrix.");
+    endif
+    n(1) = m;
+    n(2) = m;
+  endif
+
+  T = tridiag (n(1), -1, 2, -1);
+  T(1,2) = -2;
+  T(n(1),n(1)-1) = -2;
+
+  A = kron (T, eye (n(2))) + kron (eye (n(2)), T);
+endfunction
+
+function Q = orthog (n, k = 1)
+  ## ORTHOG Orthogonal and nearly orthogonal matrices.
+  ##        Q = ORTHOG(N, K) selects the K'th type of matrix of order N.
+  ##        K > 0 for exactly orthogonal matrices, K < 0 for diagonal scalings of
+  ##        orthogonal matrices.
+  ##        Available types: (K = 1 is the default)
+  ##        K = 1:  Q(i,j) = SQRT(2/(n+1)) * SIN( i*j*PI/(n+1) )
+  ##                Symmetric eigenvector matrix for second difference matrix.
+  ##        K = 2:  Q(i,j) = 2/SQRT(2*n+1)) * SIN( 2*i*j*PI/(2*n+1) )
+  ##                Symmetric.
+  ##        K = 3:  Q(r,s) = EXP(2*PI*i*(r-1)*(s-1)/n) / SQRT(n)  (i=SQRT(-1))
+  ##                Unitary, the Fourier matrix.  Q^4 is the identity.
+  ##                This is essentially the same matrix as FFT(EYE(N))/SQRT(N)!
+  ##        K = 4:  Helmert matrix: a permutation of a lower Hessenberg matrix,
+  ##                whose first row is ONES(1:N)/SQRT(N).
+  ##        K = 5:  Q(i,j) = SIN( 2*PI*(i-1)*(j-1)/n ) + COS( 2*PI*(i-1)*(j-1)/n ).
+  ##                Symmetric matrix arising in the Hartley transform.
+  ##        K = -1: Q(i,j) = COS( (i-1)*(j-1)*PI/(n-1) )
+  ##                Chebyshev Vandermonde-like matrix, based on extrema of T(n-1).
+  ##        K = -2: Q(i,j) = COS( (i-1)*(j-1/2)*PI/n) )
+  ##                Chebyshev Vandermonde-like matrix, based on zeros of T(n).
+  ##
+  ##        References:
+  ##        N.J. Higham and D.J. Higham, Large growth factors in Gaussian
+  ##             elimination with pivoting, SIAM J. Matrix Analysis and  Appl.,
+  ##             10 (1989), pp. 155-164.
+  ##        P. Morton, On the eigenvectors of Schur's matrix, J. Number Theory,
+  ##             12 (1980), pp. 122-127. (Re. ORTHOG(N, 3))
+  ##        H.O. Lancaster, The Helmert Matrices, Amer. Math. Monthly, 72 (1965),
+  ##             pp. 4-12.
+  ##        D. Bini and P. Favati, On a matrix algebra related to the discrete
+  ##             Hartley transform, SIAM J. Matrix Anal. Appl., 14 (1993),
+  ##             pp. 500-507.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for orthog matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for orthog matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for orthog matrix.");
+  endif
+
+  switch (k)
+    case (1)
+      ## E'vectors second difference matrix
+      m = (1:n)'*(1:n) * (pi/(n+1));
+      Q = sin (m) * sqrt (2/(n+1));
+
+    case (2)
+      m = (1:n)'*(1:n) * (2*pi/(2*n+1));
+      Q = sin (m) * (2/ sqrt (2*n+1));
+
+    case (3)
+      ## Vandermonde based on roots of unity
+      m = 0:n-1;
+      Q = exp (m'*m*2*pi* sqrt (-1) / n) / sqrt (n);
+
+    case (4)
+      ## Helmert matrix
+      Q = tril (ones (n));
+      Q(1,2:n) = ones (1, n-1);
+      for i = 2:n
+        Q(i,i) = -(i-1);
+      end
+      Q = diag (sqrt ([n 1:n-1] .* [1:n])) \ Q;
+
+    case (5)
+      ## Hartley matrix
+      m = (0:n-1)'*(0:n-1) * (2*pi/n);
+      Q = (cos (m) + sin (m)) / sqrt (n);
+
+    case (-1)
+      ##  extrema of T(n-1)
+      m = (0:n-1)'*(0:n-1) * (pi/(n-1));
+      Q = cos (m);
+
+    case (-2)
+      ## zeros of T(n)
+      m = (0:n-1)'*(.5:n-.5) * (pi/n);
+      Q = cos (m);
+
+    otherwise
+      error ("gallery: unknown K `%d' for orthog matrix.", k);
+  endswitch
+endfunction
+
+function A = parter (n)
+  ## PARTER    Parter matrix - a Toeplitz matrix with singular values near PI.
+  ##           PARTER(N) is the matrix with (i,j) element 1/(i-j+0.5).
+  ##           It is a Cauchy matrix and a Toeplitz matrix.
+  ##
+  ##           At the Second SIAM Conference on Linear Algebra, Raleigh, N.C.,
+  ##           1985, Cleve Moler noted that most of the singular values of
+  ##           PARTER(N) are very close to PI.  An explanation of the phenomenon
+  ##           was given by Parter; see also the paper by Tyrtyshnikov.
+  ## 
+  ##           References:
+  ##           The MathWorks Newsletter, Volume 1, Issue 1, March 1986, page 2.
+  ##           S.V. Parter, On the distribution of the singular values of Toeplitz
+  ##                matrices, Linear Algebra and Appl., 80 (1986), pp. 115-130.
+  ##           E.E. Tyrtyshnikov, Cauchy-Toeplitz matrices and some applications,
+  ##                Linear Algebra and Appl., 149 (1991), pp. 1-18.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for parter matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for parter matrix.");
+  endif
+
+  A = cauchy ((1:n) + 0.5, -(1:n));
+endfunction
+
+function P = pei (n, alpha = 1)
+  ## PEI    Pei matrix.
+  ##        PEI(N, ALPHA), where ALPHA is a scalar, is the symmetric matrix
+  ##        ALPHA*EYE(N) + ONES(N).
+  ##        If ALPHA is omitted then ALPHA = 1 is used.
+  ##        The matrix is singular for ALPHA = 0, -N.
+  ##
+  ##        Reference:
+  ##        M.L. Pei, A test matrix for inversion procedures,
+  ##        Comm. ACM, 5 (1962), p. 508.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for pei matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for pei matrix.");
+  elseif (! isnumeric (w) || ! isscalar (w))
+    error ("gallery: ALPHA must be a scalar for pei matrix.");
+  endif
+
+  P = alpha * eye (n) + ones (n);
+endfunction
+
+function A = poisson (n)
+  ## POISSON   Block tridiagonal matrix from Poisson's equation (sparse).
+  ##           POISSON(N) is the block tridiagonal matrix of order N^2
+  ##           resulting from discretizing Poisson's equation with the
+  ##           5-point operator on an N-by-N mesh.
+  ##
+  ##           Reference:
+  ##           G.H. Golub and C.F. Van Loan, Matrix Computations, second edition,
+  ##           Johns Hopkins University Press, Baltimore, Maryland, 1989
+  ##           (Section 4.5.4).
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for poisson matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for poisson matrix.");
+  endif
+
+  S = tridiag (n, -1, 2, -1);
+  I = speye (n);
+  A = kron (I, S) + kron (S, I);
+endfunction
+
+function A = prolate (n, w = 0.25)
+  ## PROLATE   Prolate matrix - symmetric, ill-conditioned Toeplitz matrix.
+  ##           A = PROLATE(N, W) is the N-by-N prolate matrix with parameter W.
+  ##           It is a symmetric Toeplitz matrix.
+  ##           If 0 < W < 0.5 then
+  ##              - A is positive definite
+  ##              - the eigenvalues of A are distinct, lie in (0, 1), and
+  ##                tend to cluster around 0 and 1.
+  ##           W defaults to 0.25.
+  ##
+  ##           Reference:
+  ##           J.M. Varah. The Prolate matrix. Linear Algebra and Appl.,
+  ##           187:269--278, 1993.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for prolate matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for prolate matrix.");
+  elseif (! isnumeric (w) || ! isscalar (w))
+    error ("gallery: W must be a scalar for prolate matrix.");
+  endif
+
+  a      = zeros (n, 1);
+  a(1)   = 2*w;
+  a(2:n) = sin (2*pi*w*(1:n-1)) ./ (pi*(1:n-1));
+
+  A = toeplitz(a);
+endfunction
+
+function H = randhess (x)
+  ## NOTE: this function was named ohess in the original Test Matrix Toolbox
+  ## RANDHESS  Random, orthogonal upper Hessenberg matrix.
+  ##        H = RANDHESS(N) is an N-by-N real, random, orthogonal
+  ##        upper Hessenberg matrix.
+  ##        Alternatively, H = RANDHESS(X), where X is an arbitrary real
+  ##        N-vector (N > 1) constructs H non-randomly using the elements
+  ##        of X as parameters.
+  ##        In both cases H is constructed via a product of N-1 Givens rotations.
+  ##
+  ##        Note: See Gragg (1986) for how to represent an N-by-N (complex)
+  ##        unitary Hessenberg matrix with positive subdiagonal elements in terms
+  ##        of 2N-1 real parameters (the Schur parametrization).
+  ##        This M-file handles the real case only and is intended simply as a
+  ##        convenient way to generate random or non-random orthogonal Hessenberg
+  ##        matrices.
+  ## 
+  ##        Reference:
+  ##        W.B. Gragg, The QR algorithm for unitary Hessenberg matrices,
+  ##        J. Comp. Appl. Math., 16 (1986), pp. 1-8.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for randhess matrix.");
+  elseif (! isnumeric (x) || ! isreal (x))
+    error ("gallery: N or X must be numeric real values for randhess matrix.");
+  endif
+
+  if (isscalar (x))
+    n = x;
+    x = rand (n-1, 1) * 2*pi;
+    H = eye (n);
+    H(n,n) = sign (randn);
+  elseif (isvector (x))
+    n = numel (x);
+    H = eye (n);
+    H(n,n) = sign (x(n)) + (x(n) == 0); # Second term ensures H(n,n) nonzero.
+  else
+    error ("gallery: N or X must be a scalar or a vector for randhess matrix.");
+  endif
+
+  for i = n:-1:2
+    ## Apply Givens rotation through angle x(i-1).
+    theta = x(i-1);
+    c = cos (theta);
+    s = sin (theta);
+    H([i-1 i], :) = [ c*H(i-1,:)+s*H(i,:)
+                     -s*H(i-1,:)+c*H(i,:) ];
+  endfor
+endfunction
+
+function A = rando (n, k = 1)
+  ## RANDO   Random matrix with elements -1, 0 or 1.
+  ##         A = RANDO(N, K) is a random N-by-N matrix with elements from
+  ##         one of the following discrete distributions (default K = 1):
+  ##           K = 1:  A(i,j) =  0 or 1    with equal probability,
+  ##           K = 2:  A(i,j) = -1 or 1    with equal probability,
+  ##           K = 3:  A(i,j) = -1, 0 or 1 with equal probability.
+  ##         N may be a 2-vector, in which case the matrix is N(1)-by-N(2).
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for rando matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]) || fix (n) != n)
+    error ("gallery: N must be an integer for rando matrix.");
+  elseif (! isnumeric (k) || ! isscalar (k))
+    error ("gallery: K must be a numeric scalar for smoke matrix.");
+  endif
+
+  ## Parameter n specifies dimension: m-by-n.
+  m = n(1);
+  n = n(end);
+
+  switch (k)
+    case (1), A =   floor (  rand(m, n) + 0.5);     # {0, 1}
+    case (2), A = 2*floor (  rand(m, n) + 0.5) -1;  # {-1, 1}
+    case (3), A =   round (3*rand(m, n) - 1.5);     # {-1, 0, 1}
+    otherwise
+      error ("gallery: unknown K `%d' for smoke matrix.", k);
+  endswitch
+
+endfunction
+
+function A = randsvd (n, kappa = sqrt (1/eps), mode = 3, kl = n-1, ku = kl)
+  ## RANDSVD  Random matrix with pre-assigned singular values.
+  ##       RANDSVD(N, KAPPA, MODE, KL, KU) is a (banded) random matrix of order N
+  ##       with COND(A) = KAPPA and singular values from the distribution MODE.
+  ##       N may be a 2-vector, in which case the matrix is N(1)-by-N(2).
+  ##       Available types:
+  ##              MODE = 1:   one large singular value,
+  ##              MODE = 2:   one small singular value,
+  ##              MODE = 3:   geometrically distributed singular values,
+  ##              MODE = 4:   arithmetically distributed singular values,
+  ##              MODE = 5:   random singular values with unif. dist. logarithm.
+  ##       If omitted, MODE defaults to 3, and KAPPA defaults to SQRT(1/EPS).
+  ##       If MODE < 0 then the effect is as for ABS(MODE) except that in the
+  ##       original matrix of singular values the order of the diagonal entries
+  ##       is reversed: small to large instead of large to small.
+  ##       KL and KU are the lower and upper bandwidths respectively; if they
+  ##       are omitted a full matrix is produced.
+  ##       If only KL is present, KU defaults to KL.
+  ##       Special case: if KAPPA < 0 then a random full symmetric positive
+  ##                     definite matrix is produced with COND(A) = -KAPPA and
+  ##                     eigenvalues distributed according to MODE.
+  ##                     KL and KU, if present, are ignored.
+  ##
+  ##       Reference:
+  ##       N.J. Higham, Accuracy and Stability of Numerical Algorithms,
+  ##          Society for Industrial and Applied Mathematics, Philadelphia, PA,
+  ##          USA, 1996; sec. 26.3.
+  ##
+  ##       This routine is similar to the more comprehensive Fortran routine xLATMS
+  ##       in the following reference:
+  ##       J.W. Demmel and A. McKenney, A test matrix generation suite,
+  ##       LAPACK Working Note #9, Courant Institute of Mathematical Sciences,
+  ##       New York, 1989.
+
+  if (nargin < 1 || nargin > 5)
+    error ("gallery: 1 to 5 arguments are required for randsvd matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]) || fix (n) != n)
+    error ("gallery: N must be a 1 or 2 element integer vector for randsvd matrix.");
+  elseif (! isnumeric (kappa) || ! isscalar (kappa))
+    error ("gallery: KAPPA must be a numeric scalar for randsvd matrix.");
+  elseif (abs (kappa) < 1)
+    error ("gallery: KAPPA must larger than or equal to 1 for randsvd matrix.");
+  elseif (! isnumeric (mode) || ! isscalar (mode))
+    error ("gallery: MODE must be a numeric scalar for randsvd matrix.");
+  elseif (! isnumeric (kl) || ! isscalar (kl))
+    error ("gallery: KL must be a numeric scalar for randsvd matrix.");
+  elseif (! isnumeric (ku) || ! isscalar (ku))
+    error ("gallery: KU must be a numeric scalar for randsvd matrix.");
+  endif
+
+  posdef = 0;
+  if (kappa < 0)
+    posdef = 1;
+    kappa  = -kappa;
+  endif
+
+  ## Parameter n specifies dimension: m-by-n.
+  m = n(1);
+  n = n(end);
+  p = min ([m n]);
+
+  ## If A will be a vector
+  if (p == 1)
+    A = randn (m, n);
+    A = A / norm (A);
+    return
+  end
+
+  ##  Set up vector sigma of singular values.
+  switch (abs (mode))
+    case (1)
+      sigma = ones (p, 1) ./ kappa;
+      sigma(1) = 1;
+    case (2)
+      sigma = ones (p, 1);
+      sigma(p) = 1 / kappa;
+    case (3)
+      factor = kappa^(-1/(p-1));
+      sigma  = factor.^[0:p-1];
+    case (4)
+      sigma = ones (p, 1) - (0:p-1)'/(p-1)*(1-1/kappa);
+    case (5)
+      ## In this case cond (A) <= kappa.
+      rand ("uniform");
+      sigma = exp (-rand (p, 1) * log (kappa));
+    otherwise
+      error ("gallery: unknown MODE `%d' for randsvd matrix.", mode);
+  endswitch
+
+  ##  Convert to diagonal matrix of singular values.
+  if (mode < 0)
+    sigma = sigma (p:-1:1);
+  end
+  sigma = diag (sigma);
+
+  if (posdef)
+    ## handle case where KAPPA was negative
+    Q = qmult (p);
+    A = Q' * sigma * Q;
+    A = (A + A') / 2;  # Ensure matrix is symmetric.
+    return
+  endif
+
+  if (m != n)
+    ## Expand to m-by-n diagonal matrix
+    sigma(m, n) = 0;
+  end
+
+  if (kl == 0 && ku == 0)
+    ## Diagonal matrix requested - nothing more to do.
+    A = sigma;
+  else
+    ##  A = U*sigma*V, where U, V are random orthogonal matrices from the
+    ##  Haar distribution.
+    A = qmult (sigma');
+    A = qmult (A');
+
+    if (kl < n-1 || ku < n-1)
+      ## Bandwidth reduction
+      A = bandred (A, kl, ku);
+    endif
+  endif
+endfunction
+
+function A = redheff (n)
+  ## REDHEFF    A (0,1) matrix of Redheffer associated with the Riemann hypothesis.
+  ##            A = REDHEFF(N) is an N-by-N matrix of 0s and 1s defined by
+  ##                A(i,j) = 1 if j = 1 or if i divides j,
+  ##                A(i,j) = 0 otherwise.
+  ##            It has N - FLOOR(LOG2(N)) - 1 eigenvalues equal to 1,
+  ##            a real eigenvalue (the spectral radius) approximately SQRT(N),
+  ##            a negative eigenvalue approximately -SQRT(N),
+  ##            and the remaining eigenvalues are provably ``small''.
+  ##            Barrett and Jarvis (1992) conjecture that
+  ##              ``the small eigenvalues all lie inside the unit circle
+  ##                ABS(Z) = 1'',
+  ##            and a proof of this conjecture, together with a proof that some
+  ##            eigenvalue tends to zero as N tends to infinity, would yield
+  ##            a new proof of the prime number theorem.
+  ##            The Riemann hypothesis is true if and only if
+  ##            DET(A) = O( N^(1/2+epsilon) ) for every epsilon > 0
+  ##                                              (`!' denotes factorial).
+  ##            See also RIEMANN.
+  ##
+  ##            Reference:
+  ##            W.W. Barrett and T.J. Jarvis,
+  ##            Spectral Properties of a Matrix of Redheffer,
+  ##            Linear Algebra and Appl., 162 (1992), pp. 673-683.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for redheff matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for redheff matrix.");
+  endif
+
+  i = (1:n)' * ones (1, n);
+  A = ! rem (i', i);
+  A(:,1) = ones (n, 1);
+endfunction
+
+function A = riemann (n)
+  ## RIEMANN    A matrix associated with the Riemann hypothesis.
+  ##            A = RIEMANN(N) is an N-by-N matrix for which the
+  ##            Riemann hypothesis is true if and only if
+  ##            DET(A) = O( N! N^(-1/2+epsilon) ) for every epsilon > 0
+  ##                                              (`!' denotes factorial).
+  ##            A = B(2:N+1, 2:N+1), where
+  ##            B(i,j) = i-1 if i divides j and -1 otherwise.
+  ##            Properties include, with M = N+1:
+  ##               Each eigenvalue E(i) satisfies ABS(E(i)) <= M - 1/M.
+  ##               i <= E(i) <= i+1 with at most M-SQRT(M) exceptions.
+  ##               All integers in the interval (M/3, M/2] are eigenvalues.
+  ##
+  ##            See also REDHEFF.
+  ##
+  ##            Reference:
+  ##            F. Roesler, Riemann's hypothesis as an eigenvalue problem,
+  ##            Linear Algebra and Appl., 81 (1986), pp. 153-198.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for riemann matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for riemann matrix.");
+  endif
+
+  n = n+1;
+  i = (2:n)' * ones (1, n-1);
+  j = i';
+  A = i .* (! rem (j, i)) - ones (n-1);
+endfunction
+
+function A = ris (n)
+  ## NOTE: this function was named dingdong in the original Test Matrix Toolbox
+  ## RIS       Dingdong matrix - a symmetric Hankel matrix.
+  ##           A = RIS(N) is the symmetric N-by-N Hankel matrix with
+  ##                          A(i,j) = 0.5/(N-i-j+1.5).
+  ##           The eigenvalues of A cluster around PI/2 and -PI/2.
+  ##
+  ##           Invented by F.N. Ris.
+  ##
+  ##           Reference:
+  ##           J.C. Nash, Compact Numerical Methods for Computers: Linear
+  ##           Algebra and Function Minimisation, second edition, Adam Hilger,
+  ##           Bristol, 1990 (Appendix 1).
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for ris matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for ris matrix.");
+  endif
+
+  p = -2*(1:n) + (n+1.5);
+  A = cauchy (p);
+endfunction
+
+function A = smoke (n, k = 0)
+  ## SMOKE     Smoke matrix - complex, with a `smoke ring' pseudospectrum.
+  ##           SMOKE(N) is an N-by-N matrix with 1s on the
+  ##           superdiagonal, 1 in the (N,1) position, and powers of
+  ##           roots of unity along the diagonal.
+  ##           SMOKE(N, 1) is the same except for a zero (N,1) element.
+  ##           The eigenvalues of SMOKE(N, 1) are the N'th roots of unity;
+  ##           those of SMOKE(N) are the N'th roots of unity times 2^(1/N).
+  ##
+  ##           Try PS(SMOKE(32)).  For SMOKE(N, 1) the pseudospectrum looks
+  ##           like a sausage folded back on itself.
+  ##           GERSH(SMOKE(N, 1)) is interesting.
+  ##
+  ##           Reference:
+  ##           L. Reichel and L.N. Trefethen, Eigenvalues and pseudo-eigenvalues of
+  ##           Toeplitz matrices, Linear Algebra and Appl., 162-164:153-185, 1992.
+
+  if (nargin < 1 || nargin > 2)
+    error ("gallery: 1 to 2 arguments are required for smoke matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be an integer for smoke matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n))
+    error ("gallery: K must be a numeric scalar for smoke matrix.");
+  endif
+
+  w = exp(2*pi*i/n);
+  A = diag( [w.^(1:n-1) 1] ) + diag(ones(n-1,1),1);
+
+  switch (k)
+    case (0), A(n,1) = 1;
+    case (1), # do nothing
+    otherwise,
+      error ("gallery: K must have a value of 0 or 1 for smoke matrix.");
+  endswitch
+endfunction
+
+function T = toeppd (n, m = n, w = rand (m,1), theta = rand (m,1))
+  ## NOTE: this function was named pdtoep in the original Test Matrix Toolbox
+  ## TOEPPD   Symmetric positive definite Toeplitz matrix.
+  ##          TOEPPD(N, M, W, THETA) is an N-by-N symmetric positive (semi-)
+  ##          definite (SPD) Toeplitz matrix, comprised of the sum of M rank 2
+  ##          (or, for certain THETA, rank 1) SPD Toeplitz matrices.
+  ##          Specifically,
+  ##                  T = W(1)*T(THETA(1)) + ... + W(M)*T(THETA(M)),
+  ##          where T(THETA(k)) has (i,j) element COS(2*PI*THETA(k)*(i-j)).
+  ##          Defaults: M = N, W = RAND(M,1), THETA = RAND(M,1).
+  ##
+  ##          Reference:
+  ##          G. Cybenko and C.F. Van Loan, Computing the minimum eigenvalue of
+  ##          a symmetric positive definite Toeplitz matrix, SIAM J. Sci. Stat.
+  ##          Comput., 7 (1986), pp. 123-131.
+
+  if (nargin < 1 || nargin > 4)
+    error ("gallery: 1 to 4 arguments are required for toeppd matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be a numeric integer for toeppd matrix.");
+  elseif (! isnumeric (m) || ! isscalar (m) || fix (m) != m)
+    error ("gallery: M must be a numeric integer for toeppd matrix.");
+  elseif (numel (w) != m || numel (theta) != m)
+    error ("gallery: W and THETA must be vectors of length M for toeppd matrix.");
+  endif
+
+  T = zeros (n);
+  E = 2*pi * ((1:n)' * ones (1, n) - ones (n, 1) * (1:n));
+
+  for i = 1:m
+    T = T + w(i) * cos (theta(i)*E);
+  endfor
+endfunction
+
+function P = toeppen (n, a = 1, b = -10, c = 0, d = 10, e = 1)
+  ## NOTE: this function was named pentoep in the original Test Matrix Toolbox
+  ## TOEPPEN   Pentadiagonal Toeplitz matrix (sparse).
+  ##           P = TOEPPEN(N, A, B, C, D, E) is the N-by-N pentadiagonal
+  ##           Toeplitz matrix with diagonals composed of the numbers
+  ##           A =: P(3,1), B =: P(2,1), C =: P(1,1), D =: P(1,2), E =: P(1,3).
+  ##           Default: (A,B,C,D,E) = (1,-10,0,10,1) (a matrix of Rutishauser).
+  ##                     This matrix has eigenvalues lying approximately on
+  ##                     the line segment 2*cos(2*t) + 20*i*sin(t).
+  ##
+  ##           Interesting plots are
+  ##           PS(FULL(TOEPPEN(32,0,1,0,0,1/4)))  - `triangle'
+  ##           PS(FULL(TOEPPEN(32,0,1/2,0,0,1)))  - `propeller'
+  ##           PS(FULL(TOEPPEN(32,0,1/2,1,1,1)))  - `fish'
+  ##
+  ##           References:
+  ##           R.M. Beam and R.F. Warming, The asymptotic spectra of
+  ##              banded Toeplitz and quasi-Toeplitz matrices, SIAM J. Sci.
+  ##              Comput. 14 (4), 1993, pp. 971-1006.
+  ##           H. Rutishauser, On test matrices, Programmation en Mathematiques
+  ##              Numeriques, Editions Centre Nat. Recherche Sci., Paris, 165,
+  ##              1966, pp. 349-365.
+
+  if (nargin < 1 || nargin > 6)
+    error ("gallery: 1 to 6 arguments are required for toeppen matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n) || fix (n) != n)
+    error ("gallery: N must be a numeric integer for toeppen matrix.");
+  elseif (any (cellfun (@(x) ! isnumeric (x) || ! isscalar (x), {a b c d e})))
+    error ("gallery: A, B, C, D and E must be numeric scalars for toeppen matrix.");
+  endif
+
+  P = spdiags ([a*ones(n,1) b*ones(n,1) c*ones(n,1) d*ones(n,1) e*ones(n,1)],
+                -2:2, n, n);
+endfunction
+
+function T = tridiag (n, x = -1, y = 2, z = -1)
+  ## TRIDIAG  Tridiagonal matrix (sparse).
+  ##          TRIDIAG(X, Y, Z) is the tridiagonal matrix with subdiagonal X,
+  ##          diagonal Y, and superdiagonal Z.
+  ##          X and Z must be vectors of dimension one less than Y.
+  ##          Alternatively TRIDIAG(N, C, D, E), where C, D, and E are all
+  ##          scalars, yields the Toeplitz tridiagonal matrix of order N
+  ##          with subdiagonal elements C, diagonal elements D, and superdiagonal
+  ##          elements E.   This matrix has eigenvalues (Todd 1977)
+  ##                   D + 2*SQRT(C*E)*COS(k*PI/(N+1)), k=1:N.
+  ##          TRIDIAG(N) is the same as TRIDIAG(N,-1,2,-1), which is
+  ##          a symmetric positive definite M-matrix (the negative of the
+  ##          second difference matrix).
+  ##
+  ##          References:
+  ##          J. Todd, Basic Numerical Mathematics, Vol. 2: Numerical Algebra,
+  ##            Birkhauser, Basel, and Academic Press, New York, 1977, p. 155.
+  ##          D.E. Rutherford, Some continuant determinants arising in physics and
+  ##            chemistry---II, Proc. Royal Soc. Edin., 63, A (1952), pp. 232-241.
+
+  if (nargin != 1 && nargin != 3 && nargin != 4)
+    error ("gallery: 1, 3, or 4 arguments are required for tridiag matrix.");
+  elseif (nargin == 3)
+    z = y;
+    y = x;
+    x = n;
+  endif
+
+  ## Force column vectors
+  x = x(:);
+  y = y(:);
+  z = z(:);
+
+  if (isscalar (x) && isscalar (y) && isscalar (z))
+    x *= ones (n-1, 1);
+    z *= ones (n-1, 1);
+    y *= ones (n,   1);
+  elseif (numel (y) != numel (x) + 1)
+    error ("gallery: X must have one element less than Y for tridiag matrix.");
+  elseif (numel (y) != numel (z) + 1)
+    error ("gallery: Z must have one element less than Y for tridiag matrix.");
+  endif
+
+  ##  T = diag (x, -1) + diag (y) + diag (z, 1);  # For non-sparse matrix.
+  n = numel (y);
+  T = spdiags ([[x;0] y [0;z]], -1:1, n, n);
+endfunction
+
+function t = triw (n, alpha = -1, k = -1)
+  ## TRIW   Upper triangular matrix discussed by Wilkinson and others.
+  ##        TRIW(N, ALPHA, K) is the upper triangular matrix with ones on
+  ##        the diagonal and ALPHAs on the first K >= 0 superdiagonals.
+  ##        N may be a 2-vector, in which case the matrix is N(1)-by-N(2) and
+  ##        upper trapezoidal.
+  ##        Defaults: ALPHA = -1,
+  ##                  K = N - 1     (full upper triangle).
+  ##        TRIW(N) is a matrix discussed by Kahan, Golub and Wilkinson.
+  ##
+  ##        Ostrowski (1954) shows that
+  ##          COND(TRIW(N,2)) = COT(PI/(4*N))^2,
+  ##        and for large ABS(ALPHA),
+  ##          COND(TRIW(N,ALPHA)) is approximately ABS(ALPHA)^N*SIN(PI/(4*N-2)).
+  ##
+  ##        Adding -2^(2-N) to the (N,1) element makes TRIW(N) singular,
+  ##        as does adding -2^(1-N) to all elements in the first column.
+  ##
+  ##        References:
+  ##        G.H. Golub and J.H. Wilkinson, Ill-conditioned eigensystems and the
+  ##           computation of the Jordan canonical form, SIAM Review,
+  ##           18(4), 1976, pp. 578-619.
+  ##        W. Kahan, Numerical linear algebra, Canadian Math. Bulletin,
+  ##           9 (1966), pp. 757-801.
+  ##        A.M. Ostrowski, On the spectrum of a one-parametric family of
+  ##           matrices, J. Reine Angew. Math., 193 (3/4), 1954, pp. 143-160.
+  ##        J.H. Wilkinson, Singular-value decomposition---basic aspects,
+  ##           in D.A.H. Jacobs, ed., Numerical Software---Needs and Availability,
+  ##           Academic Press, London, 1978, pp. 109-135.
+
+  if (nargin < 1 || nargin > 3)
+    error ("gallery: 1 to 3 arguments are required for triw matrix.");
+  elseif (! isnumeric (n) || all (numel (n) != [1 2]))
+    error ("gallery: N must be a 1 or 2 elements vector for triw matrix.");
+  elseif (! isscalar (alpha))
+    error ("gallery: ALPHA must be a scalar for triw matrix.");
+  elseif (! isscalar (k) || ! isnumeric (k) || fix (k) != k)
+    error ("gallery: K must be a numeric integer for triw matrix.");
+  endif
+
+  m = n(1);              # Parameter n specifies dimension: m-by-n.
+  n = n(end);
+
+  t = tril (eye (m, n) + alpha * triu (ones (m, n), 1), k);
+endfunction
+
+function A = wathen (nx, ny, k = 0)
+  ## # WATHEN returns the Wathen matrix.
+  ##
+  ##   Discussion:
+  ##
+  ##     The Wathen matrix is a finite element matrix which is sparse.
+  ##
+  ##     The entries of the matrix depend in part on a physical quantity
+  ##     related to density.  That density is here assigned random values between
+  ##     0 and 100.
+  ##
+  ##     A = WATHEN ( NX, NY ) is a sparse random N-by-N finite element matrix
+  ##     where N = 3*NX*NY + 2*NX + 2*NY + 1.
+  ##
+  ##     A is the consistent mass matrix for a regular NX-by-NY
+  ##     grid of 8-node (serendipity) elements in 2 space dimensions.
+  ##
+  ##     Here is an illustration for NX = 3, NX = 2:
+  ##
+  ##      23-24-25-26-27-28-29
+  ##       |     |     |     |
+  ##      19    20    21    22
+  ##       |     |     |     |
+  ##      12-13-14-15-16-17-18
+  ##       |     |     |     |
+  ##       8     9    10    11
+  ##       |     |     |     |
+  ##       1--2--3--4--5--6--7
+  ##
+  ##     For this example, the total number of nodes is, as expected,
+  ##
+  ##       N = 3 * 3 * 2 + 2 * 2 + 2 * 3 + 1 = 29.
+  ##
+  ##     A is symmetric positive definite for any (positive) values of
+  ##     the density, RHO(NX,NY), which is chosen randomly in this routine.
+  ##
+  ##     In particular, if D = DIAG(DIAG(A)), then
+  ##       0.25 <= EIG(INV(D)*A) <= 4.5
+  ##     for any positive integers NX and NY and any densities RHO(NX,NY).
+  ##
+  ##     A = WATHEN ( NX, NY, 1 ) returns the diagonally scaled matrix.
+  ##
+  ##   Modified:
+  ##
+  ##     17 September 2007
+  ##
+  ##   Author:
+  ##
+  ##     Nicholas Higham
+  ##
+  ##   Reference:
+  ##
+  ##     Nicholas Higham,
+  ##     Algorithm 694: A Collection of Test Matrices in MATLAB,
+  ##     ACM Transactions on Mathematical Software,
+  ##     Volume 17, Number 3, September 1991, pages 289-305.
+  ##
+  ##     Andrew Wathen,
+  ##     Realistic eigenvalue bounds for the Galerkin mass matrix,
+  ##     IMA Journal of Numerical Analysis,
+  ##     Volume 7, 1987, pages 449-457.
+  ##
+  ##   Parameters:
+  ##
+  ##     Input, integer NX, NY, the number of elements in the X and Y directions
+  ##     of the finite element grid.  NX and NY must each be at least 1.
+  ##
+  ##     Optional input, integer K, is used to request that the diagonally scaled
+  ##     version of the matrix be returned.  This happens if K is specified with
+  ##     the value 1.
+  ##
+  ##     Output, sparse real A(N,N), the matrix.  The dimension N is determined by
+  ##     NX and NY, as described above.  A is stored in the MATLAB sparse matrix
+  ##     format.
+
+  if (nargin < 2 || nargin > 3)
+    error ("gallery: 2 or 3 arguments are required for wathen matrix.");
+  elseif (! isnumeric (nx) || ! isscalar (nx) || nx < 1)
+    error ("gallery: NX must be a positive scalar for wathen matrix.");
+  elseif (! isnumeric (ny) || ! isscalar (ny) || ny < 1)
+    error ("gallery: NY must be a positive scalar for wathen matrix.");
+  elseif (! isscalar (k))
+    error ("gallery: K must be a scalar for wathen matrix.");
+  endif
+
+  e1 = [ 6  -6   2  -8
+        -6  32  -6  20
+         2  -6   6  -6
+        -8  20  -6  32 ];
+
+  e2 = [ 3  -8   2  -6
+        -8  16  -8  20
+         2  -8   3  -8
+        -6  20  -8  16 ];
+
+  e = [ e1  e2
+        e2' e1] / 45;
+
+  n = 3*nx*ny + 2*nx + 2*ny + 1;
+
+  A = sparse (n, n);
+
+  rho = 100 * rand (nx, ny);
+
+  for j = 1:ny
+    for i = 1:nx
+      ## 
+      ##   For the element (I,J), determine the indices of the 8 nodes.
+      ## 
+      nn(1) = 3*j*nx + 2*i + 2*j + 1;
+      nn(2) = nn(1) - 1;
+      nn(3) = nn(2) - 1;
+      nn(4) = (3*j - 1) * nx + 2*j + i - 1;
+      nn(5) = 3 * (j-1) * nx + 2*i + 2*j - 3;
+      nn(6) = nn(5) + 1;
+      nn(7) = nn(6) + 1;
+      nn(8) = nn(4) + 1;
+
+      em = e * rho(i,j);
+
+      for krow = 1:8
+        for kcol = 1:8
+          A(nn(krow),nn(kcol)) = A(nn(krow),nn(kcol)) + em(krow,kcol);
+        endfor
+      endfor
+
+    endfor
+  endfor
+
+  ## If requested, return A with diagonal scaling.
+  if (k)
+    A = diag (diag (A)) \ A;
+  endif
+endfunction
+
+function [A, b] = wilk (n)
+  ## WILK   Various specific matrices devised/discussed by Wilkinson.
+  ##        [A, b] = WILK(N) is the matrix or system of order N.
+  ##        N = 3: upper triangular system Ux=b illustrating inaccurate solution.
+  ##        N = 4: lower triangular system Lx=b, ill-conditioned.
+  ##        N = 5: HILB(6)(1:5,2:6)*1.8144.  Symmetric positive definite.
+  ##        N = 21: W21+, tridiagonal.   Eigenvalue problem.
+  ##
+  ##        References:
+  ##        J.H. Wilkinson, Error analysis of direct methods of matrix inversion,
+  ##           J. Assoc. Comput. Mach., 8 (1961),  pp. 281-330.
+  ##        J.H. Wilkinson, Rounding Errors in Algebraic Processes, Notes on Applied
+  ##           Science No. 32, Her Majesty's Stationery Office, London, 1963.
+  ##        J.H. Wilkinson, The Algebraic Eigenvalue Problem, Oxford University
+  ##           Press, 1965.
+
+  if (nargin != 1)
+    error ("gallery: 1 argument is required for wilk matrix.");
+  elseif (! isnumeric (n) || ! isscalar (n))
+    error ("gallery: N must be a numeric scalar for wilk matrix.");
+  endif
+
+  if (n == 3)
+    ## Wilkinson (1961) p.323.
+    A = [ 1e-10   0.9  -0.4
+          0       0.9  -0.4
+          0       0     1e-10 ];
+
+    b = [ 0
+          0
+          1];
+
+  elseif (n == 4)
+    ## Wilkinson (1963) p.105.
+    A = [0.9143e-4  0          0          0
+         0.8762     0.7156e-4  0          0
+         0.7943     0.8143     0.9504e-4  0
+         0.8017     0.6123     0.7165     0.7123e-4];
+
+    b = [0.6524
+         0.3127
+         0.4186
+         0.7853];
+
+  elseif (n == 5)
+    ## Wilkinson (1965), p.234.
+    A = hilb (6);
+    A = A(1:5, 2:6) * 1.8144;
+
+  elseif (n == 21)
+    ## Wilkinson (1965), p.308.
+    E = diag (ones (n-1, 1), 1);
+    m = (n-1)/2;
+    A = diag (abs (-m:m)) + E + E';
+
+  else
+    error ("gallery: unknown N `%d' for wilk matrix.", n);
+  endif
+endfunction
+
+## NOTE: bandred is part of the Test Matrix Toolbox and is used by randsvd()
+function A = bandred (A, kl, ku)
+  ## BANDRED  Band reduction by two-sided unitary transformations.
+  ##          B = BANDRED(A, KL, KU) is a matrix unitarily equivalent to A
+  ##          with lower bandwidth KL and upper bandwidth KU
+  ##          (i.e. B(i,j) = 0 if i > j+KL or j > i+KU).
+  ##          The reduction is performed using Householder transformations.
+  ##          If KU is omitted it defaults to KL.
+  ##
+  ##          Called by RANDSVD.
+  ##          This is a `standard' reduction.  Cf. reduction to bidiagonal form
+  ##          prior to computing the SVD.  This code is a little wasteful in that
+  ##          it computes certain elements which are immediately set to zero!
+  ## 
+  ##          Reference:
+  ##          G.H. Golub and C.F. Van Loan, Matrix Computations, second edition,
+  ##          Johns Hopkins University Press, Baltimore, Maryland, 1989.
+  ##          Section 5.4.3.
+
+  ##  Check for special case where order of left/right transformations matters.
+  ##  Easiest approach is to work on the transpose, flipping back at the end.
+  flip = false;
+  if (ku == 0)
+    flip = true;
+    A = A';
+    [ku, kl] = deal (kl, ku);
+  endif
+
+  [m, n] = size (A);
+
+  for j = 1:min (min (m, n), max (m-kl-1, n-ku-1))
+    if (j+kl+1 <= m)
+      [v, beta] = house (A(j+kl:m,j));
+      temp = A(j+kl:m,j:n);
+      A(j+kl:m,j:n) = temp - beta*v*(v'*temp);
+      A(j+kl+1:m,j) = zeros (m-j-kl, 1);
+    endif
+
+    if (j+ku+1 <= n)
+      [v, beta] = house (A(j,j+ku:n)');
+      temp = A(j:m,j+ku:n);
+      A(j:m,j+ku:n) = temp - beta*(temp*v)*v';
+      A(j,j+ku+1:n) = zeros (1, n-j-ku);
+    endif
+  endfor
+
+  if (flip)
+    A = A';
+  endif
+endfunction
--- a/scripts/special-matrix/module.mk	Mon Apr 29 19:13:40 2013 -0400
+++ b/scripts/special-matrix/module.mk	Sun May 12 21:45:57 2013 -0400
@@ -1,6 +1,7 @@
 FCN_FILE_DIRS += special-matrix
 
 special_matrix_FCN_FILES = \
+  special-matrix/gallery.m \
   special-matrix/hadamard.m \
   special-matrix/hankel.m \
   special-matrix/hilb.m \
--- a/src/mkoctfile.in.cc	Mon Apr 29 19:13:40 2013 -0400
+++ b/src/mkoctfile.in.cc	Sun May 12 21:45:57 2013 -0400
@@ -396,6 +396,13 @@
   return system (cmd.c_str ());
 }
 
+bool
+is_true (const std::string& s)
+{
+  return (s == "yes"
+          || s == "true");
+}
+
 int
 main (int argc, char **argv)
 {
@@ -414,7 +421,7 @@
   string ldflags = "";
   string pass_on_options = "";
   bool strip = false;
-  bool no_oct_file_strip_on_this_platform = %NO_OCT_FILE_STRIP%;
+  bool no_oct_file_strip_on_this_platform = is_true ("%NO_OCT_FILE_STRIP%");
   bool link = true;
   bool link_stand_alone = false;
   string output_ext = ".oct";
--- a/test/Makefile.am	Mon Apr 29 19:13:40 2013 -0400
+++ b/test/Makefile.am	Sun May 12 21:45:57 2013 -0400
@@ -54,6 +54,7 @@
 include bug-35448/module.mk
 include bug-36025/module.mk
 include bug-38236/module.mk
+include bug-38691/module.mk
 include classdef/module.mk
 include classes/module.mk
 include class-concat/module.mk
@@ -61,8 +62,13 @@
 include fcn-handle-derived-resolution/module.mk
 include nest/module.mk
 
+all-local: .gdbinit
+
+.gdbinit: ../etc/gdbinit
+	@$(gdbinit_install_rule)
+
 check: sparse.tst bc-overload-tests.stamp
-	$(top_builddir)/run-octave --norc --silent --no-history $(srcdir)/fntests.m $(srcdir)
+	$(top_builddir)/run-octave $(RUN_OCTAVE_OPTIONS) --norc --silent --no-history $(srcdir)/fntests.m $(srcdir)
 
 sparse.tst: build-sparse-tests.sh
 	$(srcdir)/build-sparse-tests.sh
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/bug-38691.tst	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,13 @@
+%!test
+%! addpath dir1
+%! [d1_r, d1_f1, d1_f2, d1_f3] = func1 (0);
+%! addpath dir2
+%! [d2_r, d2_f1, d2_f2, d2_f3] = func1 (0);
+%! assert (d1_r, 0);
+%! assert (d2_r, 1);
+%! assert (d1_f1, "dir1/func1");
+%! assert (d1_f2, "dir1/func2");
+%! assert (d1_f3, "dir1/func3");
+%! assert (d2_f1, "dir2/func1");
+%! assert (d2_f2, "dir2/func2");
+%! assert (d2_f3, "dir2/func3");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/dir1/func1.m	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,14 @@
+function [r, f1, f2, f3] = func1 (x)
+  f1 = "dir1/func1";
+  [r, f2, f3] = feval ("func2", x);
+endfunction
+
+function [r, f2, f3] = func2 (x)
+  f2 = "dir1/func2";
+  [r, f3] = feval ("func3", x);
+endfunction
+
+function [r, f3] = func3 (x)
+  f3 = "dir1/func3";
+  r = x;
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/dir2/func1.m	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,4 @@
+function [r, f1, f2, f3] = func1 (x)
+  f1 = "dir2/func1";
+  [r, f2, f3] = feval ("func2", x);
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/dir2/func2.m	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,4 @@
+function [r, f2, f3] = func2 (x)
+  f2 = "dir2/func2";
+  [r, f3] = feval ("func3", x);
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/dir2/func3.m	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,4 @@
+function [r, f3] = func3 (x)
+  f3 = "dir2/func3";
+  r = 1;
+endfunction
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/bug-38691/module.mk	Sun May 12 21:45:57 2013 -0400
@@ -0,0 +1,8 @@
+bug_38691_FCN_FILES = \
+  bug-38691/dir1/func1.m \
+  bug-38691/dir2/func1.m \
+  bug-38691/dir2/func2.m \
+  bug-38691/dir2/func3.m \
+  bug-38691/bug-38691.tst
+
+FCN_FILES += $(bug_38691_FCN_FILES)