Getting Started
***************

This chapter explains some of Octave's basic features, including how to start an Octave session, get help at the command prompt, edit the command line, and write Octave programs that can be executed as commands from your shell.

Invoking Octave from the Command Line
=====================================

Normally, Octave is used interactively by running the program octave without any arguments.  Once started, Octave reads commands from the terminal until you tell it to exit.

You can also specify the name of a file on the command line, and Octave will read and execute the commands from the named file and then exit when it is finished.

You can further control how Octave starts by using the command-line options described in the next section, and Octave itself can remind you of the options available.  Type octave --help to display all available options and briefly describe their use (octave -h is a shorter equivalent).

Command Line Options
--------------------

Here is a complete list of the command line options that Octave accepts.

--built-in-docstrings-file FILENAME
     Specify the name of the file containing documentation strings for the built-in functions of Octave.  This value is normally correct and should only need to be specified in extraordinary situations.

--debug
-d
     Enter parser debugging mode.  Using this option will cause Octave's parser to print a lot of information about the commands it reads, and is probably only useful if you are actually trying to debug the parser.

--doc-cache-file FILENAME
     Specify the name of the documentation cache file to use.  The value of FILENAME specified on the command line will override any value of OCTAVE_DOC_CACHE_FILE found in the environment, but not any commands in the system or user startup files that use the doc_cache_file function.

--echo-commands
-x
     Echo commands as they are executed.

--eval CODE
     Evaluate CODE and exit when finished unless --persist is also specified.

--exec-path PATH
     Specify the path to search for programs to run.  The value of PATH specified on the command line will override any value of OCTAVE_EXEC_PATH found in the environment, but not any commands in the system or user startup files that call the EXEC_PATH function.

--gui
     Start the graphical user interface (GUI).

--help
-h
     Print short help message and exit.

--image-path PATH
     Add path to the head of the search path for images.  The value of PATH specified on the command line will override any value of OCTAVE_IMAGE_PATH found in the environment, but not any commands in the system or user startup files that call the IMAGE_PATH function.

--info-file FILENAME
     Specify the name of the info file to use.  The value of FILENAME specified on the command line will override any value of OCTAVE_INFO_FILE found in the environment, but not any commands in the system or user startup files that use the info_file function.

--info-program PROGRAM
     Specify the name of the info program to use.  The value of PROGRAM specified on the command line will override any value of OCTAVE_INFO_PROGRAM found in the environment, but not any commands in the system or user startup files that use the info_program function.

--interactive
-i
     Force interactive behavior.  This can be useful for running Octave via a remote shell command or inside an Emacs shell buffer.

--line-editing
     Force readline use for command-line editing.

--no-gui
     Disable the graphical user interface (GUI) and use the command line interface (CLI) instead.  This is the default behavior, but this option may be useful to override a previous --gui.

--no-history
-H
     Disable recording of command-line history.

--no-init-file
     Don't read the initialization files ~/.octaverc and .octaverc.

--no-init-path
     Don't initialize the search path for function files to include default locations.

--no-line-editing
     Disable command-line editing.

--no-site-file
     Don't read the site-wide octaverc initialization files.

--no-window-system
-W
     Disable use of a windowing system including graphics.  This forces a strictly terminal-only environment.

--norc
-f
     Don't read any of the system or user initialization files at startup. This is equivalent to using both of the options --no-init-file and --no-site-file.

--path PATH
-p PATH
     Add path to the head of the search path for function files.  The value of PATH specified on the command line will override any value of OCTAVE_PATH found in the environment, but not any commands in the system or user startup files that set the internal load path through one of the path functions.

--persist
     Go to interactive mode after --eval or reading from a file named on the command line.

--silent
--quiet
-q
     Don't print the usual greeting and version message at startup.

--texi-macros-file FILENAME
     Specify the name of the file containing Texinfo macros for use by makeinfo.

--traditional
--braindead
     For compatibility with MATLAB, set initial values for user preferences to the following values

          PS1                             = ">> "
          PS2                             = ""
          beep_on_error                   = true
          confirm_recursive_rmdir         = false
          crash_dumps_octave_core         = false
          optimize_diagonal_matrix        = false
          optimize_permutation_matrix     = false
          optimize_range                  = false
          fixed_point_format              = true
          history_timestamp_format_string = "%%-- %D %I:%M %p --%%"
          print_empty_dimensions          = false
          print_struct_array_contents     = true
          save_default_options            = "-mat-binary"
          struct_levels_to_print          = 0

     and disable the following warnings

          Octave:abbreviated-property-match
          Octave:colon-nonscalar-argument
          Octave:data-file-in-path
          Octave:empty-index
          Octave:function-name-clash
          Octave:possible-matlab-short-circuit-operator

     Note that this does not enable the Octave:language-extension warning, which you might want if you want to be told about writing code that works in Octave but not MATLAB (see warning, warning_ids).

--verbose
-V
     Turn on verbose output.

--version
-v
     Print the program version number and exit.

FILE
     Execute commands from FILE.  Exit when done unless --persist is also specified.

