summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorkotfu <kotfu@kotfu.net>2019-07-06 17:52:19 -0600
committerGitHub <noreply@github.com>2019-07-06 17:52:19 -0600
commit34975b52e769514b44ee8c13147a22961e68e7a7 (patch)
treefe93e18257514efc25e8539d5005af34ef4dcd3b /docs
parente18013e7f6be6721531cde163ec4697eac247270 (diff)
parent0ae0567c48c0519cbecca8448df0caa32f530906 (diff)
downloadcmd2-git-34975b52e769514b44ee8c13147a22961e68e7a7.tar.gz
Merge pull request #712 from python-cmd2/docstructure
New Documentation Structure
Diffstat (limited to 'docs')
-rw-r--r--docs/alternatives.rst53
-rw-r--r--docs/api/cmd.rst5
-rw-r--r--docs/api/decorators.rst10
-rw-r--r--docs/api/exceptions.rst6
-rw-r--r--docs/api/index.rst11
-rw-r--r--docs/api/utility_classes.rst12
-rw-r--r--docs/api/utility_functions.rst48
-rw-r--r--docs/conf.py7
-rw-r--r--docs/copyright.rst7
-rw-r--r--docs/doc_conventions.rst128
-rw-r--r--docs/examples/first_app.rst322
-rw-r--r--docs/examples/index.rst7
-rw-r--r--docs/features/argument_processing.rst (renamed from docs/argument_processing.rst)147
-rw-r--r--docs/features/clipboard.rst5
-rw-r--r--docs/features/commands.rst4
-rw-r--r--docs/features/completion.rst4
-rw-r--r--docs/features/disable_commands.rst4
-rw-r--r--docs/features/embedded_python_shells.rst4
-rw-r--r--docs/features/generating_output.rst12
-rw-r--r--docs/features/help.rst141
-rw-r--r--docs/features/history.rst240
-rw-r--r--docs/features/hooks.rst (renamed from docs/hooks.rst)109
-rw-r--r--docs/features/index.rst26
-rw-r--r--docs/features/initialization.rst5
-rw-r--r--docs/features/multiline_commands.rst12
-rw-r--r--docs/features/os.rst11
-rw-r--r--docs/features/plugins.rst3
-rw-r--r--docs/features/prompt.rst42
-rw-r--r--docs/features/scripting.rst20
-rw-r--r--docs/features/settings.rst6
-rw-r--r--docs/features/shortcuts_aliases_macros.rst13
-rw-r--r--docs/features/startup_commands.rst2
-rw-r--r--docs/features/transcripts.rst (renamed from docs/transcript.rst)70
-rw-r--r--docs/freefeatures.rst377
-rw-r--r--docs/index.rst123
-rw-r--r--docs/install.rst155
-rw-r--r--docs/integrating.rst19
-rw-r--r--docs/migrating/free_features.rst5
-rw-r--r--docs/migrating/incompatibilities.rst22
-rw-r--r--docs/migrating/index.rst11
-rw-r--r--docs/migrating/minimum.rst4
-rw-r--r--docs/migrating/nextsteps.rst6
-rw-r--r--docs/migrating/why.rst25
-rw-r--r--docs/overview.rst27
-rw-r--r--docs/overview/alternatives.rst54
-rw-r--r--docs/overview/index.rst15
-rw-r--r--docs/overview/installation.rst162
-rw-r--r--docs/overview/integrating.rst32
-rw-r--r--docs/overview/resources.rst13
-rw-r--r--docs/overview/summary.rst22
-rw-r--r--docs/settingchanges.rst77
-rw-r--r--docs/unfreefeatures.rst295
52 files changed, 1946 insertions, 994 deletions
diff --git a/docs/alternatives.rst b/docs/alternatives.rst
deleted file mode 100644
index bf1545d6..00000000
--- a/docs/alternatives.rst
+++ /dev/null
@@ -1,53 +0,0 @@
-============================
-Alternatives to cmd and cmd2
-============================
-
-For programs that do not interact with the user in a continuous loop -
-programs that simply accept a set of arguments from the command line, return
-results, and do not keep the user within the program's environment - all
-you need are sys_\ .argv (the command-line arguments) and argparse_
-(for parsing UNIX-style options and flags). Though some people may prefer docopt_
-or click_ to argparse_.
-
-.. _sys: https://docs.python.org/3/library/sys.html
-.. _argparse: https://docs.python.org/3/library/argparse.html
-.. _docopt: https://pypi.python.org/pypi/docopt
-.. _click: http://click.pocoo.org
-
-
-The curses_ module produces applications that interact via a plaintext
-terminal window, but are not limited to simple text input and output;
-they can paint the screen with options that are selected from using the
-cursor keys. However, programming a curses_-based application is not as
-straightforward as using cmd_.
-
-.. _curses: https://docs.python.org/3/library/curses.html
-.. _cmd: https://docs.python.org/3/library/cmd.html
-
-Several Python packages exist for building interactive command-line applications
-approximately similar in concept to cmd_ applications. None of them
-share ``cmd2``'s close ties to cmd_, but they may be worth investigating
-nonetheless. Two of the most mature and full featured are:
-
- * `Python Prompt Toolkit`_
- * Click_
-
-.. _`Python Prompt Toolkit`: https://github.com/jonathanslenders/python-prompt-toolkit
-
-`Python Prompt Toolkit`_ is a library for building powerful interactive command lines and terminal applications in
-Python. It provides a lot of advanced visual features like syntax highlighting, bottom bars, and the ability to
-create fullscreen apps.
-
-Click_ is a Python package for creating beautiful command line interfaces in a composable way with as little code as
-necessary. It is more geared towards command line utilities instead of command line interpreters, but it can be used
-for either.
-
-Getting a working command-interpreter application based on either `Python Prompt Toolkit`_ or Click_ requires a good
-deal more effort and boilerplate code than ``cmd2``. ``cmd2`` focuses on providing an excellent out-of-the-box experience
-with as many useful features as possible built in for free with as little work required on the developer's part as
-possible. We believe that ``cmd2`` provides developers the easiest way to write a command-line interpreter, while
-allowing a good experience for end users. If you are seeking a visually richer end-user experience and don't
-mind investing more development time, we would recommend checking out `Python Prompt Toolkit`_.
-
-In the future, we may investigate options for incorporating the usage of `Python Prompt Toolkit`_ and/or Click_ into
-``cmd2`` applications.
diff --git a/docs/api/cmd.rst b/docs/api/cmd.rst
new file mode 100644
index 00000000..4f88101e
--- /dev/null
+++ b/docs/api/cmd.rst
@@ -0,0 +1,5 @@
+cmd2.Cmd
+========
+
+.. autoclass:: cmd2.cmd2.Cmd
+ :members:
diff --git a/docs/api/decorators.rst b/docs/api/decorators.rst
new file mode 100644
index 00000000..d7bfa138
--- /dev/null
+++ b/docs/api/decorators.rst
@@ -0,0 +1,10 @@
+Decorators
+==========
+
+.. autofunction:: cmd2.cmd2.with_category
+
+.. autofunction:: cmd2.cmd2.with_argument_list
+
+.. autofunction:: cmd2.cmd2.with_argparser_and_unknown_args
+
+.. autofunction:: cmd2.cmd2.with_argparser
diff --git a/docs/api/exceptions.rst b/docs/api/exceptions.rst
new file mode 100644
index 00000000..656c4a5a
--- /dev/null
+++ b/docs/api/exceptions.rst
@@ -0,0 +1,6 @@
+Exceptions
+==========
+
+.. autoexception:: cmd2.cmd2.EmbeddedConsoleExit
+
+.. autoexception:: cmd2.cmd2.EmptyStatement
diff --git a/docs/api/index.rst b/docs/api/index.rst
new file mode 100644
index 00000000..94d0fdd4
--- /dev/null
+++ b/docs/api/index.rst
@@ -0,0 +1,11 @@
+API Reference
+=============
+
+.. toctree::
+ :maxdepth: 1
+
+ cmd
+ decorators
+ exceptions
+ utility_classes
+ utility_functions
diff --git a/docs/api/utility_classes.rst b/docs/api/utility_classes.rst
new file mode 100644
index 00000000..7ed0c584
--- /dev/null
+++ b/docs/api/utility_classes.rst
@@ -0,0 +1,12 @@
+Utility Classes
+===============
+
+.. autoclass:: cmd2.utils.StdSim
+
+.. autoclass:: cmd2.utils.ByteBuf
+
+.. autoclass:: cmd2.utils.ProcReader
+
+.. autoclass:: cmd2.utils.ContextFlag
+
+.. autoclass:: cmd2.utils.RedirectionSavedState
diff --git a/docs/api/utility_functions.rst b/docs/api/utility_functions.rst
new file mode 100644
index 00000000..57a720bf
--- /dev/null
+++ b/docs/api/utility_functions.rst
@@ -0,0 +1,48 @@
+Utility Functions
+=================
+
+.. autofunction:: cmd2.utils.is_quoted
+
+.. autofunction:: cmd2.utils.quote_string_if_needed
+
+.. autofunction:: cmd2.utils.strip_quotes
+
+.. autofunction:: cmd2.cmd2.categorize
+
+.. autofunction:: cmd2.utils.center_text
+
+.. autofunction:: cmd2.utils.strip_quotes
+
+.. autofunction:: cmd2.utils.namedtuple_with_defaults
+
+.. autofunction:: cmd2.utils.cast
+
+.. autofunction:: cmd2.utils.which
+
+.. autofunction:: cmd2.utils.is_text_file
+
+.. autofunction:: cmd2.utils.remove_duplicates
+
+.. autofunction:: cmd2.utils.norm_fold
+
+.. autofunction:: cmd2.utils.try_int_or_force_to_lower_case
+
+.. autofunction:: cmd2.utils.alphabetical_sort
+
+.. autofunction:: cmd2.utils.unquote_specific_tokens
+
+.. autofunction:: cmd2.utils.natural_sort
+
+.. autofunction:: cmd2.utils.natural_keys
+
+.. autofunction:: cmd2.utils.expand_user_in_tokens
+
+.. autofunction:: cmd2.utils.expand_user
+
+.. autofunction:: cmd2.utils.find_editor
+
+.. autofunction:: cmd2.utils.get_exes_in_path
+
+.. autofunction:: cmd2.utils.files_from_glob_patterns
+
+.. autofunction:: cmd2.utils.files_from_glob_pattern
diff --git a/docs/conf.py b/docs/conf.py
index f22a117d..5463d0bb 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -37,6 +37,7 @@ sys.path.insert(0, os.path.abspath('..'))
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc',
+ 'sphinx.ext.autosectionlabel',
'sphinx.ext.intersphinx',
'sphinx.ext.doctest',
'sphinx.ext.todo']
@@ -55,8 +56,8 @@ master_doc = 'index'
# General information about the project.
project = 'cmd2'
-copyright = '2010-2018, Catherine Devlin and Todd Leonhardt'
-author = 'Catherine Devlin and Todd Leonhardt'
+copyright = '2010-2019, cmd2 contributors'
+author = 'cmd2 contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -85,6 +86,8 @@ pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
+# configure autosectionlabel extension
+autosectionlabel_prefix_document = True
# -- Options for HTML output ---------------------------------------------------
diff --git a/docs/copyright.rst b/docs/copyright.rst
new file mode 100644
index 00000000..b7183e62
--- /dev/null
+++ b/docs/copyright.rst
@@ -0,0 +1,7 @@
+Copyright
+=========
+
+The ``cmd2`` documentation is Copyright 2010-2019 by the `cmd2 contributors
+<https://github.com/python-cmd2/cmd2/graphs/contributors>`_ and is licensed
+under a `Creative Commons Attribution 4.0 International License
+<http://creativecommons.org/licenses/by/4.0/>`_.
diff --git a/docs/doc_conventions.rst b/docs/doc_conventions.rst
new file mode 100644
index 00000000..39302fc6
--- /dev/null
+++ b/docs/doc_conventions.rst
@@ -0,0 +1,128 @@
+Documentation Conventions
+=========================
+
+Guiding Principles
+------------------
+
+Follow the `Documentation Principles
+<http://www.writethedocs.org/guide/writing/docs-principles/>`_ described by
+`Write The Docs <http://www.writethedocs.org>`_
+
+In addition:
+
+- We have gone to great lengths to retain compatibility with the standard
+ library cmd, the documentation should make it easy for developers to
+ understand how to move from cmd to cmd2, and what benefits that will provide
+- We should provide both descriptive and reference documentation.
+- API reference documentation should be generated from docstrings in the code
+- Documentation should include rich hyperlinking to other areas of the
+ documentation, and to the API reference
+
+
+Naming Files
+------------
+
+- all lower case file names
+- if the name has multiple words, separate them with an underscore
+- all documentation file names end in '.rst'
+
+
+Heirarchy of headings
+---------------------
+
+show the heirarchy of sphinx headings we use, and the conventions (underline
+only, no overline)
+
+Use '=', then '-', then '~'. If your document needs more levels than that,
+break it into separate documents.
+
+You only have to worry about the heirarchy of headings within a single file.
+Sphinx handles the intra-file heirarchy magically on it's own.
+
+Use two blank lines before every heading unless it's the first heading in the
+file. Use one blank line after every heading
+
+
+Code
+----
+
+This documentation declares python as the default Sphinx domain. Python code
+or interactive python sessions can be presented by either:
+
+- finishing the preceding paragraph with a ``::`` and indenting the code
+- use the ``.. code-block::`` directive
+
+If you want to show other code, like shell commands, then use ``.. code-block:
+shell``.
+
+
+Table of Contents and Captions
+------------------------------
+
+
+Hyperlinks
+----------
+
+If you want to use an external hyperlink target, define the target at the top
+of the page, not the bottom.
+
+
+We use the Sphinx `autosectionlabel
+<http://www.sphinx-doc.org/en/master/usage/extensions/autosectionlabel.html>`_
+extension. This allows you to reference any header in any document by::
+
+ See :ref:`features/argument_processing:Help Messages`
+
+or ::
+
+ See :ref:`custom title<features/argument_processing:Help Messages>`
+
+Which render like
+
+See :ref:`features/argument_processing:Help Messages`
+
+and
+
+See :ref:`custom title<features/argument_processing:Help Messages>`
+
+[TODO what's the right way to link to source code? Can we make it link to the
+tag that the documentation is rendered from?]
+
+
+Autolinking
+-----------
+
+
+Referencing cmd2 API documentation
+----------------------------------
+
+
+Info and Warning Callouts
+-------------------------
+
+
+Wrapping
+--------
+
+Hard wrap all text with line lengths no greater than 79 characters. It makes
+everything easier when editing documentation, and has no impact on reading
+documentation because we render to html.
+
+
+Referencing cmd2
+-----------------
+
+Whenever you reference ``cmd2`` in the documentation, enclose it in double
+backticks. This indicates an inline literal in restructured text, and makes it
+stand out when rendered as html.
+
+Style Checker
+-------------
+
+Use `doc8 <https://pypi.org/project/doc8/>`_ to check the style of the
+documentation. This tool can be invoked using the proper options by typing:
+
+.. code-block:: shell
+
+ $ invoke doc8
+
diff --git a/docs/examples/first_app.rst b/docs/examples/first_app.rst
new file mode 100644
index 00000000..ef8e97dc
--- /dev/null
+++ b/docs/examples/first_app.rst
@@ -0,0 +1,322 @@
+First Application
+=================
+
+.. _cmd: https://docs.python.org/3/library/cmd.html
+
+Here's a quick walkthrough of a simple application which demonstrates 8
+features of ``cmd2``:
+
+* :ref:`features/settings:Settings`
+* :ref:`features/commands:Commands`
+* :ref:`features/argument_processing:Argument Processing`
+* :ref:`features/generating_output:Generating Output`
+* :ref:`features/help:Help`
+* :ref:`features/shortcuts_aliases_macros:Shortcuts`
+* :ref:`features/multiline_commands:Multiline Commands`
+* :ref:`features/history:History`
+
+If you don't want to type as we go, you can download the complete source for
+this example.
+
+
+Basic Application
+-----------------
+
+First we need to create a new ``cmd2`` application. Create a new file
+``first_app.py`` with the following contents::
+
+ #!/usr/bin/env python
+ """A simple cmd2 application."""
+ import cmd2
+
+
+ class FirstApp(cmd2.Cmd):
+ """A simple cmd2 application."""
+
+
+ if __name__ == '__main__':
+ import sys
+ c = FirstApp()
+ sys.exit(c.cmdloop())
+
+We have a new class ``FirstApp`` which is a subclass of
+:ref:`api/cmd:cmd2.Cmd`. When we tell python to run our file like this:
+
+.. code-block:: shell
+
+ $ python first_app.py
+
+it creates an instance of our class, and calls the ``cmdloop()`` method. This
+method accepts user input and runs commands based on that input. Because we
+subclassed ``cmd2.Cmd``, our new app already has a bunch of features built in.
+
+Congratulations, you have a working ``cmd2`` app. You can run it, and then type
+``quit`` to exit.
+
+
+Create a New Setting
+--------------------
+
+Before we create our first command, we are going to add a setting to this app.
+``cmd2`` includes robust support for :ref:`features/settings:Settings`. You
+configure settings during object initialization, so we need to add an
+initializer to our class::
+
+ def __init__(self):
+ super().__init__()
+
+ # Make maxrepeats settable at runtime
+ self.maxrepeats = 3
+ self.settable['maxrepeats'] = 'max repetitions for speak command'
+
+In that initializer, the first thing to do is to make sure we initialize
+``cmd2``. That's what the ``super().__init__()`` line does. Then we create an
+attribute to hold our setting, and then add a description of our setting to the
+``settable`` dictionary. If our attribute name isn't in ``settable``, then it
+won't be treated as a setting. Now if you run the script, and enter the ``set``
+command to see the settings, like this:
+
+.. code-block:: shell
+
+ $ python first_app.py
+ (Cmd) set
+
+you will see our ``maxrepeats`` setting show up with it's default value of
+``3``.
+
+
+Create A Command
+----------------
+
+Now we will create our first command, called ``speak`` which will echo back
+whatever we tell it to say. We are going to use an :ref:`argument processor
+<features/argument_processing:Argument Processing>` so the ``speak`` command
+can shout and talk piglatin. We will also use some built in methods for
+:ref:`generating output <features/generating_output:Generating Output>`. Add
+this code to ``first_app.py``, so that the ``speak_parser`` attribute and the
+``do_speak()`` method are part of the ``CmdLineApp()`` class::
+
+ speak_parser = argparse.ArgumentParser()
+ speak_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
+ speak_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
+ speak_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
+ speak_parser.add_argument('words', nargs='+', help='words to say')
+
+ @cmd2.with_argparser(speak_parser)
+ def do_speak(self, args):
+ """Repeats what you tell me to."""
+ words = []
+ for word in args.words:
+ if args.piglatin:
+ word = '%s%say' % (word[1:], word[0])
+ if args.shout:
+ word = word.upper()
+ words.append(word)
+ repetitions = args.repeat or 1
+ for _ in range(min(repetitions, self.maxrepeats)):
+ # .poutput handles newlines, and accommodates output redirection too
+ self.poutput(' '.join(words))
+
+Up at the top of the script, you'll also need to add::
+
+ import argparse
+
+There's a bit to unpack here, so let's walk through it. We created
+``speak_parser``, which uses the `argparse
+<https://docs.python.org/3/library/argparse.html>`_ module from the Python
+standard library to parse command line input from a user. There is nothing thus
+far that is specific to ``cmd2``.
+
+There is also a new method called ``do_speak()``. In both cmd_ and ``cmd2``,
+methods that start with ``do_`` become new commands, so by defining this method
+we have created a command called ``speak``.
+
+Note the ``@cmd2.with_argparser`` decorator on the ``do_speak()`` method. This
+decorator does 3 useful things for us:
+
+1. It tells ``cmd2`` to process all input for the ``speak`` command using the
+ argparser we defined. If the user input doesn't meet the requirements
+ defined by the argparser, then an error will be displayed for the user.
+2. It alters our ``do_speak`` method so that instead of receiving the raw user
+ input as a parameter, we receive the namespace from the argparser.
+3. It creates a help message for us based on the argparser.
+
+You can see in the body of the method how we use the namespace from the
+argparser (passed in as the variable ``args``). We build an array of words
+which we will output, honoring both the ``--piglatin`` and ``--shout`` options.
+
+At the end of the method, we use our ``maxrepeats`` setting as an upper limit
+to the number of times we will print the output.
+
+The last thing you'll notice is that we used the ``self.poutput()`` method to
+display our output. ``poutput()`` is a method provided by ``cmd2``, which I
+strongly recommend you use anytime you want to :ref:`generate output
+<features/generating_output:Generating Output>`. It provides the following
+benefits:
+
+1. Allows the user to redirect output to a text file or pipe it to a shell
+ process
+2. Gracefully handles ``BrokenPipeWarning`` exceptions for redirected output
+3. Makes the output show up in a :ref:`transcript
+ <features/transcripts:Transcripts>`
+4. Honors the setting to strip embedded ansi sequences (typically used for
+ background and foreground colors)
+
+Go run the script again, and try out the ``speak`` command. Try typing ``help
+speak``, and you will see a lovely usage message describing the various options
+for the command.
+
+With those few lines of code, we created a :ref:`command
+<features/commands:Commands>`, used an :ref:`Argument Processor
+<features/argument_processing:Argument Processing>`, added a nice :ref:`help
+message <features/help:Help>` for our users, and :ref:`generated some output
+<features/generating_output:Generating Output>`.
+
+
+Shortcuts
+---------
+
+``cmd2`` has several capabilities to simplify repetitive user input:
+:ref:`Shortcuts, Aliases, and Macros
+<features/shortcuts_aliases_macros:Shortcuts, Aliases, and Macros>`. Let's add
+a shortcut to our application. Shortcuts are character strings that can be used
+instead of a command name. For example, ``cmd2`` has support for a shortcut
+``!`` which runs the ``shell`` command. So instead of typing this:
+
+.. code-block:: shell
+
+ (Cmd) shell ls -al
+
+you can type this:
+
+.. code-block:: shell
+
+ (Cmd) !ls -al
+
+Let's add a shortcut for our ``speak`` command. Change the ``__init__()``
+method so it looks like this::
+
+ def __init__(self):
+ shortcuts = cmd2.DEFAULT_SHORTCUTS
+ shortcuts.update({'&': 'speak'})
+ super().__init__(shortcuts=shortcuts)
+
+ # Make maxrepeats settable at runtime
+ self.maxrepeats = 3
+ self.settable['maxrepeats'] = 'max repetitions for speak command'
+
+Shortcuts are passed to the ``cmd2`` initializer, and if you want the built-in
+shortcuts of ``cmd2`` you have to pass them. These shortcuts are defined as a
+dictionary, with the key being the shortcut, and the value containing the
+command. When using the default shortcuts and also adding your own, it's a good
+idea to use the ``.update()`` method to modify the dictionary. This way if you
+add a shortcut that happens to already be in the default set, yours will
+override, and you won't get any errors at runtime.
+
+Run your app again, and type:
+
+.. code-block:: shell
+
+ (Cmd) shortcuts
+
+to see the list of all of the shortcuts, including the one for speak that we
+just created.
+
+
+Multiline Commands
+------------------
+
+Some use cases benefit from the ability to have commands that span more than
+one line. For example, you might want the ability for your user to type in a
+SQL command, which can often span lines and which are terminated with a
+semicolon. Let's add a :ref:`multiline command
+<features/multiline_commands:Multiline Commands>` to our application. First
+we'll create a new command called ``orate``. This code shows both the
+definition of our ``speak`` command, and the ``orate`` command::
+
+ @cmd2.with_argparser(speak_parser)
+ def do_speak(self, args):
+ """Repeats what you tell me to."""
+ words = []
+ for word in args.words:
+ if args.piglatin:
+ word = '%s%say' % (word[1:], word[0])
+ if args.shout:
+ word = word.upper()
+ words.append(word)
+ repetitions = args.repeat or 1
+ for _ in range(min(repetitions, self.maxrepeats)):
+ # .poutput handles newlines, and accommodates output redirection too
+ self.poutput(' '.join(words))
+
+ # orate is a synonym for speak which takes multiline input
+ do_orate = do_speak
+
+With the new command created, we need to tell ``cmd2`` to treat that command as
+a multi-line command. Modify the super initialization line to look like this::
+
+ super().__init__(multiline_commands=['orate'], shortcuts=shortcuts)
+
+Now when you run the example, you can type something like this:
+
+.. code-block:: shell
+
+ (Cmd) orate O for a Muse of fire, that would ascend
+ > The brightest heaven of invention,
+ > A kingdom for a stage, princes to act
+ > And monarchs to behold the swelling scene! ;
+
+Notice the prompt changes to indicate that input is still ongoing. ``cmd2``
+will continue prompting for input until it sees an unquoted semicolon (the
+default multi-line command termination character).
+
+
+History
+-------
+
+``cmd2`` tracks the history of the commands that users enter. As a developer,
+you don't need to do anything to enable this functionality, you get it for
+free. If you want the history of commands to persist between invocations of
+your application, you'll need to do a little work. The
+:ref:`features/history:History` page has all the details.
+
+Users can access command history using two methods:
+
+- the `readline <https://docs.python.org/3/library/readline.html>`_ library
+ which provides a python interface to the `GNU readline library
+ <https://tiswww.case.edu/php/chet/readline/rltop.html>`_
+- the ``history`` command which is built-in to ``cmd2``
+
+From the prompt in a ``cmd2``-based application, you can press ``Control-p`` to
+move to the previously entered command, and ``Control-n`` to move to the next
+command. You can also search through the command history using ``Control-r``.
+The `GNU Readline User Manual
+<https://tiswww.case.edu/php/chet/readline/rluserman.html>`_ has all the
+details, including all the available commands, and instructions for customizing
+the key bindings.
+
+The ``history`` command allows a user to view the command history, and select
+commands from history by number, range, string search, or regular expression.
+With the selected commands, users can:
+
+- re-run the commands
+- edit the selected commands in a text editor, and run them after the text
+ editor exits
+- save the commands to a file
+- run the commands, saving both the commands and their output to a file
+
+Learn more about the ``history`` command by typing ``history -h`` at any
+``cmd2`` input prompt, or by exploring :ref:`Command History For Users
+<features/history:For Users>`.
+
+
+Conclusion
+----------
+
+You've just created a simple, but functional command line application. With
+minimal work on your part, the application leverages many robust features of
+``cmd2``. To learn more you can:
+
+- Dive into all of the :doc:`../features/index` that ``cmd2`` provides
+- Look at more :doc:`../examples/index`
+- Browse the :doc:`../api/index`
diff --git a/docs/examples/index.rst b/docs/examples/index.rst
new file mode 100644
index 00000000..2070b7a3
--- /dev/null
+++ b/docs/examples/index.rst
@@ -0,0 +1,7 @@
+Examples
+========
+
+.. toctree::
+ :maxdepth: 1
+
+ first_app
diff --git a/docs/argument_processing.rst b/docs/features/argument_processing.rst
index a1fc107b..5efc83ef 100644
--- a/docs/argument_processing.rst
+++ b/docs/features/argument_processing.rst
@@ -1,51 +1,64 @@
.. _decorators:
-===================
Argument Processing
===================
-``cmd2`` makes it easy to add sophisticated argument processing to your commands using the ``argparse`` python module.
-``cmd2`` handles the following for you:
+``cmd2`` makes it easy to add sophisticated argument processing to your
+commands using the ``argparse`` python module. ``cmd2`` handles the following
+for you:
1. Parsing input and quoted strings like the Unix shell
-2. Parse the resulting argument list using an instance of ``argparse.ArgumentParser`` that you provide
-3. Passes the resulting ``argparse.Namespace`` object to your command function. The ``Namespace`` includes the
- ``Statement`` object that was created when parsing the command line. It is stored in the ``__statement__``
- attribute of the ``Namespace``.
+
+2. Parse the resulting argument list using an instance of
+ ``argparse.ArgumentParser`` that you provide
+
+3. Passes the resulting ``argparse.Namespace`` object to your command function.
+ The ``Namespace`` includes the ``Statement`` object that was created when
+ parsing the command line. It is stored in the ``__statement__`` attribute of
+ the ``Namespace``.
4. Adds the usage message from the argument parser to your command.
-5. Checks if the ``-h/--help`` option is present, and if so, display the help message for the command
+5. Checks if the ``-h/--help`` option is present, and if so, display the help
+ message for the command
-These features are all provided by the ``@with_argparser`` decorator which is importable from ``cmd2``.
+These features are all provided by the ``@with_argparser`` decorator which is
+importable from ``cmd2``.
-See the either the argprint_ or decorator_ example to learn more about how to use the various ``cmd2`` argument
-processing decorators in your ``cmd2`` applications.
+See the either the argprint_ or decorator_ example to learn more about how to
+use the various ``cmd2`` argument processing decorators in your ``cmd2``
+applications.
.. _argprint: https://github.com/python-cmd2/cmd2/blob/master/examples/arg_print.py
.. _decorator: https://github.com/python-cmd2/cmd2/blob/master/examples/decorator_example.py
Decorators provided by cmd2 for argument processing
-===================================================
-``cmd2`` provides the following decorators for assisting with parsing arguments passed to commands:
+---------------------------------------------------
+
+``cmd2`` provides the following decorators for assisting with parsing arguments
+passed to commands:
.. automethod:: cmd2.cmd2.with_argument_list
+ :noindex:
.. automethod:: cmd2.cmd2.with_argparser
+ :noindex:
.. automethod:: cmd2.cmd2.with_argparser_and_unknown_args
+ :noindex:
-All of these decorators accept an optional **preserve_quotes** argument which defaults to ``False``.
-Setting this argument to ``True`` is useful for cases where you are passing the arguments to another
-command which might have its own argument parsing.
+All of these decorators accept an optional **preserve_quotes** argument which
+defaults to ``False``. Setting this argument to ``True`` is useful for cases
+where you are passing the arguments to another command which might have its own
+argument parsing.
Using the argument parser decorator
-===================================
+-----------------------------------
For each command in the ``cmd2`` subclass which requires argument parsing,
create a unique instance of ``argparse.ArgumentParser()`` which can parse the
-input appropriately for the command. Then decorate the command method with
-the ``@with_argparser`` decorator, passing the argument parser as the
-first parameter to the decorator. This changes the second argument to the command method, which will contain the results
-of ``ArgumentParser.parse_args()``.
+input appropriately for the command. Then decorate the command method with the
+``@with_argparser`` decorator, passing the argument parser as the first
+parameter to the decorator. This changes the second argument to the command
+method, which will contain the results of ``ArgumentParser.parse_args()``.
Here's what it looks like::
@@ -72,30 +85,31 @@ Here's what it looks like::
.. warning::
- It is important that each command which uses the ``@with_argparser`` decorator be passed a unique instance of a
- parser. This limitation is due to bugs in CPython prior to Python 3.7 which make it impossible to make a deep copy
- of an instance of a ``argparse.ArgumentParser``.
+ It is important that each command which uses the ``@with_argparser``
+ decorator be passed a unique instance of a parser. This limitation is due
+ to bugs in CPython prior to Python 3.7 which make it impossible to make a
+ deep copy of an instance of a ``argparse.ArgumentParser``.
- See the table_display_ example for a work-around that demonstrates how to create a function which returns a unique
- instance of the parser you want.
+ See the table_display_ example for a work-around that demonstrates how to
+ create a function which returns a unique instance of the parser you want.
.. note::
- The ``@with_argparser`` decorator sets the ``prog`` variable in
- the argument parser based on the name of the method it is decorating.
- This will override anything you specify in ``prog`` variable when
- creating the argument parser.
+ The ``@with_argparser`` decorator sets the ``prog`` variable in the argument
+ parser based on the name of the method it is decorating. This will override
+ anything you specify in ``prog`` variable when creating the argument parser.
.. _table_display: https://github.com/python-cmd2/cmd2/blob/master/examples/table_display.py
Help Messages
-=============
+-------------
-By default, cmd2 uses the docstring of the command method when a user asks
-for help on the command. When you use the ``@with_argparser``
-decorator, the docstring for the ``do_*`` method is used to set the description for the ``argparse.ArgumentParser``.
+By default, cmd2 uses the docstring of the command method when a user asks for
+help on the command. When you use the ``@with_argparser`` decorator, the
+docstring for the ``do_*`` method is used to set the description for the
+``argparse.ArgumentParser``.
With this code::
@@ -113,7 +127,7 @@ With this code::
the ``help tag`` command displays:
-.. code-block:: none
+.. code-block:: text
usage: tag [-h] tag content [content ...]
@@ -127,8 +141,8 @@ the ``help tag`` command displays:
-h, --help show this help message and exit
-If you would prefer you can set the ``description`` while instantiating the ``argparse.ArgumentParser`` and leave the
-docstring on your method empty::
+If you would prefer you can set the ``description`` while instantiating the
+``argparse.ArgumentParser`` and leave the docstring on your method empty::
import argparse
from cmd2 import with_argparser
@@ -143,7 +157,7 @@ docstring on your method empty::
Now when the user enters ``help tag`` they see:
-.. code-block:: none
+.. code-block:: text
usage: tag [-h] tag content [content ...]
@@ -173,7 +187,7 @@ To add additional text to the end of the generated help message, use the ``epilo
Which yields:
-.. code-block:: none
+.. code-block:: text
usage: tag [-h] tag content [content ...]
@@ -190,15 +204,17 @@ Which yields:
.. warning::
- If a command **foo** is decorated with one of cmd2's argparse decorators, then **help_foo** will not
- be invoked when ``help foo`` is called. The argparse_ module provides a rich API which can be used to
- tweak every aspect of the displayed help and we encourage ``cmd2`` developers to utilize that.
+ If a command **foo** is decorated with one of cmd2's argparse decorators,
+ then **help_foo** will not be invoked when ``help foo`` is called. The
+ argparse_ module provides a rich API which can be used to tweak every
+ aspect of the displayed help and we encourage ``cmd2`` developers to
+ utilize that.
.. _argparse: https://docs.python.org/3/library/argparse.html
Receiving an argument list
-==========================
+--------------------------
The default behavior of ``cmd2`` is to pass the user input directly to your
``do_*`` methods as a string. The object passed to your method is actually a
@@ -247,10 +263,12 @@ argument list instead of a string::
pass
-Using the argument parser decorator and also receiving a list of unknown positional arguments
-===============================================================================================
-If you want all unknown arguments to be passed to your command as a list of strings, then
-decorate the command method with the ``@with_argparser_and_unknown_args`` decorator.
+Unknown positional arguments
+----------------------------
+
+If you want all unknown arguments to be passed to your command as a list of
+strings, then decorate the command method with the
+``@with_argparser_and_unknown_args`` decorator.
Here's what it looks like::
@@ -275,13 +293,17 @@ Here's what it looks like::
...
-Using custom argparse.Namespace with argument parser decorators
-===============================================================================================
-In some cases, it may be necessary to write custom ``argparse`` code that is dependent on state data of your
-application. To support this ability while still allowing use of the decorators, both ``@with_argparser`` and
-``@with_argparser_and_unknown_args`` have an optional argument called ``ns_provider``.
+Using custom argparse.Namespace
+-------------------------------
+
+In some cases, it may be necessary to write custom ``argparse`` code that is
+dependent on state data of your application. To support this ability while
+still allowing use of the decorators, both ``@with_argparser`` and
+``@with_argparser_and_unknown_args`` have an optional argument called
+``ns_provider``.
-``ns_provider`` is a Callable that accepts a ``cmd2.Cmd`` object as an argument and returns an ``argparse.Namespace``::
+``ns_provider`` is a Callable that accepts a ``cmd2.Cmd`` object as an argument
+and returns an ``argparse.Namespace``::
Callable[[cmd2.Cmd], argparse.Namespace]
@@ -297,18 +319,23 @@ To use this function with the argparse decorators, do the following::
@with_argparser(my_parser, ns_provider=settings_ns_provider)
-The Namespace is passed by the decorators to the ``argparse`` parsing functions which gives your custom code access
-to the state data it needs for its parsing logic.
+The Namespace is passed by the decorators to the ``argparse`` parsing functions
+which gives your custom code access to the state data it needs for its parsing
+logic.
Sub-commands
-============
+------------
+
Sub-commands are supported for commands using either the ``@with_argparser`` or
-``@with_argparser_and_unknown_args`` decorator. The syntax for supporting them is based on argparse sub-parsers.
+``@with_argparser_and_unknown_args`` decorator. The syntax for supporting them
+is based on argparse sub-parsers.
-You may add multiple layers of sub-commands for your command. Cmd2 will automatically traverse and tab-complete
-sub-commands for all commands using argparse.
+You may add multiple layers of sub-commands for your command. Cmd2 will
+automatically traverse and tab-complete sub-commands for all commands using
+argparse.
-See the subcommands_ and tab_autocompletion_ example to learn more about how to use sub-commands in your ``cmd2`` application.
+See the subcommands_ and tab_autocompletion_ example to learn more about how to
+use sub-commands in your ``cmd2`` application.
.. _subcommands: https://github.com/python-cmd2/cmd2/blob/master/examples/subcommands.py
.. _tab_autocompletion: https://github.com/python-cmd2/cmd2/blob/master/examples/tab_autocompletion.py
diff --git a/docs/features/clipboard.rst b/docs/features/clipboard.rst
new file mode 100644
index 00000000..d5048cc0
--- /dev/null
+++ b/docs/features/clipboard.rst
@@ -0,0 +1,5 @@
+Clipboard Integration
+=====================
+
+.. automodule:: cmd2.clipboard
+ :members:
diff --git a/docs/features/commands.rst b/docs/features/commands.rst
new file mode 100644
index 00000000..3eec2373
--- /dev/null
+++ b/docs/features/commands.rst
@@ -0,0 +1,4 @@
+Commands
+========
+
+How to create a command with a ``do_command`` method,
diff --git a/docs/features/completion.rst b/docs/features/completion.rst
new file mode 100644
index 00000000..c89b24cc
--- /dev/null
+++ b/docs/features/completion.rst
@@ -0,0 +1,4 @@
+Completion
+==========
+
+How tab completion works and how to implement it in your own project
diff --git a/docs/features/disable_commands.rst b/docs/features/disable_commands.rst
new file mode 100644
index 00000000..b0f7f11b
--- /dev/null
+++ b/docs/features/disable_commands.rst
@@ -0,0 +1,4 @@
+Disabling Commands
+==================
+
+How to disable and re-enable commands, by individual command and by category
diff --git a/docs/features/embedded_python_shells.rst b/docs/features/embedded_python_shells.rst
new file mode 100644
index 00000000..ace68877
--- /dev/null
+++ b/docs/features/embedded_python_shells.rst
@@ -0,0 +1,4 @@
+Embedded Python Shells
+======================
+
+Describe ``py`` and optional ``ipy`` commands
diff --git a/docs/features/generating_output.rst b/docs/features/generating_output.rst
new file mode 100644
index 00000000..1dab6f64
--- /dev/null
+++ b/docs/features/generating_output.rst
@@ -0,0 +1,12 @@
+Generating Output
+=================
+
+how to generate output
+
+- poutput
+- perror
+- paging
+- exceptions
+- color support
+
+
diff --git a/docs/features/help.rst b/docs/features/help.rst
new file mode 100644
index 00000000..755d40f9
--- /dev/null
+++ b/docs/features/help.rst
@@ -0,0 +1,141 @@
+Help
+====
+
+use the categorize() function to create help categories
+
+Use ``help_method()`` to custom roll your own help messages.
+
+See :ref:`features/argument_processing:Help Messages`
+
+Grouping Commands
+-----------------
+
+By default, the ``help`` command displays::
+
+ Documented commands (type help <topic>):
+ ========================================
+ alias help ipy py run_pyscript set shortcuts
+ edit history macro quit run_script shell
+
+If you have a large number of commands, you can optionally group your commands
+into categories. Here's the output from the example ``help_categories.py``::
+
+ Documented commands (type help <topic>):
+
+ Application Management
+ ======================
+ deploy findleakers redeploy sessions stop
+ expire list restart start undeploy
+
+ Command Management
+ ==================
+ disable_commands enable_commands
+
+ Connecting
+ ==========
+ connect which
+
+ Server Information
+ ==================
+ resources serverinfo sslconnectorciphers status thread_dump vminfo
+
+ Other
+ =====
+ alias edit history py run_pyscript set shortcuts
+ config help macro quit run_script shell version
+
+There are 2 methods of specifying command categories, using the
+``@with_category`` decorator or with the ``categorize()`` function. Once a
+single command category is detected, the help output switches to a categorized
+mode of display. All commands with an explicit category defined default to the
+category `Other`.
+
+Using the ``@with_category`` decorator::
+
+ @with_category(CMD_CAT_CONNECTING)
+ def do_which(self, _):
+ """Which command"""
+ self.poutput('Which')
+
+Using the ``categorize()`` function:
+
+ You can call with a single function::
+
+ def do_connect(self, _):
+ """Connect command"""
+ self.poutput('Connect')
+
+ # Tag the above command functions under the category Connecting
+ categorize(do_connect, CMD_CAT_CONNECTING)
+
+ Or with an Iterable container of functions::
+
+ def do_undeploy(self, _):
+ """Undeploy command"""
+ self.poutput('Undeploy')
+
+ def do_stop(self, _):
+ """Stop command"""
+ self.poutput('Stop')
+
+ def do_findleakers(self, _):
+ """Find Leakers command"""
+ self.poutput('Find Leakers')
+
+ # Tag the above command functions under the category Application Management
+ categorize((do_undeploy,
+ do_stop,
+ do_findleakers), CMD_CAT_APP_MGMT)
+
+The ``help`` command also has a verbose option (``help -v`` or ``help
+--verbose``) that combines the help categories with per-command Help Messages::
+
+ Documented commands (type help <topic>):
+
+ Application Management
+ ================================================================================
+ deploy Deploy command
+ expire Expire command
+ findleakers Find Leakers command
+ list List command
+ redeploy Redeploy command
+ restart usage: restart [-h] {now,later,sometime,whenever}
+ sessions Sessions command
+ start Start command
+ stop Stop command
+ undeploy Undeploy command
+
+ Connecting
+ ================================================================================
+ connect Connect command
+ which Which command
+
+ Server Information
+ ================================================================================
+ resources Resources command
+ serverinfo Server Info command
+ sslconnectorciphers SSL Connector Ciphers command is an example of a command that contains
+ multiple lines of help information for the user. Each line of help in a
+ contiguous set of lines will be printed and aligned in the verbose output
+ provided with 'help --verbose'
+ status Status command
+ thread_dump Thread Dump command
+ vminfo VM Info command
+
+ Other
+ ================================================================================
+ alias Define or display aliases
+ config Config command
+ edit Edit a file in a text editor
+ help List available commands with "help" or detailed help with "help cmd"
+ history usage: history [-h] [-r | -e | -s | -o FILE | -t TRANSCRIPT] [arg]
+ py Invoke python command, shell, or script
+ quit Exits this application
+ run_pyscript Runs a python script file inside the console
+ run_script Runs commands in script file that is encoded as either ASCII or UTF-8 text
+ set usage: set [-h] [-a] [-l] [settable [settable ...]]
+ shell Execute a command as if at the OS prompt
+ shortcuts Lists shortcuts available
+ unalias Unsets aliases
+ version Version command
+
diff --git a/docs/features/history.rst b/docs/features/history.rst
new file mode 100644
index 00000000..7d6a03a4
--- /dev/null
+++ b/docs/features/history.rst
@@ -0,0 +1,240 @@
+History
+=======
+
+For Developers
+--------------
+
+- Describe how cmd2 tracks history
+- how persistent history works
+- differences in history and bash shell history (we only store valid commands
+ in history)
+- reference the public code structures we use to store history
+
+``cmd2`` adds the option of making this history persistent via optional
+arguments to ``cmd2.Cmd.__init__()``:
+
+.. automethod:: cmd2.cmd2.Cmd.__init__
+
+
+For Users
+---------
+
+You can use the up and down arrow keys to move through the history of
+previously entered commands.
+
+If the ``readline`` module is installed, you can press ``Control-p`` to move to
+the previously entered command, and ``Control-n`` to move to the next command.
+You can also search through the command history using ``Control-r``.
+
+Eric Johnson hosts a nice `readline cheat sheet
+<http://readline.kablamo.org/emacs.html>`_, or you can dig into the `GNU
+Readline User Manual
+<https://tiswww.case.edu/php/chet/readline/rluserman.html>`_ for all the
+details, including instructions for customizing the key bindings.
+
+``cmd2`` makes a third type of history access available with the ``history``
+command. Each time the user enters a command, ``cmd2`` saves the input. The
+``history`` command lets you do interesting things with that saved input. The
+examples to follow all assume that you have entered the following commands::
+
+ (Cmd) alias create one !echo one
+ Alias 'one' created
+ (Cmd) alias create two !echo two
+ Alias 'two' created
+ (Cmd) alias create three !echo three
+ Alias 'three' created
+ (Cmd) alias create four !echo four
+ Alias 'four' created
+
+In it's simplest form, the ``history`` command displays previously entered
+commands. With no additional arguments, it displays all previously entered
+commands::
+
+ (Cmd) history
+ 1 alias create one !echo one
+ 2 alias create two !echo two
+ 3 alias create three !echo three
+ 4 alias create four !echo four
+
+If you give a positive integer as an argument, then it only displays the
+specified command::
+
+ (Cmd) history 4
+ 4 alias create four !echo four
+
+If you give a negative integer *N* as an argument, then it display the *Nth*
+last command. For example, if you give ``-1`` it will display the last command
+you entered. If you give ``-2`` it will display the next to last command you
+entered, and so forth::
+
+ (Cmd) history -2
+ 3 alias create three !echo three
+
+You can use a similar mechanism to display a range of commands. Simply give two
+command numbers separated by ``..`` or ``:``, and you will see all commands
+between, and including, those two numbers::
+
+ (Cmd) history 1:3
+ 1 alias create one !echo one
+ 2 alias create two !echo two
+ 3 alias create three !echo three
+
+If you omit the first number, it will start at the beginning. If you omit the
+last number, it will continue to the end::
+
+ (Cmd) history :2
+ 1 alias create one !echo one
+ 2 alias create two !echo two
+ (Cmd) history 2:
+ 2 alias create two !echo two
+ 3 alias create three !echo three
+ 4 alias create four !echo four
+
+If you want to display the last three commands entered::
+
+ (Cmd) history -- -3:
+ 2 alias create two !echo two
+ 3 alias create three !echo three
+ 4 alias create four !echo four
+
+Notice the double dashes. These are required because the history command uses
+``argparse`` to parse the command line arguments. As described in the `argparse
+documentation <https://docs.python.org/3/library/argparse.html>`_ , ``-3:`` is
+an option, not an argument:
+
+ If you have positional arguments that must begin with - and don’t look
+ like negative numbers, you can insert the pseudo-argument '--' which tells
+ parse_args() that everything after that is a positional argument:
+
+There is no zeroth command, so don't ask for it. If you are a python
+programmer, you've probably noticed this looks a lot like the slice syntax for
+lists and arrays. It is, with the exception that the first history command is
+1, where the first element in a python array is 0.
+
+Besides selecting previous commands by number, you can also search for them.
+You can use a simple string search::
+
+ (Cmd) history two
+ 2 alias create two !echo two
+
+Or a regular expression search by enclosing your regex in slashes::
+
+ (Cmd) history '/te\ +th/'
+ 3 alias create three !echo three
+
+If your regular expression contains any characters that ``argparse`` finds
+interesting, like dash or plus, you also need to enclose your regular
+expression in quotation marks.
+
+This all sounds great, but doesn't it seem like a bit of overkill to have all
+these ways to select commands if all we can do is display them? Turns out,
+displaying history commands is just the beginning. The history command can
+perform many other actions:
+
+- running previously entered commands
+- saving previously entered commands to a text file
+- opening previously entered commands in your favorite text editor
+- running previously entered commands, saving the commands and their output
+ to a text file
+- clearing the history of entered commands
+
+Each of these actions is invoked using a command line option. The ``-r`` or
+``--run`` option runs one or more previously entered commands. To run command
+number 1::
+
+ (Cmd) history --run 1
+
+To rerun the last two commands (there's that double dash again to make argparse
+stop looking for options)::
+
+ (Cmd) history -r -- -2:
+
+Say you want to re-run some previously entered commands, but you would really
+like to make a few changes to them before doing so. When you use the ``-e`` or
+``--edit`` option, ``history`` will write the selected commands out to a text
+file, and open that file with a text editor. You make whatever changes,
+additions, or deletions, you want. When you leave the text editor, all the
+commands in the file are executed. To edit and then re-run commands 2-4 you
+would::
+
+ (Cmd) history --edit 2:4
+
+If you want to save the commands to a text file, but not edit and re-run them,
+use the ``-o`` or ``--output-file`` option. This is a great way to create
+:ref:`scripts`, which can be executed using the ``run_script`` command. To
+save the first 5 commands entered in this session to a text file::
+
+ (Cmd) history :5 -o history.txt
+
+The ``history`` command can also save both the commands and their output to a
+text file. This is called a transcript. See
+:ref:`features/transcripts:Transcripts` for more information on how transcripts
+work, and what you can use them for. To create a transcript use the ``-t`` or
+``--transcription`` option::
+
+ (Cmd) history 2:3 --transcript transcript.txt
+
+The ``--transcript`` option implies ``--run``: the commands must be re-run in
+order to capture their output to the transcript file.
+
+The last action the history command can perform is to clear the command history
+using ``-c`` or ``--clear``::
+
+ (Cmd) history -c
+
+In addition to these five actions, the ``history`` command also has some
+options to control how the output is formatted. With no arguments, the
+``history`` command displays the command number before each command. This is
+great when displaying history to the screen because it gives you an easy
+reference to identify previously entered commands. However, when creating a
+script or a transcript, the command numbers would prevent the script from
+loading properly. The ``-s`` or ``--script`` option instructs the ``history``
+command to suppress the line numbers. This option is automatically set by the
+``--output-file``, ``--transcript``, and ``--edit`` options. If you want to
+output the history commands with line numbers to a file, you can do it with
+output redirection::
+
+ (Cmd) history 1:4 > history.txt
+
+You might use ``-s`` or ``--script`` on it's own if you want to display history
+commands to the screen without line numbers, so you can copy them to the
+clipboard::
+
+ (Cmd) history -s 1:3
+
+``cmd2`` supports both aliases and macros, which allow you to substitute a
+short, more convenient input string with a longer replacement string. Say we
+create an alias like this, and then use it::
+
+ (Cmd) alias create ls shell ls -aF
+ Alias 'ls' created
+ (Cmd) ls -d h*
+ history.txt htmlcov/
+
+By default, the ``history`` command shows exactly what we typed::
+
+ (Cmd) history
+ 1 alias create ls shell ls -aF
+ 2 ls -d h*
+
+There are two ways to modify that display so you can see what aliases and
+macros were expanded to. The first is to use ``-x`` or ``--expanded``. These
+options show the expanded command instead of the entered command::
+
+ (Cmd) history -x
+ 1 alias create ls shell ls -aF
+ 2 shell ls -aF -d h*
+
+If you want to see both the entered command and the expanded command, use the
+``-v`` or ``--verbose`` option::
+
+ (Cmd) history -v
+ 1 alias create ls shell ls -aF
+ 2 ls -d h*
+ 2x shell ls -aF -d h*
+
+If the entered command had no expansion, it is displayed as usual. However, if
+there is some change as the result of expanding macros and aliases, then the
+entered command is displayed with the number, and the expanded command is
+displayed with the number followed by an ``x``.
+
diff --git a/docs/hooks.rst b/docs/features/hooks.rst
index 5db97fe5..17f2884e 100644
--- a/docs/hooks.rst
+++ b/docs/features/hooks.rst
@@ -1,7 +1,5 @@
-.. cmd2 documentation for application and command lifecycle and the available hooks
-
-cmd2 Application Lifecycle and Hooks
-====================================
+Hooks
+=====
The typical way of starting a cmd2 application is as follows::
@@ -17,6 +15,7 @@ There are several pre-existing methods and attributes which you can tweak to
control the overall behavior of your application before, during, and after the
command processing loop.
+
Application Lifecycle Hooks
---------------------------
@@ -54,9 +53,9 @@ value is ignored.
Application Lifecycle Attributes
--------------------------------
-There are numerous attributes of and arguments to ``cmd2.Cmd`` which have
-a significant effect on the application behavior upon entering or during the
-main loop. A partial list of some of the more important ones is presented here:
+There are numerous attributes of and arguments to ``cmd2.Cmd`` which have a
+significant effect on the application behavior upon entering or during the main
+loop. A partial list of some of the more important ones is presented here:
- **intro**: *str* - if provided this serves as the intro banner printed once
at start of application, after ``preloop`` runs
@@ -87,7 +86,8 @@ the application exits:
#. Add statement to history
#. Call `do_command` method
#. Call methods registered with `register_postcmd_hook()`
-#. Call `postcmd(stop, statement)` - for backwards compatibility with ``cmd.Cmd``
+#. Call `postcmd(stop, statement)` - for backwards compatibility with
+ ``cmd.Cmd``
#. Stop timer and display the elapsed time
#. Stop redirecting output if it was redirected
#. Call methods registered with `register_cmdfinalization_hook()`
@@ -114,8 +114,9 @@ If a hook raises any other exception:
Specific types of hook methods have additional options as described below.
+
Postparsing Hooks
-^^^^^^^^^^^^^^^^^
+-----------------
Postparsing hooks are called after the user input has been parsed but before
execution of the command. These hooks can be used to:
@@ -140,10 +141,10 @@ To define and register a postparsing hook, do the following::
# is available as params.statement
return params
-``register_postparsing_hook()`` checks the method signature of the passed callable,
-and raises a ``TypeError`` if it has the wrong number of parameters. It will
-also raise a ``TypeError`` if the passed parameter and return value are not annotated
-as ``PostparsingData``.
+``register_postparsing_hook()`` checks the method signature of the passed
+callable, and raises a ``TypeError`` if it has the wrong number of parameters.
+It will also raise a ``TypeError`` if the passed parameter and return value are
+not annotated as ``PostparsingData``.
The hook method will be passed one parameter, a ``PostparsingData`` object
which we will refer to as ``params``. ``params`` contains two attributes.
@@ -158,17 +159,17 @@ method may modify the attributes of the object to influece the behavior of
the application. If ``params.stop`` is set to true, a fatal failure is
triggered prior to execution of the command, and the application exits.
-To modify the user input, you create a new ``Statement`` object and return it in
-``params.statement``. Don't try and directly modify the contents of a
-``Statement`` object, there be dragons. Instead, use the various attributes in a
-``Statement`` object to construct a new string, and then parse that string to
+To modify the user input, you create a new ``Statement`` object and return it
+in ``params.statement``. Don't try and directly modify the contents of a
+``Statement`` object, there be dragons. Instead, use the various attributes in
+a ``Statement`` object to construct a new string, and then parse that string to
create a new ``Statement`` object.
-``cmd2.Cmd()`` uses an instance of ``cmd2.StatementParser`` to parse user input.
-This instance has been configured with the proper command terminators, multiline
-commands, and other parsing related settings. This instance is available as the
-``self.statement_parser`` attribute. Here's a simple example which shows the
-proper technique::
+``cmd2.Cmd()`` uses an instance of ``cmd2.StatementParser`` to parse user
+input. This instance has been configured with the proper command terminators,
+multiline commands, and other parsing related settings. This instance is
+available as the ``self.statement_parser`` attribute. Here's a simple example
+which shows the proper technique::
def myhookmethod(self, params: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
if not '|' in params.statement.raw:
@@ -186,7 +187,7 @@ attribute set to ``True``:
Precommand Hooks
-^^^^^^^^^^^^^^^^^
+----------------
Precommand hooks can modify the user input, but can not request the application
terminate. If your hook needs to be able to exit the application, you should
@@ -215,21 +216,22 @@ different properties (see above). If you do so, assign your new ``Statement``
object to ``data.statement``.
The precommand hook must return a ``PrecommandData`` object. You don't have to
-create this object from scratch, you can just return the one passed into the hook.
+create this object from scratch, you can just return the one passed into the
+hook.
After all registered precommand hooks have been called,
-``self.precmd(statement)`` will be called. To retain full backward compatibility
-with ``cmd.Cmd``, this method is passed a ``Statement``, not a
+``self.precmd(statement)`` will be called. To retain full backward
+compatibility with ``cmd.Cmd``, this method is passed a ``Statement``, not a
``PrecommandData`` object.
Postcommand Hooks
-^^^^^^^^^^^^^^^^^^
+-----------------
Once the command method has returned (i.e. the ``do_command(self, statement)
method`` has been called and returns, all postcommand hooks are called. If
-output was redirected by the user, it is still redirected, and the command timer
-is still running.
+output was redirected by the user, it is still redirected, and the command
+timer is still running.
Here's how to define and register a postcommand hook::
@@ -241,24 +243,25 @@ Here's how to define and register a postcommand hook::
def myhookmethod(self, data: cmd2.plugin.PostcommandData) -> cmd2.plugin.PostcommandData:
return data
-Your hook will be passed a ``PostcommandData`` object, which has a ``statement``
-attribute that describes the command which was executed. If your postcommand
-hook method gets called, you are guaranteed that the command method was called,
-and that it didn't raise an exception.
+Your hook will be passed a ``PostcommandData`` object, which has a
+``statement`` attribute that describes the command which was executed. If your
+postcommand hook method gets called, you are guaranteed that the command method
+was called, and that it didn't raise an exception.
If any postcommand hook raises an exception, the exception will be displayed to
the user, and no further postcommand hook methods will be called. Command
finalization hooks, if any, will be called.
After all registered postcommand hooks have been called,
-``self.postcmd(statement)`` will be called to retain full backward compatibility
-with ``cmd.Cmd``.
+``self.postcmd(statement)`` will be called to retain full backward
+compatibility with ``cmd.Cmd``.
-If any postcommand hook (registered or ``self.postcmd()``) returns a ``PostcommandData`` object
-with the stop attribute set to ``True``, subsequent postcommand hooks will still be called, as
-will the command finalization hooks, but once those hooks have all been called, the application
-will terminate. Likewise, if ``self.postcmd()`` returns ``True``, the command finalization hooks
-will be called before the application terminates.
+If any postcommand hook (registered or ``self.postcmd()``) returns a
+``PostcommandData`` object with the stop attribute set to ``True``, subsequent
+postcommand hooks will still be called, as will the command finalization hooks,
+but once those hooks have all been called, the application will terminate.
+Likewise, if ``self.postcmd()`` returns ``True``, the command finalization
+hooks will be called before the application terminates.
Any postcommand hook can change the value of the ``stop`` parameter before
returning it, and the modified value will be passed to the next postcommand
@@ -270,10 +273,10 @@ compelling reason to do otherwise.
Command Finalization Hooks
-^^^^^^^^^^^^^^^^^^^^^^^^^^
+--------------------------
-Command finalization hooks are called even if one of the other types of hooks or
-the command method raise an exception. Here's how to create and register a
+Command finalization hooks are called even if one of the other types of hooks
+or the command method raise an exception. Here's how to create and register a
command finalization hook::
class App(cmd2.Cmd):
@@ -284,20 +287,22 @@ command finalization hook::
def myhookmethod(self, stop, statement):
return stop
-Command Finalization hooks must check whether the statement object is ``None``. There are certain circumstances where these hooks may be called before the statement has been parsed, so you can't always rely on having a statement.
+Command Finalization hooks must check whether the statement object is ``None``.
+There are certain circumstances where these hooks may be called before the
+statement has been parsed, so you can't always rely on having a statement.
If any prior postparsing or precommand hook has requested the application to
terminate, the value of the ``stop`` parameter passed to the first command
-finalization hook will be ``True``. Any command finalization hook can change the
-value of the ``stop`` parameter before returning it, and the modified value will
-be passed to the next command finalization hook. The value returned by the final
-command finalization hook will determine whether the application terminates or
-not.
+finalization hook will be ``True``. Any command finalization hook can change
+the value of the ``stop`` parameter before returning it, and the modified value
+will be passed to the next command finalization hook. The value returned by the
+final command finalization hook will determine whether the application
+terminates or not.
This approach to command finalization hooks can be powerful, but it can also
-cause problems. If your hook blindly returns ``False``, a prior hook's requst to
-exit the application will not be honored. It's best to return the value you were
-passed unless you have a compelling reason to do otherwise.
+cause problems. If your hook blindly returns ``False``, a prior hook's requst
+to exit the application will not be honored. It's best to return the value you
+were passed unless you have a compelling reason to do otherwise.
If any command finalization hook raises an exception, no more command
finalization hooks will be called. If the last hook to return a value returned
diff --git a/docs/features/index.rst b/docs/features/index.rst
new file mode 100644
index 00000000..3087031f
--- /dev/null
+++ b/docs/features/index.rst
@@ -0,0 +1,26 @@
+Features
+========
+
+.. toctree::
+ :maxdepth: 1
+
+ argument_processing
+ clipboard
+ commands
+ completion
+ disable_commands
+ embedded_python_shells
+ generating_output
+ help
+ history
+ hooks
+ initialization
+ multiline_commands
+ os
+ plugins
+ prompt
+ scripting
+ settings
+ shortcuts_aliases_macros
+ startup_commands
+ transcripts
diff --git a/docs/features/initialization.rst b/docs/features/initialization.rst
new file mode 100644
index 00000000..f167a55a
--- /dev/null
+++ b/docs/features/initialization.rst
@@ -0,0 +1,5 @@
+Initialization
+==============
+
+Show how to properly initialize a ``cmd2`` app, showing parameters, sequencing,
+etc.
diff --git a/docs/features/multiline_commands.rst b/docs/features/multiline_commands.rst
new file mode 100644
index 00000000..d6502058
--- /dev/null
+++ b/docs/features/multiline_commands.rst
@@ -0,0 +1,12 @@
+Multiline Commands
+==================
+
+Command input may span multiple lines for the commands whose names are listed
+in the ``multiline_commands`` argument to ``cmd2.Cmd.__init__()``. These
+commands will be executed only after the user has entered a *terminator*. By
+default, the command terminator is ``;``; specifying the ``terminators``
+optional argument to ``cmd2.Cmd.__init__()`` allows different terminators. A
+blank line is *always* considered a command terminator (cannot be overridden).
+
+In multiline commands, output redirection characters like ``>`` and ``|`` are
+part of the command arguments unless they appear after the terminator.
diff --git a/docs/features/os.rst b/docs/features/os.rst
new file mode 100644
index 00000000..780e99f2
--- /dev/null
+++ b/docs/features/os.rst
@@ -0,0 +1,11 @@
+Integrating with the OS
+=======================
+
+- how to redirect output
+- executing OS commands from within ``cmd2``
+- editors
+- paging
+- exit codes
+- Automation and calling cmd2 from other CLI/CLU tools via commands at
+ invocation and quit
+
diff --git a/docs/features/plugins.rst b/docs/features/plugins.rst
new file mode 100644
index 00000000..253666e7
--- /dev/null
+++ b/docs/features/plugins.rst
@@ -0,0 +1,3 @@
+Plugins
+=======
+
diff --git a/docs/features/prompt.rst b/docs/features/prompt.rst
new file mode 100644
index 00000000..40c50d2b
--- /dev/null
+++ b/docs/features/prompt.rst
@@ -0,0 +1,42 @@
+Prompt
+======
+
+``cmd2`` can issue a prompt before soliciting user input.
+
+Asynchronous Feedback
+---------------------
+
+``cmd2`` provides two functions to provide asynchronous feedback to the user
+without interfering with the command line. This means the feedback is provided
+to the user when they are still entering text at the prompt. To use this
+functionality, the application must be running in a terminal that supports
+VT100 control characters and readline. Linux, Mac, and Windows 10 and greater
+all support these.
+
+async_alert()
+ Used to display an important message to the user while they are at the
+ prompt in between commands. To the user it appears as if an alert message
+ is printed above the prompt and their current input text and cursor
+ location is left alone.
+
+async_update_prompt()
+ Updates the prompt while the user is still typing at it. This is good for
+ alerting the user to system changes dynamically in between commands. For
+ instance you could alter the color of the prompt to indicate a system
+ status or increase a counter to report an event.
+
+``cmd2`` also provides a function to change the title of the terminal window.
+This feature requires the application be running in a terminal that supports
+VT100 control characters. Linux, Mac, and Windows 10 and greater all support
+these.
+
+set_window_title()
+ Sets the terminal window title
+
+
+The easiest way to understand these functions is to see the AsyncPrinting_
+example for a demonstration.
+
+.. _AsyncPrinting: https://github.com/python-cmd2/cmd2/blob/master/examples/async_printing.py
+
+
diff --git a/docs/features/scripting.rst b/docs/features/scripting.rst
new file mode 100644
index 00000000..73566cde
--- /dev/null
+++ b/docs/features/scripting.rst
@@ -0,0 +1,20 @@
+Scripting
+=========
+
+Document use cases and commands for ``run_script`` and ``run_pyscript``
+
+Comments
+--------
+
+Any command line input where the first non-whitespace character is a `#` will
+be treated as a comment. This means any `#` character appearing later in the
+command will be treated as a literal. The same applies to a `#` in the middle
+of a multiline command, even if it is the first character on a line.
+
+Comments can be useful in :ref:`scripts`, but would be pointless within an
+interactive session.
+
+::
+
+ (Cmd) # this is a comment
+ (Cmd) this # is not a comment
diff --git a/docs/features/settings.rst b/docs/features/settings.rst
new file mode 100644
index 00000000..696b085f
--- /dev/null
+++ b/docs/features/settings.rst
@@ -0,0 +1,6 @@
+Settings
+========
+
+- current settings and what they do
+- how a developer can add their own
+- how to hide built in settings from a user
diff --git a/docs/features/shortcuts_aliases_macros.rst b/docs/features/shortcuts_aliases_macros.rst
new file mode 100644
index 00000000..7b91a4b5
--- /dev/null
+++ b/docs/features/shortcuts_aliases_macros.rst
@@ -0,0 +1,13 @@
+Shortcuts, Aliases, and Macros
+==============================
+
+Shortcuts
+---------
+
+
+Aliases
+-------
+
+
+Macros
+------
diff --git a/docs/features/startup_commands.rst b/docs/features/startup_commands.rst
new file mode 100644
index 00000000..1efcc014
--- /dev/null
+++ b/docs/features/startup_commands.rst
@@ -0,0 +1,2 @@
+Startup Commands
+================
diff --git a/docs/transcript.rst b/docs/features/transcripts.rst
index 089ab704..18daeb78 100644
--- a/docs/transcript.rst
+++ b/docs/features/transcripts.rst
@@ -1,6 +1,5 @@
-========================
-Transcript based testing
-========================
+Transcripts
+===========
A transcript is both the input and output of a successful session of a
``cmd2``-based app which is saved to a text file. With no extra work on your
@@ -10,12 +9,12 @@ from commands that produce dynamic or variable output.
.. highlight:: none
-Creating a transcript
-=====================
-Automatically from history
---------------------------
-A transcript can automatically generated based upon commands previously executed in the *history* using ``history -t``::
+Creating From History
+---------------------
+
+A transcript can automatically generated based upon commands previously
+executed in the *history* using ``history -t``::
(Cmd) help
...
@@ -28,23 +27,29 @@ This is by far the easiest way to generate a transcript.
.. warning::
- Make sure you use the **poutput()** method in your ``cmd2`` application for generating command output. This method
- of the ``cmd2.Cmd`` class ensure that output is properly redirected when redirecting to a file, piping to a shell
- command, and when generating a transcript.
+ Make sure you use the **poutput()** method in your ``cmd2`` application for
+ generating command output. This method of the ``cmd2.Cmd`` class ensure
+ that output is properly redirected when redirecting to a file, piping to a
+ shell command, and when generating a transcript.
+
+
+Creating From A Script File
+---------------------------
-Automatically from a script file
---------------------------------
-A transcript can also be automatically generated from a script file using ``run_script -t``::
+A transcript can also be automatically generated from a script file using
+``run_script -t``::
(Cmd) run_script scripts/script.txt -t transcript.txt
2 commands and their outputs saved to transcript file 'transcript.txt'
(Cmd)
-This is a particularly attractive option for automatically regenerating transcripts for regression testing as your ``cmd2``
-application changes.
+This is a particularly attractive option for automatically regenerating
+transcripts for regression testing as your ``cmd2`` application changes.
+
+
+Creating Manually
+-----------------
-Manually
---------
Here's a transcript created from ``python examples/example.py``::
(Cmd) say -r 3 Goodnight, Gracie
@@ -83,7 +88,8 @@ lines of the transcript as comments::
maybe we could like go to er lunch right?
In this example I've used several different commenting styles, and even bare
-text. It doesn't matter what you put on those beginning lines. Everything before::
+text. It doesn't matter what you put on those beginning lines. Everything
+before::
(Cmd) say -r 3 Goodnight, Gracie
@@ -91,7 +97,7 @@ will be ignored.
Regular Expressions
-===================
+-------------------
If we used the above transcript as-is, it would likely fail. As you can see,
the ``mumble`` command doesn't always return the same thing: it inserts random
@@ -106,9 +112,10 @@ and are surrounded by slashes::
/.*\bmaybe\b.*\bcould\b.*\blunch\b.*/
Without creating a tutorial on regular expressions, this one matches anything
-that has the words ``maybe``, ``could``, and ``lunch`` in that order. It doesn't
-ensure that ``we`` or ``go`` or ``to`` appear in the output, but it does work if
-mumble happens to add words to the beginning or the end of the output.
+that has the words ``maybe``, ``could``, and ``lunch`` in that order. It
+doesn't ensure that ``we`` or ``go`` or ``to`` appear in the output, but it
+does work if mumble happens to add words to the beginning or the end of the
+output.
Since the output could be multiple lines long, ``cmd2`` uses multiline regular
expression matching, and also uses the ``DOTALL`` flag. These two flags subtly
@@ -117,7 +124,8 @@ change the behavior of commonly used special characters like ``.``, ``^`` and
documentation <https://docs.python.org/3/library/re.html>`_.
If your output has slashes in it, you will need to escape those slashes so the
-stuff between them is not interpred as a regular expression. In this transcript::
+stuff between them is not interpred as a regular expression. In this
+transcript::
(Cmd) say cd /usr/local/lib/python3.6/site-packages
/usr/local/lib/python3.6/site-packages
@@ -153,13 +161,13 @@ the path instead of specifying it verbatim, or we can escape the slashes::
of a failing transcript is an extra or missing newline.
If you are using regular expressions, be aware that depending on how you
- write your regex, the newlines after the regex may or may not matter.
- ``\Z`` matches *after* the newline at the end of the string, whereas
- ``$`` matches the end of the string *or* just before a newline.
+ write your regex, the newlines after the regex may or may not matter. ``\Z``
+ matches *after* the newline at the end of the string, whereas ``$`` matches
+ the end of the string *or* just before a newline.
-Running a transcript
-====================
+Running A Transcript
+--------------------
Once you have created a transcript, it's easy to have your application play it
back and check the output. From within the ``examples/`` directory::
@@ -178,8 +186,8 @@ output matches the expected result from the transcript.
.. note::
If you have set ``allow_cli_args`` to False in order to disable parsing of
- command line arguments at invocation, then the use of ``-t`` or ``--test``
- to run transcript testing is automatically disabled. In this case, you can
+ command line arguments at invocation, then the use of ``-t`` or ``--test`` to
+ run transcript testing is automatically disabled. In this case, you can
alternatively provide a value for the optional ``transcript_files`` when
constructing the instance of your ``cmd2.Cmd`` derived class in order to
cause a transcript test to run::
diff --git a/docs/freefeatures.rst b/docs/freefeatures.rst
index a06bab90..25fe3be9 100644
--- a/docs/freefeatures.rst
+++ b/docs/freefeatures.rst
@@ -12,38 +12,30 @@ simply by replacing ``import cmd`` with ``import cmd2 as cmd``.
Script files
============
-Text files can serve as scripts for your ``cmd2``-based
-application, with the ``run_script``, ``_relative_run_script``, and ``edit`` commands.
+Text files can serve as scripts for your ``cmd2``-based application, with the
+``run_script``, ``_relative_run_script``, and ``edit`` commands.
Both ASCII and UTF-8 encoded unicode text files are supported.
-Simply include one command per line, typed exactly as you would inside a ``cmd2`` application.
+Simply include one command per line, typed exactly as you would inside a
+``cmd2`` application.
.. automethod:: cmd2.cmd2.Cmd.do_run_script
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.do__relative_run_script
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.do_edit
+ :noindex:
-Comments
-========
-
-Any command line input where the first non-whitespace character is a `#` will be treated as a comment.
-This means any `#` character appearing later in the command will be treated as a literal. The same
-applies to a `#` in the middle of a multiline command, even if it is the first character on a line.
-
-Comments can be useful in :ref:`scripts`, but would be pointless within an interactive session.
-
-::
-
- (Cmd) # this is a comment
- (Cmd) this # is not a comment
-
Startup Initialization Script
=============================
-You can execute commands from a startup initialization script by passing a file path to the ``startup_script``
-argument to the ``cmd2.Cmd.__init__()`` method like so::
+
+You can execute commands from a startup initialization script by passing a file
+path to the ``startup_script`` argument to the ``cmd2.Cmd.__init__()`` method
+like so::
class StartupApp(cmd2.Cmd):
def __init__(self):
@@ -93,45 +85,51 @@ As in a Unix shell, output of a command can be redirected:
- appended to a file with ``>>``, as in ``mycommand args >> filename.txt``
- piped (``|``) as input to operating-system commands, as in
``mycommand args | wc``
- - sent to the operating system paste buffer, by ending with a bare ``>``, as in ``mycommand args >``. You can even append output to the current contents of the paste buffer by ending your command with ``>>``.
+ - sent to the operating system paste buffer, by ending with a bare ``>``, as
+ in ``mycommand args >``. You can even append output to the current contents
+ of the paste buffer by ending your command with ``>>``.
.. note::
- If you wish to disable cmd2's output redirection and pipes features, you can do so by setting the ``allow_redirection``
- attribute of your ``cmd2.Cmd`` class instance to ``False``. This would be useful, for example, if you want to restrict
- the ability for an end user to write to disk or interact with shell commands for security reasons::
+ If you wish to disable cmd2's output redirection and pipes features, you can
+ do so by setting the ``allow_redirection`` attribute of your ``cmd2.Cmd``
+ class instance to ``False``. This would be useful, for example, if you want
+ to restrict the ability for an end user to write to disk or interact with
+ shell commands for security reasons::
from cmd2 import Cmd
class App(Cmd):
def __init__(self):
self.allow_redirection = False
- cmd2's parser will still treat the ``>``, ``>>``, and `|` symbols as output redirection and pipe symbols and will strip
- arguments after them from the command line arguments accordingly. But output from a command will not be redirected
- to a file or piped to a shell command.
+ cmd2's parser will still treat the ``>``, ``>>``, and `|` symbols as output
+ redirection and pipe symbols and will strip arguments after them from the
+ command line arguments accordingly. But output from a command will not be
+ redirected to a file or piped to a shell command.
-If you need to include any of these redirection characters in your command,
-you can enclose them in quotation marks, ``mycommand 'with > in the argument'``.
+If you need to include any of these redirection characters in your command, you
+can enclose them in quotation marks, ``mycommand 'with > in the argument'``.
Python
======
The ``py`` command will run its arguments as a Python command. Entered without
-arguments, it enters an interactive Python session. The session can call "back"
-to your application through the name defined in ``self.pyscript_name`` (defaults
-to ``app``). This wrapper provides access to execute commands in your cmd2
-application while maintaining isolation.
+arguments, it enters an interactive Python session. The session can call
+"back" to your application through the name defined in ``self.pyscript_name``
+(defaults to ``app``). This wrapper provides access to execute commands in
+your cmd2 application while maintaining isolation.
You may optionally enable full access to to your application by setting
``locals_in_py`` to ``True``. Enabling this flag adds ``self`` to the python
session, which is a reference to your Cmd2 application. This can be useful for
debugging your application. To prevent users from enabling this ability
-manually you'll need to remove ``locals_in_py`` from the ``settable`` dictionary.
+manually you'll need to remove ``locals_in_py`` from the ``settable``
+dictionary.
-The ``app`` object (or your custom name) provides access to application commands
-through raw commands. For example, any application command call be called with
-``app("<command>")``.
+The ``app`` object (or your custom name) provides access to application
+commands through raw commands. For example, any application command call be
+called with ``app("<command>")``.
::
@@ -165,28 +163,31 @@ More Python examples:
>>> quit()
Python was here >
-Using the ``py`` command is tightly integrated with your main ``cmd2`` application
-and any variables created or changed will persist for the life of the application::
+Using the ``py`` command is tightly integrated with your main ``cmd2``
+application and any variables created or changed will persist for the life of
+the application::
(Cmd) py x = 5
(Cmd) py print(x)
5
-The ``py`` command also allows you to run Python scripts via ``py run('myscript.py')``.
-This provides a more complicated and more powerful scripting capability than that
-provided by the simple text file scripts discussed in :ref:`scripts`. Python scripts can include
-conditional control flow logic. See the **python_scripting.py** ``cmd2`` application and
-the **script_conditional.py** script in the ``examples`` source code directory for an
-example of how to achieve this in your own applications.
+The ``py`` command also allows you to run Python scripts via ``py
+run('myscript.py')``. This provides a more complicated and more powerful
+scripting capability than that provided by the simple text file scripts
+discussed in :ref:`scripts`. Python scripts can include conditional control
+flow logic. See the **python_scripting.py** ``cmd2`` application and the
+**script_conditional.py** script in the ``examples`` source code directory for
+an example of how to achieve this in your own applications.
-Using ``py`` to run scripts directly is considered deprecated. The newer ``run_pyscript`` command
-is superior for doing this in two primary ways:
+Using ``py`` to run scripts directly is considered deprecated. The newer
+``run_pyscript`` command is superior for doing this in two primary ways:
- it supports tab-completion of file system paths
- it has the ability to pass command-line arguments to the scripts invoked
-There are no disadvantages to using ``run_pyscript`` as opposed to ``py run()``. A simple example
-of using ``run_pyscript`` is shown below along with the arg_printer_ script::
+There are no disadvantages to using ``run_pyscript`` as opposed to ``py
+run()``. A simple example of using ``run_pyscript`` is shown below along with
+the arg_printer_ script::
(Cmd) run_pyscript examples/scripts/arg_printer.py foo bar baz
Running Python script 'arg_printer.py' which was called with 3 arguments
@@ -196,8 +197,10 @@ of using ``run_pyscript`` is shown below along with the arg_printer_ script::
.. note::
- If you want to be able to pass arguments with spaces to commands, then we strongly recommend using one of the decorators,
- such as ``with_argument_list``. ``cmd2`` will pass your **do_*** methods a list of arguments in this case.
+ If you want to be able to pass arguments with spaces to commands, then we
+ strongly recommend using one of the decorators, such as
+ ``with_argument_list``. ``cmd2`` will pass your **do_*** methods a list of
+ arguments in this case.
When using this decorator, you can then put arguments in quotes like so::
@@ -205,13 +208,15 @@ of using ``run_pyscript`` is shown below along with the arg_printer_ script::
(Cmd) lprint foo "bar baz"
lprint was called with the following list of arguments: ['foo', 'bar baz']
-.. _arg_printer: https://github.com/python-cmd2/cmd2/blob/master/examples/scripts/arg_printer.py
+.. _arg_printer:
+ https://github.com/python-cmd2/cmd2/blob/master/examples/scripts/arg_printer.py
+
IPython (optional)
==================
-**If** IPython_ is installed on the system **and** the ``cmd2.Cmd`` class
-is instantiated with ``use_ipython=True``, then the optional ``ipy`` command will
+**If** IPython_ is installed on the system **and** the ``cmd2.Cmd`` class is
+instantiated with ``use_ipython=True``, then the optional ``ipy`` command will
be present::
from cmd2 import Cmd
@@ -220,11 +225,11 @@ be present::
Cmd.__init__(self, use_ipython=True)
The ``ipy`` command enters an interactive IPython_ session. Similar to an
-interactive Python session, this shell can access your application instance via ``self`` and any changes
-to your application made via ``self`` will persist.
-However, any local or global variable created within the ``ipy`` shell will not persist.
-Within the ``ipy`` shell, you cannot call "back" to your application with ``cmd("")``, however you can run commands
-directly like so::
+interactive Python session, this shell can access your application instance via
+``self`` and any changes to your application made via ``self`` will persist.
+However, any local or global variable created within the ``ipy`` shell will not
+persist. Within the ``ipy`` shell, you cannot call "back" to your application
+with ``cmd("")``, however you can run commands directly like so::
self.onecmd_plus_hooks('help')
@@ -232,231 +237,14 @@ IPython_ provides many advantages, including:
* Comprehensive object introspection
* Get help on objects with ``?``
- * Extensible tab completion, with support by default for completion of python variables and keywords
+ * Extensible tab completion, with support by default for completion of
+ python variables and keywords
-The object introspection and tab completion make IPython particularly efficient for debugging as well as for interactive
-experimentation and data analysis.
+The object introspection and tab completion make IPython particularly efficient
+for debugging as well as for interactive experimentation and data analysis.
.. _IPython: http://ipython.readthedocs.io
-Searchable command history
-==========================
-
-All cmd_-based applications have access to previous commands with
-the up- and down- arrow keys.
-
-All cmd_-based applications on systems with the ``readline`` module
-also provide `Readline Emacs editing mode`_. With this you can, for example, use **Ctrl-r** to search backward through
-the readline history.
-
-``cmd2`` adds the option of making this history persistent via optional arguments to ``cmd2.Cmd.__init__()``:
-
-.. automethod:: cmd2.cmd2.Cmd.__init__
-
-``cmd2`` makes a third type of history access available with the ``history``
-command. Each time the user enters a command, ``cmd2`` saves the input. The
-``history`` command lets you do interesting things with that saved input. The
-examples to follow all assume that you have entered the following commands::
-
- (Cmd) alias create one !echo one
- Alias 'one' created
- (Cmd) alias create two !echo two
- Alias 'two' created
- (Cmd) alias create three !echo three
- Alias 'three' created
- (Cmd) alias create four !echo four
- Alias 'four' created
-
-In it's simplest form, the ``history`` command displays previously entered
-commands. With no additional arguments, it displays all previously entered
-commands::
-
- (Cmd) history
- 1 alias create one !echo one
- 2 alias create two !echo two
- 3 alias create three !echo three
- 4 alias create four !echo four
-
-If you give a positive integer as an argument, then it only displays the
-specified command::
-
- (Cmd) history 4
- 4 alias create four !echo four
-
-If you give a negative integer *N* as an argument, then it display the *Nth*
-last command. For example, if you give ``-1`` it will display the last command
-you entered. If you give ``-2`` it will display the next to last command you
-entered, and so forth::
-
- (Cmd) history -2
- 3 alias create three !echo three
-
-You can use a similar mechanism to display a range of commands. Simply give two
-command numbers separated by ``..`` or ``:``, and you will see all commands
-between, and including, those two numbers::
-
- (Cmd) history 1:3
- 1 alias create one !echo one
- 2 alias create two !echo two
- 3 alias create three !echo three
-
-If you omit the first number, it will start at the beginning. If you omit the
-last number, it will continue to the end::
-
- (Cmd) history :2
- 1 alias create one !echo one
- 2 alias create two !echo two
- (Cmd) history 2:
- 2 alias create two !echo two
- 3 alias create three !echo three
- 4 alias create four !echo four
-
-If you want to display the last three commands entered::
-
- (Cmd) history -- -3:
- 2 alias create two !echo two
- 3 alias create three !echo three
- 4 alias create four !echo four
-
-Notice the double dashes. These are required because the history command uses
-``argparse`` to parse the command line arguments. As described in the `argparse
-documentation <https://docs.python.org/3/library/argparse.html>`_ , ``-3:`` is
-an option, not an argument:
-
- If you have positional arguments that must begin with - and don’t look like
- negative numbers, you can insert the pseudo-argument '--' which tells
- parse_args() that everything after that is a positional argument:
-
-There is no zeroth command, so don't ask for it. If you are a python programmer,
-you've probably noticed this looks a lot like the slice syntax for lists and
-arrays. It is, with the exception that the first history command is 1, where the
-first element in a python array is 0.
-
-Besides selecting previous commands by number, you can also search for them. You
-can use a simple string search::
-
- (Cmd) history two
- 2 alias create two !echo two
-
-Or a regular expression search by enclosing your regex in slashes::
-
- (Cmd) history '/te\ +th/'
- 3 alias create three !echo three
-
-If your regular expression contains any characters that ``argparse`` finds
-interesting, like dash or plus, you also need to enclose your regular expression
-in quotation marks.
-
-This all sounds great, but doesn't it seem like a bit of overkill to have all
-these ways to select commands if all we can do is display them? Turns out,
-displaying history commands is just the beginning. The history command can
-perform many other actions:
-
-- running previously entered commands
-- saving previously entered commands to a text file
-- opening previously entered commands in your favorite text editor
-- running previously entered commands, saving the commands and their output to a text file
-- clearing the history of entered commands
-
-Each of these actions is invoked using a command line option. The ``-r`` or
-``--run`` option runs one or more previously entered commands. To run command
-number 1::
-
- (Cmd) history --run 1
-
-To rerun the last two commands (there's that double dash again to make argparse
-stop looking for options)::
-
- (Cmd) history -r -- -2:
-
-Say you want to re-run some previously entered commands, but you would really
-like to make a few changes to them before doing so. When you use the ``-e`` or
-``--edit`` option, ``history`` will write the selected commands out to a text
-file, and open that file with a text editor. You make whatever changes,
-additions, or deletions, you want. When you leave the text editor, all the
-commands in the file are executed. To edit and then re-run commands 2-4 you
-would::
-
- (Cmd) history --edit 2:4
-
-If you want to save the commands to a text file, but not edit and re-run them,
-use the ``-o`` or ``--output-file`` option. This is a great way to create
-:ref:`scripts`, which can be executed using the ``run_script`` command. To
-save the first 5 commands entered in this session to a text file::
-
- (Cmd) history :5 -o history.txt
-
-The ``history`` command can also save both the commands and their output to a
-text file. This is called a transcript. See :doc:`transcript` for more
-information on how transcripts work, and what you can use them for. To create a
-transcript use the ``-t`` or ``--transcription`` option::
-
- (Cmd) history 2:3 --transcript transcript.txt
-
-The ``--transcript`` option implies ``--run``: the commands must be re-run in
-order to capture their output to the transcript file.
-
-The last action the history command can perform is to clear the command history
-using ``-c`` or ``--clear``::
-
- (Cmd) history -c
-
-In addition to these five actions, the ``history`` command also has some options
-to control how the output is formatted. With no arguments, the ``history``
-command displays the command number before each command. This is great when
-displaying history to the screen because it gives you an easy reference to
-identify previously entered commands. However, when creating a script or a
-transcript, the command numbers would prevent the script from loading properly.
-The ``-s`` or ``--script`` option instructs the ``history`` command to suppress
-the line numbers. This option is automatically set by the ``--output-file``,
-``--transcript``, and ``--edit`` options. If you want to output the history
-commands with line numbers to a file, you can do it with output redirection::
-
- (Cmd) history 1:4 > history.txt
-
-You might use ``-s`` or ``--script`` on it's own if you want to display history
-commands to the screen without line numbers, so you can copy them to the
-clipboard::
-
- (Cmd) history -s 1:3
-
-``cmd2`` supports both aliases and macros, which allow you to substitute a
-short, more convenient input string with a longer replacement string. Say we
-create an alias like this, and then use it::
-
- (Cmd) alias create ls shell ls -aF
- Alias 'ls' created
- (Cmd) ls -d h*
- history.txt htmlcov/
-
-By default, the ``history`` command shows exactly what we typed::
-
- (Cmd) history
- 1 alias create ls shell ls -aF
- 2 ls -d h*
-
-There are two ways to modify that display so you can see what aliases and macros
-were expanded to. The first is to use ``-x`` or ``--expanded``. These options
-show the expanded command instead of the entered command::
-
- (Cmd) history -x
- 1 alias create ls shell ls -aF
- 2 shell ls -aF -d h*
-
-If you want to see both the entered command and the expanded command, use the
-``-v`` or ``--verbose`` option::
-
- (Cmd) history -v
- 1 alias create ls shell ls -aF
- 2 ls -d h*
- 2x shell ls -aF -d h*
-
-If the entered command had no expansion, it is displayed as usual. However, if
-there is some change as the result of expanding macros and aliases, then the
-entered command is displayed with the number, and the expanded command is
-displayed with the number followed by an ``x``.
-
-.. _`Readline Emacs editing mode`: http://readline.kablamo.org/emacs.html
Quitting the application
========================
@@ -472,8 +260,10 @@ Several generically useful commands are defined
with automatically included ``do_`` methods.
.. automethod:: cmd2.cmd2.Cmd.do_quit
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.do_shell
+ :noindex:
( ``!`` is a shortcut for ``shell``; thus ``!ls``
is equivalent to ``shell ls``.)
@@ -485,7 +275,7 @@ A transcript is both the input and output of a successful session of a
``cmd2``-based app which is saved to a text file. The transcript can be played
back into the app as a unit test.
-.. code-block:: none
+.. code-block:: text
$ python example.py --test transcript_regex.txt
.
@@ -494,13 +284,14 @@ back into the app as a unit test.
OK
-See :doc:`transcript` for more details.
+See :doc:`features/transcripts` for more details.
Tab-Completion
==============
-``cmd2`` adds tab-completion of file system paths for all built-in commands where it makes sense, including:
+``cmd2`` adds tab-completion of file system paths for all built-in commands
+where it makes sense, including:
- ``edit``
- ``run_pyscript``
@@ -509,19 +300,23 @@ Tab-Completion
``cmd2`` also adds tab-completion of shell commands to the ``shell`` command.
-Additionally, it is trivial to add identical file system path completion to your own custom commands. Suppose you
-have defined a custom command ``foo`` by implementing the ``do_foo`` method. To enable path completion for the ``foo``
-command, then add a line of code similar to the following to your class which inherits from ``cmd2.Cmd``::
+Additionally, it is trivial to add identical file system path completion to
+your own custom commands. Suppose you have defined a custom command ``foo`` by
+implementing the ``do_foo`` method. To enable path completion for the ``foo``
+command, then add a line of code similar to the following to your class which
+inherits from ``cmd2.Cmd``::
complete_foo = self.path_complete
-This will effectively define the ``complete_foo`` readline completer method in your class and make it utilize the same
-path completion logic as the built-in commands.
+This will effectively define the ``complete_foo`` readline completer method in
+your class and make it utilize the same path completion logic as the built-in
+commands.
-The built-in logic allows for a few more advanced path completion capabilities, such as cases where you only want to
-match directories. Suppose you have a custom command ``bar`` implemented by the ``do_bar`` method. You can enable
-path completion of directories only for this command by adding a line of code similar to the following to your class
-which inherits from ``cmd2.Cmd``::
+The built-in logic allows for a few more advanced path completion capabilities,
+such as cases where you only want to match directories. Suppose you have a
+custom command ``bar`` implemented by the ``do_bar`` method. You can enable
+path completion of directories only for this command by adding a line of code
+similar to the following to your class which inherits from ``cmd2.Cmd``::
# Make sure you have an "import functools" somewhere at the top
complete_bar = functools.partialmethod(cmd2.Cmd.path_complete, path_filter=os.path.isdir)
diff --git a/docs/index.rst b/docs/index.rst
index 5f9c4c3d..27432132 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,23 +1,16 @@
-.. cmd2 documentation master file, created by
- sphinx-quickstart on Wed Feb 10 12:05:28 2010.
- You can adapt this file completely to your liking, but it should at least
- contain the root `toctree` directive.
-
+====
cmd2
====
-A python package for building powerful command-line interpreter (CLI)
-programs. Extends the Python Standard Library's cmd_ package.
+.. default-domain:: py
.. _cmd: https://docs.python.org/3/library/cmd.html
-.. _`cmd2 project page`: https://github.com/python-cmd2/cmd2
-.. _`project bug tracker`: https://github.com/python-cmd2/cmd2/issues
+A python package for building powerful command-line interpreter (CLI)
+programs. Extends the Python Standard Library's cmd_ package.
The basic use of ``cmd2`` is identical to that of cmd_.
-.. highlight:: python
-
1. Create a subclass of ``cmd2.Cmd``. Define attributes and
``do_*`` methods to control its behavior. Throughout this documentation,
we will assume that you are naming your subclass ``App``::
@@ -31,51 +24,91 @@ The basic use of ``cmd2`` is identical to that of cmd_.
app = App()
app.cmdloop()
-.. note::
- The tab-completion feature provided by cmd_ relies on underlying capability provided by GNU readline or an
- equivalent library. Linux distros will almost always come with the required library installed.
- For macOS, we recommend using the `gnureadline <https://pypi.python.org/pypi/gnureadline>`_ Python module which includes
- a statically linked version of GNU readline. Alternatively on macOS the ``conda`` package manager that comes
- with the Anaconda Python distro can be used to install ``readline`` (preferably from conda-forge) or the
- `Homebrew <https://brew.sh>`_ package manager can be used to to install the ``readline`` package.
- For Windows, we recommend installing the `pyreadline <https://pypi.python.org/pypi/pyreadline>`_ Python module.
+Getting Started
+===============
-Resources
----------
+.. include:: overview/summary.rst
+
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+
+ overview/index
-* cmd_
-* `cmd2 project page`_
-* `project bug tracker`_
-* Florida PyCon 2017: `slides <https://docs.google.com/presentation/d/1LRmpfBt3V-pYQfgQHdczf16F3hcXmhK83tl77R6IJtE>`_, `video <https://www.youtube.com/watch?v=6m0RdpITaeY>`_
-These docs will refer to ``App`` as your ``cmd2.Cmd``
-subclass, and ``app`` as an instance of ``App``. Of
-course, in your program, you may name them whatever
-you want.
+Migrating from cmd
+==================
-Contents:
+[create links with short descriptions to the various migrating pages here]
.. toctree::
:maxdepth: 2
- install
- overview
- freefeatures
- settingchanges
- unfreefeatures
- transcript
- argument_processing
- integrating
- hooks
- alternatives
+ migrating/index
+
+
+Features
+========
+
+[create links with short descriptions to the various feature pages here]
+
+.. toctree::
+ :maxdepth: 2
+
+ features/index
+
-Compatibility
+API Reference
=============
-Tested and working with Python 3.5+ on Windows, macOS, and Linux.
+.. toctree::
+ :maxdepth: 2
+
+ api/index
-Index
-=====
-* :ref:`genindex`
+Examples
+========
+
+[create links with short descriptions to the various examples pages here]
+
+.. toctree::
+ :maxdepth: 2
+
+ examples/index
+
+
+Meta
+====
+
+:doc:`doc_conventions`
+
+.. toctree::
+ :maxdepth: 2
+ :hidden:
+ :caption: Meta
+
+ doc_conventions
+ copyright
+
+
+To Be Integrated
+================
+
+Files from old documentation to be integrated into new structure
+
+* :doc:`freefeatures`
+* :doc:`integrating`
+* :doc:`settingchanges`
+* :doc:`unfreefeatures`
+
+.. toctree::
+ :maxdepth: 2
+ :hidden:
+ :caption: To Be Integrated
+
+ freefeatures
+ integrating
+ settingchanges
+ unfreefeatures
diff --git a/docs/install.rst b/docs/install.rst
deleted file mode 100644
index 62765704..00000000
--- a/docs/install.rst
+++ /dev/null
@@ -1,155 +0,0 @@
-
-Installation Instructions
-=========================
-
-This section covers the basics of how to install, upgrade, and uninstall ``cmd2``.
-
-Installing
-----------
-First you need to make sure you have Python 3.5+, pip_, and setuptools_. Then you can just use pip to
-install from PyPI_.
-
-.. _pip: https://pypi.python.org/pypi/pip
-.. _setuptools: https://pypi.python.org/pypi/setuptools
-.. _PyPI: https://pypi.python.org/pypi
-
-.. note::
-
- Depending on how and where you have installed Python on your system and on what OS you are using, you may need to
- have administrator or root privileges to install Python packages. If this is the case, take the necessary steps
- required to run the commands in this section as root/admin, e.g.: on most Linux or Mac systems, you can precede them
- with ``sudo``::
-
- sudo pip install <package_name>
-
-
-Requirements for Installing
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-* If you have Python 3 >=3.5 installed from `python.org
- <https://www.python.org>`_, you will already have pip_ and
- setuptools_, but may need to upgrade to the latest versions:
-
- On Linux or OS X:
-
- ::
-
- pip install -U pip setuptools
-
-
- On Windows:
-
- ::
-
- python -m pip install -U pip setuptools
-
-
-.. _`pip_install`:
-
-Use pip for Installing
-~~~~~~~~~~~~~~~~~~~~~~
-
-pip_ is the recommended installer. Installing packages from PyPI_ with pip is easy::
-
- pip install cmd2
-
-This should also install the required 3rd-party dependencies, if necessary.
-
-
-.. _github:
-
-Install from GitHub using pip
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The latest version of ``cmd2`` can be installed directly from the master branch on GitHub using pip_::
-
- pip install -U git+git://github.com/python-cmd2/cmd2.git
-
-This should also install the required 3rd-party dependencies, if necessary.
-
-
-Install from Debian or Ubuntu repos
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We recommend installing from pip_, but if you wish to install from Debian or Ubuntu repos this can be done with
-apt-get.
-
-For Python 3::
-
- sudo apt-get install python3-cmd2
-
-This will also install the required 3rd-party dependencies.
-
-.. warning::
-
- Versions of ``cmd2`` before 0.7.0 should be considered to be of unstable "beta" quality and should not be relied upon
- for production use. If you cannot get a version >= 0.7 from your OS repository, then we recommend
- installing from either pip or GitHub - see :ref:`pip_install` or :ref:`github`.
-
-
-Deploy cmd2.py with your project
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-``cmd2`` is contained in a small number of Python files, which can be easily copied into your project. *The
-copyright and license notice must be retained*.
-
-This is an option suitable for advanced Python users. You can simply include the files within your project's hierarchy.
-If you want to modify ``cmd2``, this may be a reasonable option. Though, we encourage you to use stock ``cmd2`` and
-either composition or inheritance to achieve the same goal.
-
-This approach will obviously NOT automatically install the required 3rd-party dependencies, so you need to make sure
-the following Python packages are installed:
-
- * attrs
- * colorama
- * pyperclip
- * wcwidth
-
-On Windows, there is an additional dependency:
-
- * pyreadline
-
-
-Upgrading cmd2
---------------
-
-Upgrade an already installed ``cmd2`` to the latest version from PyPI_::
-
- pip install -U cmd2
-
-This will upgrade to the newest stable version of ``cmd2`` and will also upgrade any dependencies if necessary.
-
-
-Uninstalling cmd2
------------------
-If you wish to permanently uninstall ``cmd2``, this can also easily be done with pip_::
-
- pip uninstall cmd2
-
-
-Extra requirement for macOS
-===========================
-macOS comes with the `libedit <http://thrysoee.dk/editline/>`_ library which is similar, but not identical, to GNU Readline.
-Tab-completion for ``cmd2`` applications is only tested against GNU Readline.
-
-There are several ways GNU Readline can be installed within a Python environment on a Mac, detailed in the following subsections.
-
-gnureadline Python module
--------------------------
-Install the `gnureadline <https://pypi.python.org/pypi/gnureadline>`_ Python module which is statically linked against a specific compatible version of GNU Readline::
-
- pip install -U gnureadline
-
-readline via conda
-------------------
-Install the **readline** package using the ``conda`` package manager included with the Anaconda Python distribution::
-
- conda install readline
-
-readline via brew
------------------
-Install the **readline** package using the Homebrew package manager (compiles from source)::
-
- brew install openssl
- brew install pyenv
- brew install readline
-
-Then use pyenv to compile Python and link against the installed readline
diff --git a/docs/integrating.rst b/docs/integrating.rst
index bf79ee4e..9b0cf737 100644
--- a/docs/integrating.rst
+++ b/docs/integrating.rst
@@ -51,10 +51,10 @@ loop::
(Cmd)
You may need more control over command line arguments passed from the operating
-system shell. For example, you might have a command inside your ``cmd2`` program
-which itself accepts arguments, and maybe even option strings. Say you wanted to
-run the ``speak`` command from the operating system shell, but have it say it in
-pig latin::
+system shell. For example, you might have a command inside your ``cmd2``
+program which itself accepts arguments, and maybe even option strings. Say you
+wanted to run the ``speak`` command from the operating system shell, but have
+it say it in pig latin::
$ python example/example.py speak -p hello there
python example.py speak -p hello there
@@ -66,7 +66,8 @@ pig latin::
(Cmd)
Uh-oh, that's not what we wanted. ``cmd2`` treated ``-p``, ``hello``, and
-``there`` as commands, which don't exist in that program, thus the syntax errors.
+``there`` as commands, which don't exist in that program, thus the syntax
+errors.
There is an easy way around this, which is demonstrated in
``examples/cmd_as_argument.py``. By setting ``allow_cli_args=False`` you can so
@@ -85,8 +86,8 @@ Integrating cmd2 with event loops
Throughout this documentation we have focused on the **90%** use case, that is
the use case we believe around **90+%** of our user base is looking for. This
focuses on ease of use and the best out-of-the-box experience where developers
-get the most functionality for the least amount of effort. We are talking about
-running cmd2 applications with the ``cmdloop()`` method::
+get the most functionality for the least amount of effort. We are talking
+about running cmd2 applications with the ``cmdloop()`` method::
from cmd2 import Cmd
class App(Cmd):
@@ -142,7 +143,8 @@ The **onecmd_plus_hooks()** method will do the following to execute a single
#. Add statement to history
#. Call `do_command` method
#. Call methods registered with `register_postcmd_hook()`
-#. Call `postcmd(stop, statement)` - for backwards compatibility with ``cmd.Cmd``
+#. Call `postcmd(stop, statement)` - for backwards compatibility with
+ ``cmd.Cmd``
#. Stop timer and display the elapsed time
#. Stop redirecting output if it was redirected
#. Call methods registered with `register_cmdfinalization_hook()`
@@ -159,3 +161,4 @@ with several disadvantages, including:
Here is a little more info on ``runcmds_plus_hooks``:
.. automethod:: cmd2.cmd2.Cmd.runcmds_plus_hooks
+ :noindex:
diff --git a/docs/migrating/free_features.rst b/docs/migrating/free_features.rst
new file mode 100644
index 00000000..afb29fc3
--- /dev/null
+++ b/docs/migrating/free_features.rst
@@ -0,0 +1,5 @@
+What you get for free
+=====================
+
+A brief list (with links to details) of major features you get for free once
+you migrate.
diff --git a/docs/migrating/incompatibilities.rst b/docs/migrating/incompatibilities.rst
new file mode 100644
index 00000000..7a8a5aba
--- /dev/null
+++ b/docs/migrating/incompatibilities.rst
@@ -0,0 +1,22 @@
+Incompatibilities
+=================
+
+.. _cmd: https://docs.python.org/3/library/cmd.html
+
+``cmd2`` strives to be drop-in compatible with cmd_, however there are a few
+things that are not.
+
+
+cmd.emptyline()
+---------------
+
+The `cmd.emptyline()
+<https://docs.python.org/3/library/cmd.html#cmd.Cmd.emptyline>`_ function is
+called when an empty line is entered in response to the prompt. By default, in
+cmd_ if this method is not overridden, it repeats and executes the last
+nonempty command entered. However, no end user we have encountered views this
+as expected or desirable default behavior. Thus, the default behavior in
+``cmd2`` is to simply go to the next line and issue the prompt again. At this
+time, cmd2 completely ignores empty lines and the base class cmd.emptyline()
+method never gets called and thus the emptyline() behavior cannot be
+overridden.
diff --git a/docs/migrating/index.rst b/docs/migrating/index.rst
new file mode 100644
index 00000000..9c01b1bd
--- /dev/null
+++ b/docs/migrating/index.rst
@@ -0,0 +1,11 @@
+Migrating from cmd
+==================
+
+.. toctree::
+ :maxdepth: 1
+
+ why
+ incompatibilities
+ minimum
+ free_features
+ nextsteps
diff --git a/docs/migrating/minimum.rst b/docs/migrating/minimum.rst
new file mode 100644
index 00000000..d604cf7a
--- /dev/null
+++ b/docs/migrating/minimum.rst
@@ -0,0 +1,4 @@
+Minimum required changes
+========================
+
+The minimum required changes to move to cmd2
diff --git a/docs/migrating/nextsteps.rst b/docs/migrating/nextsteps.rst
new file mode 100644
index 00000000..3f560501
--- /dev/null
+++ b/docs/migrating/nextsteps.rst
@@ -0,0 +1,6 @@
+Next Steps
+==========
+
+What features (with links to details) are easy to implement next
+
+:doc:`Help <../features/help>`
diff --git a/docs/migrating/why.rst b/docs/migrating/why.rst
new file mode 100644
index 00000000..71017d89
--- /dev/null
+++ b/docs/migrating/why.rst
@@ -0,0 +1,25 @@
+Why Migrate to cmd2
+===================
+
+.. _cmd: https://docs.python.org/3/library/cmd.html
+
+``cmd2`` is an extension of cmd_, the Python Standard Library's module for
+creating simple interactive command-line applications.
+
+``cmd2`` can be used as a drop-in replacement for cmd_. Simply importing
+``cmd2`` in place of cmd_ will add many features to an application without any
+further modifications.
+
+Understanding the use of cmd_ is the first step in learning the use of
+``cmd2``. Once you have read the cmd_ docs, return here to learn the ways that
+``cmd2`` differs from cmd_.
+
+
+Describe why you would want to migrate, and the benefits of doing so
+
+Unicode
+
+features
+
+active community
+
diff --git a/docs/overview.rst b/docs/overview.rst
deleted file mode 100644
index 75b8caa9..00000000
--- a/docs/overview.rst
+++ /dev/null
@@ -1,27 +0,0 @@
-
-========
-Overview
-========
-
-``cmd2`` is an extension of cmd_, the Python Standard Library's module for
-creating simple interactive command-line applications.
-
-``cmd2`` can be used as a drop-in replacement for cmd_. Simply importing ``cmd2``
-in place of cmd_ will add many features to an application without any further
-modifications.
-
-Understanding the use of cmd_ is the first step in learning the use of ``cmd2``.
-Once you have read the cmd_ docs, return here to learn the ways that ``cmd2``
-differs from cmd_.
-
-.. note::
-
- ``cmd2`` is not quite a drop-in replacement for cmd_.
- The `cmd.emptyline() <https://docs.python.org/3/library/cmd.html#cmd.Cmd.emptyline>`_ function is called
- when an empty line is entered in response to the prompt. By default, in cmd_ if this method is not overridden, it
- repeats and executes the last nonempty command entered. However, no end user we have encountered views this as
- expected or desirable default behavior. Thus, the default behavior in ``cmd2`` is to simply go to the next line
- and issue the prompt again. At this time, cmd2 completely ignores empty lines and the base class cmd.emptyline()
- method never gets called and thus the emptyline() behavior cannot be overridden.
-
-.. _cmd: https://docs.python.org/3/library/cmd.html
diff --git a/docs/overview/alternatives.rst b/docs/overview/alternatives.rst
new file mode 100644
index 00000000..63977334
--- /dev/null
+++ b/docs/overview/alternatives.rst
@@ -0,0 +1,54 @@
+Alternatives
+============
+
+For programs that do not interact with the user in a continuous loop - programs
+that simply accept a set of arguments from the command line, return results,
+and do not keep the user within the program's environment - all you need are
+sys_\ .argv (the command-line arguments) and argparse_ (for parsing UNIX-style
+options and flags). Though some people may prefer docopt_ or click_ to
+argparse_.
+
+.. _sys: https://docs.python.org/3/library/sys.html
+.. _argparse: https://docs.python.org/3/library/argparse.html
+.. _docopt: https://pypi.python.org/pypi/docopt
+.. _click: http://click.pocoo.org
+
+
+The curses_ module produces applications that interact via a plaintext terminal
+window, but are not limited to simple text input and output; they can paint the
+screen with options that are selected from using the cursor keys. However,
+programming a curses_-based application is not as straightforward as using
+cmd_.
+
+.. _curses: https://docs.python.org/3/library/curses.html
+.. _cmd: https://docs.python.org/3/library/cmd.html
+
+Several Python packages exist for building interactive command-line
+applications approximately similar in concept to cmd_ applications. None of
+them share ``cmd2``'s close ties to cmd_, but they may be worth investigating
+nonetheless. Two of the most mature and full featured are:
+
+ * `Python Prompt Toolkit`_
+ * Click_
+
+.. _`Python Prompt Toolkit`: https://github.com/jonathanslenders/python-prompt-toolkit
+
+`Python Prompt Toolkit`_ is a library for building powerful interactive command
+lines and terminal applications in Python. It provides a lot of advanced
+visual features like syntax highlighting, bottom bars, and the ability to
+create fullscreen apps.
+
+Click_ is a Python package for creating beautiful command line interfaces in a
+composable way with as little code as necessary. It is more geared towards
+command line utilities instead of command line interpreters, but it can be used
+for either.
+
+Getting a working command-interpreter application based on either `Python
+Prompt Toolkit`_ or Click_ requires a good deal more effort and boilerplate
+code than ``cmd2``. ``cmd2`` focuses on providing an excellent out-of-the-box
+experience with as many useful features as possible built in for free with as
+little work required on the developer's part as possible. We believe that
+``cmd2`` provides developers the easiest way to write a command-line
+interpreter, while allowing a good experience for end users. If you are
+seeking a visually richer end-user experience and don't mind investing more
+development time, we would recommend checking out `Python Prompt Toolkit`_.
diff --git a/docs/overview/index.rst b/docs/overview/index.rst
new file mode 100644
index 00000000..231191c1
--- /dev/null
+++ b/docs/overview/index.rst
@@ -0,0 +1,15 @@
+Getting Started
+===============
+
+.. toctree::
+ :maxdepth: 1
+ :hidden:
+
+ installation
+ ../examples/first_app
+ integrating
+ alternatives
+ resources
+
+
+.. include:: summary.rst
diff --git a/docs/overview/installation.rst b/docs/overview/installation.rst
new file mode 100644
index 00000000..9f1209b6
--- /dev/null
+++ b/docs/overview/installation.rst
@@ -0,0 +1,162 @@
+
+Installation Instructions
+=========================
+
+
+.. _pip: https://pypi.python.org/pypi/pip
+.. _setuptools: https://pypi.python.org/pypi/setuptools
+.. _PyPI: https://pypi.python.org/pypi
+
+``cmd2`` works on Linux, macOS, and Windows. It requires Python 3.5 or
+higher, pip_, and setuptools_. If you've got all that, then you can just:
+
+.. code-block:: shell
+
+ $ pip install cmd2
+
+.. note::
+
+ Depending on how and where you have installed Python on your system and on
+ what OS you are using, you may need to have administrator or root privileges
+ to install Python packages. If this is the case, take the necessary steps
+ required to run the commands in this section as root/admin, e.g.: on most
+ Linux or Mac systems, you can precede them with ``sudo``:
+
+ .. code-block:: shell
+
+ $ sudo pip install <package_name>
+
+
+Prerequisites
+-------------
+
+If you have Python 3 >=3.5 installed from `python.org
+<https://www.python.org>`_, you will already have pip_ and setuptools_, but may
+need to upgrade to the latest versions:
+
+ On Linux or OS X:
+
+ .. code-block:: shell
+
+ $ pip install -U pip setuptools
+
+
+ On Windows:
+
+ .. code-block:: shell
+
+ > python -m pip install -U pip setuptools
+
+
+.. _`pip_install`:
+
+Install from PyPI
+-----------------
+
+pip_ is the recommended installer. Installing packages from PyPI_ with pip is
+easy:
+
+.. code-block:: shell
+
+ $ pip install cmd2
+
+This will install the required 3rd-party dependencies, if necessary.
+
+
+.. _github:
+
+Install from GitHub
+-------------------
+
+The latest version of ``cmd2`` can be installed directly from the master branch
+on GitHub using pip_:
+
+.. code-block:: shell
+
+ $ pip install -U git+git://github.com/python-cmd2/cmd2.git
+
+
+Install from Debian or Ubuntu repos
+-----------------------------------
+
+We recommend installing from pip_, but if you wish to install from Debian or
+Ubuntu repos this can be done with apt-get.
+
+For Python 3::
+
+ $ sudo apt-get install python3-cmd2
+
+This will also install the required 3rd-party dependencies.
+
+.. warning::
+
+ Versions of ``cmd2`` before 0.7.0 should be considered to be of unstable
+ "beta" quality and should not be relied upon for production use. If you
+ cannot get a version >= 0.7 from your OS repository, then we recommend
+ installing from either pip or GitHub - see :ref:`pip_install` or
+ :ref:`github`.
+
+
+Upgrading cmd2
+--------------
+
+Upgrade an already installed ``cmd2`` to the latest version from PyPI_::
+
+ pip install -U cmd2
+
+This will upgrade to the newest stable version of ``cmd2`` and will also
+upgrade any dependencies if necessary.
+
+
+Uninstalling cmd2
+-----------------
+If you wish to permanently uninstall ``cmd2``, this can also easily be done with pip_::
+
+ $ pip uninstall cmd2
+
+
+macOS Considerations
+--------------------
+
+macOS comes with the `libedit <http://thrysoee.dk/editline/>`_ library which is
+similar, but not identical, to GNU Readline. Tab-completion for ``cmd2``
+applications is only tested against GNU Readline.
+
+There are several ways GNU Readline can be installed within a Python
+environment on a Mac, detailed in the following subsections.
+
+
+gnureadline Python module
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Install the `gnureadline <https://pypi.python.org/pypi/gnureadline>`_ Python module which is statically linked against a specific compatible version of GNU Readline:
+
+.. code-block:: shell
+
+ $ pip install -U gnureadline
+
+
+readline via conda
+~~~~~~~~~~~~~~~~~~
+
+Install the **readline** package using the ``conda`` package manager included
+with the Anaconda Python distribution:
+
+.. code-block:: shell
+
+ $ conda install readline
+
+
+readline via brew
+~~~~~~~~~~~~~~~~~
+
+Install the **readline** package using the Homebrew package manager (compiles
+from source):
+
+.. code-block:: shell
+
+ $ brew install openssl
+ $ brew install pyenv
+ $ brew install readline
+
+Then use pyenv to compile Python and link against the installed readline
diff --git a/docs/overview/integrating.rst b/docs/overview/integrating.rst
new file mode 100644
index 00000000..e28df1a7
--- /dev/null
+++ b/docs/overview/integrating.rst
@@ -0,0 +1,32 @@
+Integrate cmd2 Into Your Project
+================================
+
+Once installed, you will want to ensure that your project's dependencies
+include ``cmd2``. Make sure your ``setup.py`` includes the following::
+
+ install_requires=[
+ 'cmd2>=1,<2',
+ ]
+
+The ``cmd2`` project uses `Semantic Versioning <https://semver.org>`_, which
+means that any incompatible API changes will be release with a new major
+version number. We recommend that you follow the advice given by the Python
+Packaging User Guide related to `install_requires
+<https://packaging.python.org/discussions/install-requires-vs-requirements/>`_.
+By setting an upper bound on the allowed version, you can ensure that your
+project does not inadvertently get installed with an incompatible future
+version of ``cmd2``.
+
+
+Windows Considerations
+-------------------------------
+
+If you would like to use :ref:`features/completion:Completion`, and you want
+your application to run on Windows, you will need to ensure you install the
+``pyreadline`` package. Make sure to include the following in your
+``setup.py``::
+
+ install_requires=[
+ 'cmd2>=1,<2',
+ ":sys_platform=='win32'": ['pyreadline'],
+ ]
diff --git a/docs/overview/resources.rst b/docs/overview/resources.rst
new file mode 100644
index 00000000..487ac316
--- /dev/null
+++ b/docs/overview/resources.rst
@@ -0,0 +1,13 @@
+Resources
+=========
+
+.. _cmd: https://docs.python.org/3/library/cmd.html
+.. _`cmd2 project page`: https://github.com/python-cmd2/cmd2
+.. _`project bug tracker`: https://github.com/python-cmd2/cmd2/issues
+
+Project related links and other resources:
+
+* cmd_
+* `cmd2 project page`_
+* `project bug tracker`_
+* Florida PyCon 2017: `slides <https://docs.google.com/presentation/d/1LRmpfBt3V-pYQfgQHdczf16F3hcXmhK83tl77R6IJtE>`_, `video <https://www.youtube.com/watch?v=6m0RdpITaeY>`_
diff --git a/docs/overview/summary.rst b/docs/overview/summary.rst
new file mode 100644
index 00000000..9285014c
--- /dev/null
+++ b/docs/overview/summary.rst
@@ -0,0 +1,22 @@
+
+.. _cmd: https://docs.python.org/3/library/cmd.html
+
+Building a new `REPL <https://en.wikipedia.org/wiki/Read–eval–print_loop>`_ or
+`Command Line Interface <https://en.wikipedia.org/wiki/Command-line_interface>`_
+application?
+
+Already built an application that uses cmd_ from the python standard library
+and want to add more functionality with very little work?
+
+``cmd2`` is a powerful python library for building command line applications.
+Start here to find out if this library is a good fit for your needs.
+
+* :ref:`overview/installation:Installation Instructions` - how to install
+ ``cmd2`` and associated optional dependencies
+* :ref:`examples/first_app:First Application` - a sample application showing 8
+ key features of ``cmd2``
+* :ref:`overview/integrating:Integrate cmd2 Into Your Project` - adding
+ ``cmd2`` to your project
+* :ref:`overview/alternatives:Alternatives` - other python packages that might
+ meet your needs
+* :ref:`overview/resources:Resources` - related links and other materials
diff --git a/docs/settingchanges.rst b/docs/settingchanges.rst
index 81f025a7..d4f277fd 100644
--- a/docs/settingchanges.rst
+++ b/docs/settingchanges.rst
@@ -12,9 +12,10 @@ its name is included in the dictionary ``app.settable``.
Shortcuts
=========
-Command shortcuts for long command names and common commands can make life more convenient for your users.
-Shortcuts are used without a space separating them from their arguments, like ``!ls``. By default, the
-following shortcuts are defined:
+Command shortcuts for long command names and common commands can make life more
+convenient for your users. Shortcuts are used without a space separating them
+from their arguments, like ``!ls``. By default, the following shortcuts are
+defined:
``?``
help
@@ -39,17 +40,19 @@ To define more shortcuts, update the dict ``App.shortcuts`` with the
.. warning::
- Shortcuts need to be created by updating the ``shortcuts`` dictionary attribute prior to calling the
- ``cmd2.Cmd`` super class ``__init__()`` method. Moreover, that super class init method needs to be called after
- updating the ``shortcuts`` attribute This warning applies in general to many other attributes which are not
- settable at runtime.
+ Shortcuts need to be created by updating the ``shortcuts`` dictionary
+ attribute prior to calling the ``cmd2.Cmd`` super class ``__init__()``
+ method. Moreover, that super class init method needs to be called after
+ updating the ``shortcuts`` attribute This warning applies in general to many
+ other attributes which are not settable at runtime.
Aliases
=======
-In addition to shortcuts, ``cmd2`` provides a full alias feature via the ``alias`` command. Aliases work in a similar
-fashion to aliases in the Bash shell.
+In addition to shortcuts, ``cmd2`` provides a full alias feature via the
+``alias`` command. Aliases work in a similar fashion to aliases in the Bash
+shell.
The syntax to create an alias is: ``alias create name command [args]``.
@@ -57,9 +60,10 @@ The syntax to create an alias is: ``alias create name command [args]``.
For more details run: ``help alias create``
-Use ``alias list`` to see all or some of your aliases. The output of this command displays your aliases using the same command that
-was used to create them. Therefore you can place this output in a ``cmd2`` startup script to recreate your aliases each time
-you start the application
+Use ``alias list`` to see all or some of your aliases. The output of this
+command displays your aliases using the same command that was used to create
+them. Therefore you can place this output in a ``cmd2`` startup script to
+recreate your aliases each time you start the application
Ex: ``alias list``
@@ -72,8 +76,9 @@ For more details run: ``help alias delete``
Macros
======
-``cmd2`` provides a feature that is similar to aliases called macros. The major difference between macros and aliases
-is that macros can contain argument placeholders. Arguments are expressed when creating a macro using {#} notation
+``cmd2`` provides a feature that is similar to aliases called macros. The major
+difference between macros and aliases is that macros can contain argument
+placeholders. Arguments are expressed when creating a macro using {#} notation
where {1} means the first argument.
The following creates a macro called my_macro that expects two arguments:
@@ -87,8 +92,9 @@ command is run. For example:
For more details run: ``help macro create``
-The macro command has ``list`` and ``delete`` subcommands that function identically to the alias subcommands of the
-same name. Like aliases, macros can be created via a ``cmd2`` startup script to preserve them across application
+The macro command has ``list`` and ``delete`` subcommands that function
+identically to the alias subcommands of the same name. Like aliases, macros can
+be created via a ``cmd2`` startup script to preserve them across application
sessions.
For more details on listing macros run: ``help macro list``
@@ -99,20 +105,18 @@ For more details on deleting macros run: ``help macro delete``
Default to shell
================
-Every ``cmd2`` application can execute operating-system
-level (shell) commands with ``shell`` or a ``!``
-shortcut::
+Every ``cmd2`` application can execute operating-system level (shell) commands
+with ``shell`` or a ``!`` shortcut::
(Cmd) shell which python
/usr/bin/python
(Cmd) !which python
/usr/bin/python
-However, if the parameter ``default_to_shell`` is
-``True``, then *every* command will be attempted on
-the operating system. Only if that attempt fails
-(i.e., produces a nonzero return value) will the
-application's own ``default`` method be called.
+However, if the parameter ``default_to_shell`` is ``True``, then *every*
+command will be attempted on the operating system. Only if that attempt fails
+(i.e., produces a nonzero return value) will the application's own ``default``
+method be called.
::
@@ -125,11 +129,10 @@ application's own ``default`` method be called.
Quit on SIGINT
==============
-On many shells, SIGINT (most often triggered by the user
-pressing Ctrl+C) only cancels the current line, not the
-entire command loop. By default, a ``cmd2`` application will quit
-on receiving this signal. However, if ``quit_on_sigint`` is
-set to ``False``, then the current line will simply be cancelled.
+On many shells, SIGINT (most often triggered by the user pressing Ctrl+C) only
+cancels the current line, not the entire command loop. By default, a ``cmd2``
+application will quit on receiving this signal. However, if ``quit_on_sigint``
+is set to ``False``, then the current line will simply be cancelled.
::
@@ -144,21 +147,20 @@ set to ``False``, then the current line will simply be cancelled.
Timing
======
-Setting ``App.timing`` to ``True`` outputs timing data after
-every application command is executed. |settable|
+Setting ``App.timing`` to ``True`` outputs timing data after every application
+command is executed. |settable|
Echo
====
-If ``True``, each command the user issues will be repeated
-to the screen before it is executed. This is particularly
-useful when running scripts.
+If ``True``, each command the user issues will be repeated to the screen before
+it is executed. This is particularly useful when running scripts.
Debug
=====
-Setting ``App.debug`` to ``True`` will produce detailed error stacks
-whenever the application generates an error. |settable|
+Setting ``App.debug`` to ``True`` will produce detailed error stacks whenever
+the application generates an error. |settable|
.. |settable| replace:: The user can ``set`` this parameter
during application execution.
@@ -185,7 +187,8 @@ with::
quiet: False # Don't print nonessential feedback
timing: False # Report execution times
-Any of these user-settable parameters can be set while running your app with the ``set`` command like so::
+Any of these user-settable parameters can be set while running your app with
+the ``set`` command like so::
set allow_ansi Never
diff --git a/docs/unfreefeatures.rst b/docs/unfreefeatures.rst
index 02e1b981..19c4e547 100644
--- a/docs/unfreefeatures.rst
+++ b/docs/unfreefeatures.rst
@@ -1,33 +1,12 @@
-======================================
Features requiring application changes
======================================
-Multiline commands
-==================
-
-Command input may span multiple lines for the
-commands whose names are listed in the
-``multiline_commands`` argument to ``cmd2.Cmd.__init__()``. These
-commands will be executed only
-after the user has entered a *terminator*.
-By default, the command terminator is
-``;``; specifying the ``terminators`` optional argument to ``cmd2.Cmd.__init__()`` allows different
-terminators. A blank line
-is *always* considered a command terminator
-(cannot be overridden).
-
-In multiline commands, output redirection characters
-like ``>`` and ``|`` are part of the command
-arguments unless they appear after the terminator.
-
Parsed statements
-=================
+-----------------
-``cmd2`` passes ``arg`` to a ``do_`` method (or
-``default``) as a Statement, a subclass of
-string that includes many attributes of the parsed
-input:
+``cmd2`` passes ``arg`` to a ``do_`` method (or ``default``) as a Statement, a
+subclass of string that includes many attributes of the parsed input:
command
Name of the command called
@@ -55,35 +34,32 @@ terminator
-If ``Statement`` does not contain an attribute,
-querying for it will return ``None``.
+If ``Statement`` does not contain an attribute, querying for it will return
+``None``.
-(Getting ``arg`` as a ``Statement`` is
-technically "free", in that it requires no application
-changes from the cmd_ standard, but there will
-be no result unless you change your application
-to *use* any of the additional attributes.)
+(Getting ``arg`` as a ``Statement`` is technically "free", in that it requires
+no application changes from the cmd_ standard, but there will be no result
+unless you change your application to *use* any of the additional attributes.)
.. _cmd: https://docs.python.org/3/library/cmd.html
Environment parameters
-======================
+----------------------
Your application can define user-settable parameters which your code can
-reference. First create a class attribute with the default value. Then
-update the ``settable`` dictionary with your setting name and a short
-description before you initialize the superclass. Here's an example, from
+reference. First create a class attribute with the default value. Then update
+the ``settable`` dictionary with your setting name and a short description
+before you initialize the superclass. Here's an example, from
``examples/environment.py``:
.. literalinclude:: ../examples/environment.py
-If you want to be notified when a setting changes (as we do above), then
-define a method ``_onchange_{setting}()``. This method will be called after
-the user changes a setting, and will receive both the old value and the new
-value.
+If you want to be notified when a setting changes (as we do above), then define
+a method ``_onchange_{setting}()``. This method will be called after the user
+changes a setting, and will receive both the old value and the new value.
-.. code-block:: none
+.. code-block:: text
(Cmd) set --long | grep sunny
sunny: False # Is it sunny outside?
@@ -108,24 +84,25 @@ value.
Commands with flags
===================
-All ``do_`` methods are responsible for interpreting
-the arguments passed to them. However, ``cmd2`` lets
-a ``do_`` methods accept Unix-style *flags*. It uses argparse_
-to parse the flags, and they work the same way as for
-that module.
+All ``do_`` methods are responsible for interpreting the arguments passed to
+them. However, ``cmd2`` lets a ``do_`` methods accept Unix-style *flags*. It
+uses argparse_ to parse the flags, and they work the same way as for that
+module.
-``cmd2`` defines a few decorators which change the behavior of
-how arguments get parsed for and passed to a ``do_`` method. See the section :ref:`decorators` for more information.
+``cmd2`` defines a few decorators which change the behavior of how arguments
+get parsed for and passed to a ``do_`` method. See the section
+:ref:`decorators` for more information.
.. _argparse: https://docs.python.org/3/library/argparse.html
poutput, pfeedback, perror, ppaged
==================================
-Standard ``cmd`` applications produce their output with ``self.stdout.write('output')`` (or with ``print``,
-but ``print`` decreases output flexibility). ``cmd2`` applications can use
-``self.poutput('output')``, ``self.pfeedback('message')``, ``self.perror('errmsg')``, and ``self.ppaged('text')``
-instead. These methods have these advantages:
+Standard ``cmd`` applications produce their output with
+``self.stdout.write('output')`` (or with ``print``, but ``print`` decreases
+output flexibility). ``cmd2`` applications can use ``self.poutput('output')``,
+``self.pfeedback('message')``, ``self.perror('errmsg')``, and
+``self.ppaged('text')`` instead. These methods have these advantages:
- Handle output redirection to file and/or pipe appropriately
- More concise
@@ -133,16 +110,20 @@ instead. These methods have these advantages:
- Option to display long output using a pager via ``ppaged()``
.. automethod:: cmd2.cmd2.Cmd.poutput
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.perror
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.pfeedback
+ :noindex:
.. automethod:: cmd2.cmd2.Cmd.ppaged
+ :noindex:
Colored Output
==============
-The output methods in the previous section all honor the ``allow_ansi`` setting,
-which has three possible values:
+The output methods in the previous section all honor the ``allow_ansi``
+setting, which has three possible values:
Never
poutput(), pfeedback(), and ppaged() strip all ANSI escape sequences
@@ -150,16 +131,18 @@ Never
Terminal
(the default value) poutput(), pfeedback(), and ppaged() do not strip any
- ANSI escape sequences when the output is a terminal, but if the output is
- a pipe or a file the escape sequences are stripped. If you want colorized
+ ANSI escape sequences when the output is a terminal, but if the output is a
+ pipe or a file the escape sequences are stripped. If you want colorized
output you must add ANSI escape sequences using either cmd2's internal ansi
- module or another color library such as `plumbum.colors`, `colorama`, or `colored`.
+ module or another color library such as `plumbum.colors`, `colorama`, or
+ `colored`.
Always
poutput(), pfeedback(), and ppaged() never strip ANSI escape sequences,
regardless of the output destination
-Colored and otherwise styled output can be generated using the `ansi.style()` function:
+Colored and otherwise styled output can be generated using the `ansi.style()`
+function:
.. automethod:: cmd2.ansi.style
@@ -174,8 +157,8 @@ any output. If ``quiet`` is ``False``, then the output will be produced. If
``quiet`` is ``True``, no output will be produced.
This makes ``self.pfeedback()`` useful for non-essential output like status
-messages. Users can control whether they would like to see these messages by changing
-the value of the ``quiet`` setting.
+messages. Users can control whether they would like to see these messages by
+changing the value of the ``quiet`` setting.
select
@@ -183,9 +166,11 @@ select
Presents numbered options to user, as bash ``select``.
-``app.select`` is called from within a method (not by the user directly; it is ``app.select``, not ``app.do_select``).
+``app.select`` is called from within a method (not by the user directly; it is
+``app.select``, not ``app.do_select``).
.. automethod:: cmd2.cmd2.Cmd.select
+ :noindex:
::
@@ -206,179 +191,22 @@ Presents numbered options to user, as bash ``select``.
Exit code to shell
==================
-The ``self.exit_code`` attribute of your ``cmd2`` application controls
-what exit code is returned from ``cmdloop()`` when it completes. It is your job to make sure that
-this exit code gets sent to the shell when your application exits by calling ``sys.exit(app.cmdloop())``.
-
-
-Asynchronous Feedback
-=====================
-``cmd2`` provides two functions to provide asynchronous feedback to the user without interfering with
-the command line. This means the feedback is provided to the user when they are still entering text at
-the prompt. To use this functionality, the application must be running in a terminal that supports
-VT100 control characters and readline. Linux, Mac, and Windows 10 and greater all support these.
-
-async_alert()
- Used to display an important message to the user while they are at the prompt in between commands.
- To the user it appears as if an alert message is printed above the prompt and their current input
- text and cursor location is left alone.
-
-async_update_prompt()
- Updates the prompt while the user is still typing at it. This is good for alerting the user to system
- changes dynamically in between commands. For instance you could alter the color of the prompt to indicate
- a system status or increase a counter to report an event.
-
-``cmd2`` also provides a function to change the title of the terminal window. This feature requires the
-application be running in a terminal that supports VT100 control characters. Linux, Mac, and Windows 10 and
-greater all support these.
-
-set_window_title()
- Sets the terminal window title
-
-
-The easiest way to understand these functions is to see the AsyncPrinting_ example for a demonstration.
-
-.. _AsyncPrinting: https://github.com/python-cmd2/cmd2/blob/master/examples/async_printing.py
-
-
-Grouping Commands
-=================
-
-By default, the ``help`` command displays::
-
- Documented commands (type help <topic>):
- ========================================
- alias help ipy py run_pyscript set shortcuts
- edit history macro quit run_script shell
-
-If you have a large number of commands, you can optionally group your commands into categories.
-Here's the output from the example ``help_categories.py``::
-
- Documented commands (type help <topic>):
-
- Application Management
- ======================
- deploy findleakers redeploy sessions stop
- expire list restart start undeploy
-
- Command Management
- ==================
- disable_commands enable_commands
-
- Connecting
- ==========
- connect which
-
- Server Information
- ==================
- resources serverinfo sslconnectorciphers status thread_dump vminfo
-
- Other
- =====
- alias edit history py run_pyscript set shortcuts
- config help macro quit run_script shell version
-
-There are 2 methods of specifying command categories, using the ``@with_category`` decorator or with the
-``categorize()`` function. Once a single command category is detected, the help output switches to a categorized
-mode of display. All commands with an explicit category defined default to the category `Other`.
-
-Using the ``@with_category`` decorator::
-
- @with_category(CMD_CAT_CONNECTING)
- def do_which(self, _):
- """Which command"""
- self.poutput('Which')
-
-Using the ``categorize()`` function:
-
- You can call with a single function::
-
- def do_connect(self, _):
- """Connect command"""
- self.poutput('Connect')
-
- # Tag the above command functions under the category Connecting
- categorize(do_connect, CMD_CAT_CONNECTING)
-
- Or with an Iterable container of functions::
-
- def do_undeploy(self, _):
- """Undeploy command"""
- self.poutput('Undeploy')
-
- def do_stop(self, _):
- """Stop command"""
- self.poutput('Stop')
-
- def do_findleakers(self, _):
- """Find Leakers command"""
- self.poutput('Find Leakers')
-
- # Tag the above command functions under the category Application Management
- categorize((do_undeploy,
- do_stop,
- do_findleakers), CMD_CAT_APP_MGMT)
-
-The ``help`` command also has a verbose option (``help -v`` or ``help --verbose``) that combines
-the help categories with per-command Help Messages::
- Documented commands (type help <topic>):
-
- Application Management
- ================================================================================
- deploy Deploy command
- expire Expire command
- findleakers Find Leakers command
- list List command
- redeploy Redeploy command
- restart usage: restart [-h] {now,later,sometime,whenever}
- sessions Sessions command
- start Start command
- stop Stop command
- undeploy Undeploy command
-
- Connecting
- ================================================================================
- connect Connect command
- which Which command
-
- Server Information
- ================================================================================
- resources Resources command
- serverinfo Server Info command
- sslconnectorciphers SSL Connector Ciphers command is an example of a command that contains
- multiple lines of help information for the user. Each line of help in a
- contiguous set of lines will be printed and aligned in the verbose output
- provided with 'help --verbose'
- status Status command
- thread_dump Thread Dump command
- vminfo VM Info command
-
- Other
- ================================================================================
- alias Define or display aliases
- config Config command
- edit Edit a file in a text editor
- help List available commands with "help" or detailed help with "help cmd"
- history usage: history [-h] [-r | -e | -s | -o FILE | -t TRANSCRIPT] [arg]
- py Invoke python command, shell, or script
- quit Exits this application
- run_pyscript Runs a python script file inside the console
- run_script Runs commands in script file that is encoded as either ASCII or UTF-8 text
- set usage: set [-h] [-a] [-l] [settable [settable ...]]
- shell Execute a command as if at the OS prompt
- shortcuts Lists shortcuts available
- unalias Unsets aliases
- version Version command
+The ``self.exit_code`` attribute of your ``cmd2`` application controls what
+exit code is returned from ``cmdloop()`` when it completes. It is your job to
+make sure that this exit code gets sent to the shell when your application
+exits by calling ``sys.exit(app.cmdloop())``.
Disabling Commands
==================
-``cmd2`` supports disabling commands during runtime. This is useful if certain commands should only be available
-when the application is in a specific state. When a command is disabled, it will not show up in the help menu or
-tab complete. If a user tries to run the command, a command-specific message supplied by the developer will be
-printed. The following functions support this feature.
+``cmd2`` supports disabling commands during runtime. This is useful if certain
+commands should only be available when the application is in a specific state.
+When a command is disabled, it will not show up in the help menu or tab
+complete. If a user tries to run the command, a command-specific message
+supplied by the developer will be printed. The following functions support this
+feature.
enable_command()
Enable an individual command
@@ -387,16 +215,17 @@ enable_category()
Enable an entire category of commands
disable_command()
- Disable an individual command and set the message that will print when this command is run or help is called
- on it while disabled
+ Disable an individual command and set the message that will print when this
+ command is run or help is called on it while disabled
disable_category()
- Disable an entire category of commands and set the message that will print when anything in this category is
- run or help is called on it while disabled
+ Disable an entire category of commands and set the message that will print
+ when anything in this category is run or help is called on it while
+ disabled
See the definitions of these functions for descriptions of their arguments.
-See the ``do_enable_commands()`` and ``do_disable_commands()`` functions in the HelpCategories_ example for
-a demonstration.
+See the ``do_enable_commands()`` and ``do_disable_commands()`` functions in the
+HelpCategories_ example for a demonstration.
.. _HelpCategories: https://github.com/python-cmd2/cmd2/blob/master/examples/help_categories.py