Octave also includes several functions which return information about the command line, including the number of arguments and all of the options.

 -- ARGS =: argv ()
     Return the command line arguments passed to Octave.

     For example, if you invoked Octave using the command

          octave --no-line-editing --silent

     argv would return a cell array of strings with the elements --no-line-editing and --silent.

     If you write an executable Octave script, argv will return the list of arguments passed to the script.  See Executable Octave Programs, for an example of how to create an executable Octave script. program_name, cmdline_options

 -- OPT_STRUCT =: cmdline_options ()
     Return a structure containing detailed information about the command line arguments passed to Octave.

     Programming Note: This function provides copious amounts of information about Octave's parsing of command line options and may be more useful for debugging Octave rather than for general use. argv, program_name

 -- NAME =: program_name ()
     Return the filename component of the value returned by program_invocation_name.

     program_invocation_name, argv

 -- NAME =: program_invocation_name ()
     Return the string that was typed at the shell prompt to run Octave.

     The string may include path components as well as the program filename.

     If executing a script from the command line (e.g., octave foo.m) or using an executable Octave script, the program name is set to the name of the script.  See Executable Octave Programs, for an example of how to create an executable Octave script. program_name, argv

Here is an example of using these functions to reproduce the command line which invoked Octave.

     printf ("%s", program_name ());
     arg_list = argv ();
     for i = 1:nargin
       printf (" %s", arg_list{i});
     endfor
     printf ("\n");

See Indexing Cell Arrays, for an explanation of how to retrieve objects from cell arrays, and Defining Functions, for information about the variable nargin.

Startup Files
-------------

When Octave starts, it looks for commands to execute from the files in the following list.  These files may contain any valid Octave commands, including function definitions.

OCTAVE-HOME/share/octave/site/m/startup/octaverc
     where OCTAVE-HOME is the directory in which Octave is installed (the default is /usr/local). This file is provided so that changes to the default Octave environment can be made globally for all users at your site for all versions of Octave you have installed.  Care should be taken when making changes to this file since all users of Octave at your site will be affected.  The default file may be overridden by the environment variable OCTAVE_SITE_INITFILE.

OCTAVE-HOME/share/octave/VERSION/m/startup/octaverc
     where OCTAVE-HOME is the directory in which Octave is installed (the default is /usr/local), and VERSION is the version number of Octave.  This file is provided so that changes to the default Octave environment can be made globally for all users of a particular version of Octave.  Care should be taken when making changes to this file since all users of Octave at your site will be affected.  The default file may be overridden by the environment variable OCTAVE_VERSION_INITFILE.

CONFIG-DIR/octave/octaverc
     where CONFIG-DIR is the platform-dependent location for user local configuration files (e.g., $XDG_CONFIG_HOME on many Unix-like operating systems or %APPDATA% on Windows).

~/.octaverc
     This file is used to make personal changes to the default Octave environment.

.octaverc
     This file can be used to make changes to the default Octave environment for a particular project.  Octave searches for this file in the current directory after it reads ~/.octaverc.  Any use of the cd command in the ~/.octaverc file will affect the directory where Octave searches for .octaverc.

     If you start Octave in your home directory, commands from the file ~/.octaverc will only be executed once.

startup.m
     This file is used to make personal changes to the default Octave environment. It is executed for MATLAB compatibility, but ~/.octaverc is the preferred location for configuration changes.

A message will be displayed as each of the startup files is read if you invoke Octave with the --verbose option but without the --silent option.

The startup files are always processed in the system's locale charset (independent of the m-file encoding that is set, for example, in the GUI properties).  In other words, the system's locale charset is in effect until a user manually sets the m-file encoding (e.g., in one of the startup files) and triggers re-parsing of any relevant m-files.  Octave can be forced to use a new encoding with the function mfile_encoding:

     mfile_encoding ("utf-8");  # set new encoding
     clear ("functions");  # re-parse all .m files in the new encoding

This changes the encoding that is used to interpret all subsequently run startup and m-files (not including the currently executing file).

Quitting Octave
===============

Shutdown is initiated with the exit or quit commands (they are equivalent).  Similar to startup, Octave has a shutdown process that can be customized by user script files.  During shutdown Octave will search for the script file finish.m in the function load path.  Commands to save all workspace variables or cleanup temporary files may be placed there.  Additional functions to execute on shutdown may be registered with atexit.

 -- quit:
 -- quit: cancel
 -- quit: force
 -- quit: ("cancel")
 -- quit: ("force")
 -- quit: (STATUS)
 -- quit: (STATUS, "force")
 -- exit: (...)
     Quit the current Octave session.

     If the optional integer value STATUS is supplied, pass that value to the operating system as Octave's exit status.  The default value is zero.

     When exiting, Octave will attempt to run the m-file finish.m if it exists.  User commands to save the workspace or clean up temporary files may be placed in that file.  Alternatively, another m-file may be scheduled to run using atexit.  If an error occurs while executing the finish.m file, Octave does not exit and control is returned to the command prompt.

     If the optional argument "cancel" is provided, Octave does not exit and control is returned to the command prompt.  This feature allows the finish.m file to cancel the quit process.

     If the user preference to request confirmation before exiting, Octave will display a dialog and give the user an option to cancel the exit process.

     If the optional argument "force" is provided, no confirmation is requested, and the execution of the finish.m file is skipped.

     Programming Note: exit is an alias for quit and can be used interchangeably. atexit

 -- atexit: (FCN)
 -- atexit: (FCN, true)
 -- atexit: (FCN, false)
 -- STATUS =: atexit (FCN, false)
     Register a function to be called when Octave exits.

     For example,

          function last_words ()
            disp ("Bye bye");
          endfunction
          atexit ("last_words");

     will print the message "Bye bye" when Octave exits.

     The additional argument FLAG will register or unregister FCN from the list of functions to be called when Octave exits.  If FLAG is true, the function is registered, and if FLAG is false, it is unregistered.  For example, after registering the function last_words above,

          atexit ("last_words", false);

     will remove the function from the list and Octave will not call last_words when it exits.

     The optional output STATUS is only available when unregistering a function.  The value is true if the unregistering was successful and false otherwise.

     Programming Note: atexit only removes the first occurrence of a function from the list; if a function was placed in the list multiple times with atexit, it must also be removed from the list multiple times. quit

Commands for Getting Help
=========================

The entire text of this manual is available from the Octave prompt via the command doc.  In addition, the documentation for individual user-written functions and variables is also available via the help command.  This section describes the commands used for reading the manual and the documentation strings for user-supplied functions and variables.  See Function Files, for more information about how to document the functions you write.

 -- help: NAME
 -- help: --list
 -- help: .
 -- help:
 -- HELP_TEXT =: help (...)
     Display the help text for NAME.

     For example, the command help help prints a short message describing the help command.

     Given the single argument --list, list all operators, keywords, built-in functions, and loadable functions available in the current session of Octave.

     Given the single argument ., list all operators available in the current session of Octave.

     If invoked without any arguments, help displays instructions on how to access help from the command line.

     The help command can provide information about most operators, but NAME must be enclosed by single or double quotes to prevent the Octave interpreter from acting on NAME.  For example, help "+" displays help on the addition operator. doc, lookfor, which, info

 -- doc: FUNCTION_NAME
 -- doc:
     Display documentation for the function FUNCTION_NAME directly from an online version of the printed manual, using the GNU Info browser.

     If invoked without an argument, the manual is shown from the beginning.

     For example, the command doc rand starts the GNU Info browser at the rand node in the online version of the manual.

     Once the GNU Info browser is running, help for using it is available using the command C-h. help

 -- lookfor: STR
 -- lookfor: -all STR
 -- [FCN, HELP1STR] =: lookfor (STR)
 -- [FCN, HELP1STR] =: lookfor ("-all", STR)
     Search for the string STR in the documentation of all functions in the current function search path.

     By default, lookfor looks for STR in just the first sentence of the help string for each function found.  The entire help text of each function can be searched by using the "-all" argument.  All searches are case insensitive.

     When called with no output arguments, lookfor prints the list of matching functions to the terminal.  Otherwise, the output argument FCNS contains the function names and HELP1STR contains the first sentence from the help string of each function.

     Programming Note: The ability of lookfor to correctly identify the first sentence of the help text is dependent on the format of the function's help.  All Octave core functions are correctly formatted, but the same can not be guaranteed for external packages and user-supplied functions. Therefore, the use of the "-all" argument may be necessary to find related functions that are not a part of Octave.

     The speed of lookup is greatly enhanced by having a cached documentation file.  For more information, see doc_cache_create. help, doc, which, path, doc_cache_create

To see what is new in the current release of Octave, use the news function.

 -- news:
 -- news: PACKAGE
     Display the current NEWS file for Octave or an installed package.

     When called without an argument, display the NEWS file for Octave.

     When given a package name PACKAGE, display the current NEWS file for that package. ver, pkg

 -- info: ()
     Display contact information for the GNU Octave community.

 -- warranty: ()
     Describe the conditions for copying and distributing Octave.

The following functions can be used to change which programs are used for displaying the documentation, and where the documentation can be found.

 -- VAL =: info_file ()
 -- OLD_VAL =: info_file (NEW_VAL)
 -- OLD_VAL =: info_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the Octave info file.

     The default value is OCTAVE-HOME/share/info/octave.info, in which OCTAVE-HOME is the root directory of the Octave installation. The default value may be overridden by the environment variable OCTAVE_INFO_FILE, or the command line argument --info-file FNAME.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. info_program, doc, help, makeinfo_program

 -- VAL =: info_program ()
 -- OLD_VAL =: info_program (NEW_VAL)
 -- OLD_VAL =: info_program (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the info program to run.

     The default value is info.  The default value may be overridden by the environment variable OCTAVE_INFO_PROGRAM, or the command line argument --info-program NAME.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. info_file, doc, help, makeinfo_program

 -- VAL =: makeinfo_program ()
 -- OLD_VAL =: makeinfo_program (NEW_VAL)
 -- OLD_VAL =: makeinfo_program (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the program that Octave runs to format help text containing Texinfo markup commands.

     The default value is makeinfo.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. texi_macros_file, info_file, info_program, doc, help

 -- VAL =: texi_macros_file ()
 -- OLD_VAL =: texi_macros_file (NEW_VAL)
 -- OLD_VAL =: texi_macros_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the file containing Texinfo macros that are prepended to documentation strings before they are passed to makeinfo.

     The default value is OCTAVE-HOME/share/octave/VERSION/etc/macros.texi, in which OCTAVE-HOME is the root directory of the Octave installation, and VERSION is the Octave version number. The default value may be overridden by the environment variable OCTAVE_TEXI_MACROS_FILE, or the command line argument --texi-macros-file FNAME.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. makeinfo_program

 -- VAL =: doc_cache_file ()
 -- OLD_VAL =: doc_cache_file (NEW_VAL)
 -- OLD_VAL =: doc_cache_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the Octave documentation cache file.

     A cache file significantly improves the performance of the lookfor command.  The default value is OCTAVE-HOME/share/octave/VERSION/etc/doc-cache, in which OCTAVE-HOME is the root directory of the Octave installation, and VERSION is the Octave version number. The default value may be overridden by the environment variable OCTAVE_DOC_CACHE_FILE, or the command line argument --doc-cache-file FNAME.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. doc_cache_create, lookfor, info_program, doc, help, makeinfo_program lookfor

 -- VAL =: built_in_docstrings_file ()
 -- OLD_VAL =: built_in_docstrings_file (NEW_VAL)
 -- OLD_VAL =: built_in_docstrings_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the file containing docstrings for built-in Octave functions.

     The default value is OCTAVE-HOME/share/octave/VERSION/etc/built-in-docstrings, in which OCTAVE-HOME is the root directory of the Octave installation, and VERSION is the Octave version number.  The default value may be overridden by the environment variable OCTAVE_BUILT_IN_DOCSTRINGS_FILE, or the command line argument --built-in-docstrings-file FNAME.

     Note: This variable is only used when Octave is initializing itself. Modifying it during a running session of Octave will have no effect.

 -- VAL =: suppress_verbose_help_message ()
 -- OLD_VAL =: suppress_verbose_help_message (NEW_VAL)
 -- OLD_VAL =: suppress_verbose_help_message (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave will add additional help information to the end of the output from the help command and usage messages for built-in commands.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

The following functions are principally used internally by Octave for generating the documentation.  They are documented here for completeness and because they may occasionally be useful for users.

 -- doc_cache_create: (OUT_FILE, DIRECTORY)
 -- doc_cache_create: (OUT_FILE)
 -- doc_cache_create: ()
     Generate documentation cache for all functions in DIRECTORY.

     A documentation cache is generated for all functions in DIRECTORY which may be a single string or a cell array of strings.  The cache is used to speed up the function lookfor.

     The cache is saved in the file OUT_FILE which defaults to the value doc-cache if not given.

     If no directory is given (or it is the empty matrix), a cache for built-in functions, operators, and keywords is generated.

     doc_cache_file, lookfor, path

 -- [TEXT, FORMAT] =: get_help_text (NAME)
     Return the raw help text of function NAME.

     The raw help text is returned in TEXT and the format in FORMAT. The format is a string which is one of "texinfo", "html", or "plain text". get_help_text_from_file

 -- [TEXT, FORMAT] =: get_help_text_from_file (FNAME)
     Return the raw help text from the file FNAME.

     The raw help text is returned in TEXT and the format in FORMAT. The format is a string which is one of "texinfo", "html", or "plain text". get_help_text

 -- TEXT =: get_first_help_sentence (NAME)
 -- TEXT =: get_first_help_sentence (NAME, MAX_LEN)
 -- [TEXT, STATUS] =: get_first_help_sentence (...)
     Return the first sentence of a function's help text.

     The first sentence is defined as the text after the function declaration until either the first period (".") or the first appearance of two consecutive newlines ("\n\n").  The text is truncated to a maximum length of MAX_LEN, which defaults to 80.  If the text must be truncated the last three characters of the text are replaced with "..." to indicate that more text was available.

     The optional output argument STATUS returns the status reported by makeinfo.  If only one output argument is requested, and STATUS is nonzero, a warning is displayed.

     As an example, the first sentence of this help text is

          get_first_help_sentence ("get_first_help_sentence")
          -| ans = Return the first sentence of a function's help text.

Command Line Editing
====================

Octave uses the GNU Readline library to provide an extensive set of command-line editing and history features.  Only the most common features are described in this manual.  In addition, all of the editing functions can be bound to different key strokes at the user's discretion. This manual assumes no changes from the default Emacs bindings.  See the GNU Readline Library manual for more information on customizing Readline and for a complete feature list.

To insert printing characters (letters, digits, symbols, etc.), simply type the character.  Octave will insert the character at the cursor and advance the cursor forward.

Many of the command-line editing functions operate using control characters.  For example, the character Control-a moves the cursor to the beginning of the line.  To type C-a, hold down CTRL and then press a.  In the following sections, control characters such as Control-a are written as C-a.

Another set of command-line editing functions use Meta characters.  To type M-u, hold down the META key and press u.  Depending on the keyboard, the META key may be labeled ALT or even WINDOWS.  If your terminal does not have a META key, you can still type Meta characters using two-character sequences starting with ESC.  Thus, to enter M-u, you would type ESC u.  The ESC character sequences are also allowed on terminals with real Meta keys.  In the following sections, Meta characters such as Meta-u are written as M-u.

Cursor Motion
-------------

The following commands allow you to position the cursor.

C-b
     Move back one character.

C-f
     Move forward one character.

BACKSPACE
     Delete the character to the left of the cursor.

DEL
     Delete the character underneath the cursor.

C-d
     Delete the character underneath the cursor.

M-f
     Move forward a word.

M-b
     Move backward a word.

C-a
     Move to the start of the line.

C-e
     Move to the end of the line.

C-l
     Clear the screen, reprinting the current line at the top.

C-_
C-/
     Undo the last action.  You can undo all the way back to an empty line.

M-r
     Undo all changes made to this line.  This is like typing the `undo' command enough times to get back to the beginning.

The above table describes the most basic possible keystrokes that you need in order to do editing of the input line.  On most terminals, you can also use the left and right arrow keys in place of C-f and C-b to move forward and backward.

Notice how C-f moves forward a character, while M-f moves forward a word.  It is a loose convention that control keystrokes operate on characters while meta keystrokes operate on words.

The function clc will allow you to clear the screen from within Octave programs.

 -- clc: ()
 -- home: ()
     Clear the terminal screen and move the cursor to the upper left corner.

     Programming Note: home is an alias for clc and can be used interchangeably.

Killing and Yanking
-------------------

Killing text means to delete the text from the line, but to save it away for later use, usually by yanking it back into the line. If the description for a command says that it `kills' text, then you can be sure that you can get the text back in a different (or the same) place later.

Here is the list of commands for killing text.

C-k
     Kill the text from the current cursor position to the end of the line.

M-d
     Kill from the cursor to the end of the current word, or if between words, to the end of the next word.

M-DEL
     Kill from the cursor to the start of the previous word, or if between words, to the start of the previous word.

C-w
     Kill from the cursor to the previous whitespace.  This is different than M-DEL because the word boundaries differ.

And, here is how to yank the text back into the line.  Yanking means to copy the most-recently-killed text from the kill buffer.

C-y
     Yank the most recently killed text back into the buffer at the cursor.

M-y
     Rotate the kill-ring, and yank the new top.  You can only do this if the prior command is C-y or M-y.

When you use a kill command, the text is saved in a kill-ring. Any number of consecutive kills save all of the killed text together, so that when you yank it back, you get it in one clean sweep.  The kill ring is not line specific; the text that you killed on a previously typed line is available to be yanked back later, when you are typing another line.

Commands for Changing Text
--------------------------

The following commands can be used for entering characters that would otherwise have a special meaning (e.g., TAB, C-q, etc.), or for quickly correcting typing mistakes.

C-q
C-v
     Add the next character that you type to the line verbatim.  This is how to insert things like C-q for example.

M-TAB
     Insert a tab character.

C-t
     Drag the character before the cursor forward over the character at the cursor, also moving the cursor forward.  If the cursor is at the end of the line, then transpose the two characters before it.

M-t
     Drag the word behind the cursor past the word in front of the cursor moving the cursor over that word as well.

M-u
     Uppercase the characters following the cursor to the end of the current (or following) word, moving the cursor to the end of the word.

M-l
     Lowercase the characters following the cursor to the end of the current (or following) word, moving the cursor to the end of the word.

M-c
     Uppercase the character following the cursor (or the beginning of the next word if the cursor is between words), moving the cursor to the end of the word.

Letting Readline Type for You
-----------------------------

The following commands allow Octave to complete command and variable names for you.

TAB
     Attempt to do completion on the text before the cursor.  Octave can complete the names of commands and variables.

M-?
     List the possible completions of the text before the cursor.

 -- VAL =: completion_append_char ()
 -- OLD_VAL =: completion_append_char (NEW_VAL)
 -- OLD_VAL =: completion_append_char (NEW_VAL, "local")
     Query or set the internal character variable that is appended to successful command-line completion attempts.

     The default value is " " (a single space).

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

 -- COMPLETION_LIST =: completion_matches ("HINT")
     Generate possible word completions for Octave given the character sequence HINT.

     This function is provided for the benefit of programs like Emacs which might be controlling Octave and handling user input.  For example:

          completion_matches ("sine")
          =>
          sinetone
          sinewave

     Programming Note: The current command number in Octave is not incremented when this function is called.  This is a feature, not a bug.

Commands for Manipulating the History
-------------------------------------

Octave normally keeps track of the commands you type so that you can recall previous commands to edit or execute them again.  When you exit Octave, the most recent commands you have typed, up to the number specified by the variable history_size, are saved in a file. When Octave starts, it loads an initial list of commands from the file named by the variable history_file.

Here are the commands for simple browsing and searching the history list.

LFD
RET
     Accept the current line regardless of where the cursor is.  If the line is non-empty, add it to the history list.  If the line was a history line, then restore the history line to its original state.

C-p
     Move `up' through the history list.

C-n
     Move `down' through the history list.

M-<
     Move to the first line in the history.

M->
     Move to the end of the input history, i.e., the line you are entering!

C-r
     Search backward starting at the current line and moving `up' through the history as necessary.  This is an incremental search.

C-s
     Search forward starting at the current line and moving `down' through the history as necessary.

On most terminals, you can also use the up and down arrow keys in place of C-p and C-n to move through the history list.

In addition to the keyboard commands for moving through the history list, Octave provides three functions for viewing, editing, and re-running chunks of commands from the history list.

 -- history:
 -- history: OPT1 ...
 -- H =: history ()
 -- H =: history (OPT1, ...)
     If invoked with no arguments, history displays a list of commands that you have executed.

     Valid options are:

     N
     -N
          Display only the most recent N lines of history.

     -c
          Clear the history list.

     -q
          Don't number the displayed lines of history.  This is useful for cutting and pasting commands using the X Window System.

     -r FILE
          Read the file FILE, appending its contents to the current history list.  If the name is omitted, use the default history file (normally ~/.octave_hist).

     -w FILE
          Write the current history to the file FILE.  If the name is omitted, use the default history file (normally ~/.octave_hist).

     For example, to display the five most recent commands that you have typed without displaying line numbers, use the command history -q 5.

     If invoked with a single output argument, the history will be saved to that argument as a cell string and will not be output to screen. edit_history, run_history

 -- edit_history:
 -- edit_history: CMD_NUMBER
 -- edit_history: FIRST LAST
     Edit the history list using the editor named by the variable EDITOR.

     The commands to be edited are first copied to a temporary file.  When you exit the editor, Octave executes the commands that remain in the file.  It is often more convenient to use edit_history to define functions rather than attempting to enter them directly on the command line. The block of commands is executed as soon as you exit the editor. To avoid executing any commands, simply delete all the lines from the buffer before leaving the editor.

     When invoked with no arguments, edit the previously executed command; With one argument, edit the specified command CMD_NUMBER; With two arguments, edit the list of commands between FIRST and LAST.  Command number specifiers may also be negative where -1 refers to the most recently executed command. The following are equivalent and edit the most recently executed command.

          edit_history
          edit_history -1

     When using ranges, specifying a larger number for the first command than the last command reverses the list of commands before they are placed in the buffer to be edited. run_history, history

 -- run_history:
 -- run_history: CMD_NUMBER
 -- run_history: FIRST LAST
     Run commands from the history list.

     When invoked with no arguments, run the previously executed command;

     With one argument, run the specified command CMD_NUMBER;

     With two arguments, run the list of commands between FIRST and LAST.  Command number specifiers may also be negative where -1 refers to the most recently executed command.  For example, the command

          run_history
               OR
          run_history -1

     executes the most recent command again. The command

          run_history 13 169

     executes commands 13 through 169.

     Specifying a larger number for the first command than the last command reverses the list of commands before executing them. For example:

          disp (1)
          disp (2)
          run_history -1 -2
          =>
           2
           1

     edit_history, history

Octave also allows you customize the details of when, where, and how history is saved.

 -- VAL =: history_save ()
 -- OLD_VAL =: history_save (NEW_VAL)
 -- OLD_VAL =: history_save (NEW_VAL, "local")
     Query or set the internal variable that controls whether commands entered on the command line are saved in the history file.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. history_control, history_file, history_size, history_timestamp_format_string

 -- VAL =: history_control ()
 -- OLD_VAL =: history_control (NEW_VAL)
     Query or set the internal variable that specifies how commands are saved to the history list.

     The default value is an empty character string, but may be overridden by the environment variable OCTAVE_HISTCONTROL.

     The value of history_control is a colon-separated list of values controlling how commands are saved on the history list.  If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list.  A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups.  A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved.  Any value not in the above list is ignored.  If history_control is the empty string, all commands are saved on the history list, subject to the value of history_save. history_file, history_size, history_timestamp_format_string, history_save

 -- VAL =: history_file ()
 -- OLD_VAL =: history_file (NEW_VAL)
     Query or set the internal variable that specifies the name of the file used to store command history.

     All future commands issued during the current Octave session will be written to this new file (if the current setting of history_save allows for this).

     The default value is $DATA/octave/history, where $DATA is the platform-specific location for (roaming) user data files (e.g., $XDG_DATA_HOME or, if that is not set, ~/.local/share on Unix-like operating systems or %APPDATA% on Windows).  The default value may be overridden by the environment variable OCTAVE_HISTFILE.

     Programming Notes:

     If you want to permanently change the location of Octave's history file you need to issue the history_file command in every new Octave session. This can be achieved by using Octave's .octaverc startup file.

     If you also want to read the saved history commands of past Octave sessions from this different history file, then you need to use the additional command history -r after setting the new value of the history file.  Example code in Octave's startup file to do this might look like this:

          history_file ("~/new/.octave_hist");
          if (exist (history_file ()))
            history ("-r", history_file());
          endif

     history, history_control, history_save, history_size, history_timestamp_format_string

 -- VAL =: history_size ()
 -- OLD_VAL =: history_size (NEW_VAL)
     Query or set the internal variable that specifies how many entries to store in the history file.

     The default value is 1000, but may be overridden by the environment variable OCTAVE_HISTSIZE. history_file, history_timestamp_format_string, history_save

 -- VAL =: history_timestamp_format_string ()
 -- OLD_VAL =: history_timestamp_format_string (NEW_VAL)
 -- OLD_VAL =: history_timestamp_format_string (NEW_VAL, "local")
     Query or set the internal variable that specifies the format string for the comment line that is written to the history file when Octave exits.

     The format string is passed to strftime.  The default value is

          "# Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. strftime, history_file, history_size, history_save

 -- VAL =: EDITOR ()
 -- OLD_VAL =: EDITOR (NEW_VAL)
 -- OLD_VAL =: EDITOR (NEW_VAL, "local")
     Query or set the internal variable that specifies the default text editor.

     The default value is taken from the environment variable EDITOR when Octave starts.  If the environment variable is not initialized, EDITOR will be set to "emacs".

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

     edit, edit_history

Customizing readline
--------------------

Octave uses the GNU Readline library for command-line editing and history features.  Readline is very flexible and can be modified through a configuration file of commands (See the GNU Readline library for the exact command syntax).  The default configuration file is normally ~/.inputrc.

Octave provides two commands for initializing Readline and thereby changing the command line behavior.

 -- readline_read_init_file: ()
 -- readline_read_init_file: (FILE)
     Read the readline library initialization file FILE.

     If FILE is omitted, read the default initialization file (normally ~/.inputrc).

     See Readline Init File (GNU Readline Library), for details. readline_re_read_init_file

 -- readline_re_read_init_file: ()
     Re-read the last readline library initialization file that was read.

     See Readline Init File (GNU Readline Library), for details. readline_read_init_file

Customizing the Prompt
----------------------

The following variables are available for customizing the appearance of the command-line prompts.  Octave allows the prompt to be customized by inserting a number of backslash-escaped special characters that are decoded as follows:

\t
     The time.

\d
     The date.

\n
     Begins a new line by printing the equivalent of a carriage return followed by a line feed.

\s
     The name of the program (usually just octave).

\w
     The current working directory.

\W
     The basename of the current working directory.

\u
     The username of the current user.

\h
     The hostname, up to the first `.'.

\H
     The hostname.

\#
     The command number of this command, counting from when Octave starts.

\!
     The history number of this command.  This differs from \# by the number of commands in the history list when Octave starts.

\$
     If the effective UID is 0, a #, otherwise a $.

\nnn
     The character whose character code in octal is NNN.

\\
     A backslash.

 -- VAL =: PS1 ()
 -- OLD_VAL =: PS1 (NEW_VAL)
 -- OLD_VAL =: PS1 (NEW_VAL, "local")
     Query or set the primary prompt string.

     When executing interactively, Octave displays the primary prompt when it is ready to read a command.

     The default value of the primary prompt string is 'octave:\#> '.  To change it, use a command like

          PS1 ('\u@\H> ')

     which will result in the prompt boris@kremvax>  for the user boris logged in on the host kremvax.kgb.su.  Note that two backslashes are required to enter a backslash into a double-quoted character string.  See Strings.

     You can also use ANSI escape sequences if your terminal supports them. This can be useful for coloring the prompt.  For example,

          PS1 ('\[\033[01;31m\]\s:\#> \[\033[0m\]')

     will give the default Octave prompt a red coloring.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. PS2, PS4

 -- VAL =: PS2 ()
 -- OLD_VAL =: PS2 (NEW_VAL)
 -- OLD_VAL =: PS2 (NEW_VAL, "local")
     Query or set the secondary prompt string.

     The secondary prompt is printed when Octave is expecting additional input to complete a command.  For example, if you are typing a for loop that spans several lines, Octave will print the secondary prompt at the beginning of each line after the first.  The default value of the secondary prompt string is "> ".

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. PS1, PS4

 -- VAL =: PS4 ()
 -- OLD_VAL =: PS4 (NEW_VAL)
 -- OLD_VAL =: PS4 (NEW_VAL, "local")
     Query or set the character string used to prefix output produced when echoing commands is enabled.

     The default value is "+ ". See Diary and Echo Commands, for a description of echoing commands.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. echo, PS1, PS2

Diary and Echo Commands
-----------------------

Octave's diary feature allows you to keep a log of all or part of an interactive session by recording the input you type and the output that Octave produces in a separate file.

 -- diary:
 -- diary: on
 -- diary: off
 -- diary: FILENAME
 -- [STATUS, DIARYFILE] =: diary
     Record a list of all commands and the output they produce, mixed together just as they appear on the terminal.

     Valid options are:

     on
          Start recording a session in a file called diary in the current working directory.

     off
          Stop recording the session in the diary file.

     FILENAME
          Record the session in the file named FILENAME.

     With no input or output arguments, diary toggles the current diary state.

     If output arguments are requested, diary ignores inputs and returns the current status.  The boolean STATUS indicates whether recording is on or off, and DIARYFILE is the name of the file where the session is stored. history, evalc

Sometimes it is useful to see the commands in a function or script as they are being evaluated.  This can be especially helpful for debugging some kinds of problems.

 -- echo:
 -- echo: on
 -- echo: off
 -- echo: on all
 -- echo: off all
 -- echo: FUNCTION on
 -- echo: FUNCTION off
     Control whether commands are displayed as they are executed.

     Valid options are:

     on
          Enable echoing of commands as they are executed in script files.

     off
          Disable echoing of commands as they are executed in script files.

     on all
          Enable echoing of commands as they are executed in script files and functions.

     off all
          Disable echoing of commands as they are executed in script files and functions.

     FUNCTION on
          Enable echoing of commands as they are executed in the named function.

     FUNCTION off
          Disable echoing of commands as they are executed in the named function.

     With no arguments, echo toggles the current echo state.

     PS4

How Octave Reports Errors
=========================

Octave reports two kinds of errors for invalid programs.

A parse error occurs if Octave cannot understand something you have typed.  For example, if you misspell a keyword,

     octave:13> function z = f (x, y) z = x ||| 2; endfunction

Octave will respond immediately with a message like this:

     parse error:

       syntax error

     >>> function z = f (x, y) z = x ||| y; endfunction
                                       ^

For most parse errors, Octave uses a caret (^) to mark the point on the line where it was unable to make sense of your input.  In this case, Octave generated an error message because the keyword for the logical or operator (||) was misspelled.  It marked the error at the third | because the code leading up to this was correct but the final | was not understood.

Another class of error message occurs at evaluation time.  These errors are called run-time errors, or sometimes evaluation errors, because they occur when your program is being run, or evaluated.  For example, if after correcting the mistake in the previous function definition, you type

     octave:13> f ()

Octave will respond with

     error: `x' undefined near line 1 column 24
     error: called from:
     error:   f at line 1, column 22

This error message has several parts, and gives quite a bit of information to help you locate the source of the error.  The messages are generated from the point of the innermost error, and provide a traceback of enclosing expressions and function calls.

In the example above, the first line indicates that a variable named x was found to be undefined near line 1 and column 24 of some function or expression.  For errors occurring within functions, lines are counted from the beginning of the file containing the function definition.  For errors occurring outside of an enclosing function, the line number indicates the input line number, which is usually displayed in the primary prompt string.

The second and third lines of the error message indicate that the error occurred within the function f.  If the function f had been called from within another function, for example, g, the list of errors would have ended with one more line:

     error:   g at line 1, column 17

These lists of function calls make it fairly easy to trace the path your program took before the error occurred, and to correct the error before trying again.

Executable Octave Programs
==========================

Once you have learned Octave, you may want to write self-contained Octave scripts, using the #! script mechanism.  You can do this on GNU systems and on many Unix systems  (The #! mechanism works on Unix systems derived from Berkeley Unix, System V Release 4, and some System V Release 3 systems.).

Self-contained Octave scripts are useful when you want to write a program which users can invoke without knowing that the program is written in the Octave language.  Octave scripts are also used for batch processing of data files.  Once an algorithm has been developed and tested in the interactive portion of Octave, it can be committed to an executable script and used again and again on new data files.

As a trivial example of an executable Octave script, you might create a text file named hello, containing the following lines:

     #! OCTAVE-INTERPRETER-NAME -qf
     # a sample Octave program
     printf ("Hello, world!\n");

(where OCTAVE-INTERPRETER-NAME should be replaced with the full path and name of your Octave binary).  Note that this will only work if #! appears at the very beginning of the file.  After making the file executable (with the chmod command on Unix systems), you can simply type:

     hello

at the shell, and the system will arrange to run Octave as if you had typed:

     octave hello

The line beginning with #! lists the full path and filename of an interpreter to be run, and an optional initial command line argument to pass to that interpreter.  The operating system then runs the interpreter with the given argument and the full argument list of the executed program.  The first argument in the list is the full filename of the Octave executable.  The rest of the argument list will either be options to Octave, or data files, or both.  The -qf options are usually specified in stand-alone Octave programs to prevent them from printing the normal startup message, and to keep them from behaving differently depending on the contents of a particular user's ~/.octaverc file.  See Invoking Octave from the Command Line.

Note that some operating systems may place a limit on the number of characters that are recognized after #!.  Also, the arguments appearing in a #! line are parsed differently by various shells/systems.  The majority of them group all the arguments together in one string and pass it to the interpreter as a single argument.  In this case, the following script:

     #! OCTAVE-INTERPRETER-NAME -q -f # comment

is equivalent to typing at the command line:

     octave "-q -f # comment"

which will produce an error message.  Unfortunately, it is not possible for Octave to determine whether it has been called from the command line or from a #! script, so some care is needed when using the #! mechanism.

Passing Arguments to Executable Scripts
---------------------------------------

Note that when Octave is started from an executable script, the built-in function argv returns a cell array containing the command line arguments passed to the executable Octave script, not the arguments passed to the Octave interpreter on the #! line of the script. For example, the following program will reproduce the command line that was used to execute the script, not -qf.

     #! /bin/octave -qf
     printf ("%s", program_name ());
     arg_list = argv ();
     for i = 1:nargin
       printf (" %s", arg_list{i});
     endfor
     printf ("\n");

Dual-Purpose Executable Scripts and Octave Functions
----------------------------------------------------

To write m-files that can act as executable programs when called from the shell or as normal functions when called from within Octave, use default input arguments initialized with the argv function.

If a function is called from the shell Octave will not pass any input parameters to the function and therefore the default argument is used.  But when a function is called from the interpreter any arguments are passed to the function and these override the default.

Additionally, the file must end with the extension .m so that the interpreter will recognize it as an Octave function.  Finally, the output from argv is a cell array of strings.  It may be necessary to convert this to a numeric value with str2double or str2num before processing.

As a complete example, consider the following code located in the file mysin.m.

     #! /bin/octave -qf
     function retval = mysin (x = str2double (argv(){end}))
       retval = sin (x)
     endfunction

This can be called from the shell with

     mysin.m 1.5

or from Octave with

     mysin (1.5)

Comments in Octave Programs
===========================

A comment is some text that is included in a program for the sake of human readers, and which is NOT an executable part of the program. Comments can explain what the program does, and how it works.  Nearly all programming languages have provisions for comments, because programs are typically hard to understand without them.

Single Line Comments
--------------------

In the Octave language, a comment starts with either the sharp sign character, #, or the percent symbol % and continues to the end of the line.  Any text following the sharp sign or percent symbol is ignored by the Octave interpreter and not executed.  The following example shows whole line and partial line comments.

     function countdown
       # Count down for main rocket engines
       disp (3);
       disp (2);
       disp (1);
       disp ("Blast Off!");  # Rocket leaves pad
     endfunction

Block Comments
--------------

Entire blocks of code can be commented by enclosing the code between matching #{ and #} or %{ and %} markers. For example,

     function quick_countdown
       # Count down for main rocket engines
       disp (3);
      #{
       disp (2);
       disp (1);
      #}
       disp ("Blast Off!");  # Rocket leaves pad
     endfunction

will produce a very quick countdown from '3' to "Blast Off" as the lines "disp (2);" and "disp (1);" won't be executed.

The block comment markers must appear alone as the only characters on a line (excepting whitespace) in order to be parsed correctly.

Comments and the Help System
----------------------------

The help command (see Getting Help) is able to find the first block of comments in a function and return those as a documentation string.  This means that the same commands used to get help on built-in functions are available for properly formatted user-defined functions.  For example, after defining the function f below,

     function xdot = f (x, t)

     # usage: f (x, t)
     #
     # This function defines the right-hand
     # side functions for a set of nonlinear
     # differential equations.

       r = 0.25;
       ...
     endfunction

the command help f produces the output

      usage: f (x, t)

      This function defines the right-hand
      side functions for a set of nonlinear
      differential equations.

Although it is possible to put comment lines into keyboard-composed, throw-away Octave programs, it usually isn't very useful because the purpose of a comment is to help you or another person understand the program at a later time.

The help parser currently only recognizes single line comments (see Single Line Comments) and not block comments for the initial help text.